From 2c5cc34c836733f502e1d3983f9c4a06280bb4c0 Mon Sep 17 00:00:00 2001 From: Fergie McDowall Date: Mon, 9 Oct 2017 15:34:50 +0200 Subject: [PATCH] build(dist): dist file is built every time 'npm test' is run dist file is built every time 'npm test' is run --- dist/search-index.js | 47259 +++++++++++++++----------------- dist/search-index.min.js | 16 +- docs/demo/search-index.min.js | 16 +- package-lock.json | 50 +- package.json | 4 +- 5 files changed, 22162 insertions(+), 25183 deletions(-) diff --git a/dist/search-index.js b/dist/search-index.js index b05253db..d91e185b 100644 --- a/dist/search-index.js +++ b/dist/search-index.js @@ -1,504 +1,130 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=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=typeof require=="function"&&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}var i=typeof require=="function"&&require;for(var o=0;o]/, - stopwords: [], - weight: 0 + keySeparator: '○', + logLevel: 'error' }, options) options.log = bunyan.createLogger({ name: 'search-index', level: options.logLevel }) if (!options.indexes) { - const leveldown = require('leveldown') - levelup(options.indexPath || 'si', { + level(SearchIndex.options.indexPath || 'si', { valueEncoding: 'json', - db: leveldown + db: down }, function (err, db) { - options.indexes = db - done(err, options) + SearchIndex.options.indexes = db + return done(err, SearchIndex) }) } else { - done(null, options) + return done(null, SearchIndex) } } -},{"./lib/add.js":2,"./lib/delete.js":3,"./lib/replicate.js":4,"JSONStream":5,"async":6,"bunyan":7,"docproc":16,"leveldown":51,"levelup":60,"pumpify":73,"stream":223}],2:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') +},{"./siUtil.js":2,"bunyan":10,"leveldown":58,"levelup":71,"search-index-adder":104,"search-index-searcher":109}],2:[function(require,module,exports){ +module.exports = function(siOptions) { + var siUtil = {} -const emitIndexKeys = function (s) { - for (var key in s.deltaIndex) { - s.push({ - key: key, - value: s.deltaIndex[key] - }) + siUtil.countDocs = function (callback) { + var count = 0 + const gte = 'DOCUMENT' + siOptions.keySeparator + const lte = 'DOCUMENT' + siOptions.keySeparator + siOptions.keySeparator + siOptions.indexes.createReadStream({gte: gte, lte: lte}) + .on('data', function (data) { + count++ + }) + .on('error', function (err) { + return callback(err, null) + }) + .on('end', function () { + return callback(null, count) + }) } - s.deltaIndex = {} -} -const IndexBatch = function (indexer) { - this.indexer = indexer - this.deltaIndex = {} - Transform.call(this, { objectMode: true }) -} -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) { - if (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] - var tfKeyName = 'TF' + sep + fieldName + sep + token - var 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) + siUtil.close = function (callback) { + siOptions.indexes.close(function (err) { + while (!siOptions.indexes.isClosed()) { + //log not always working here- investigate + if (siOptions.log) siOptions.log.info('closing...') } - that.deltaIndex['DOCUMENT-VECTOR' + sep + fieldName + sep + ingestedDoc.id + sep] = - ingestedDoc.vector[fieldName] - } - // console.log(Object.keys(that.deltaIndex).length) - // console.log(that.batchOptions.batchSize) - var totalKeys = Object.keys(that.deltaIndex).length - if (totalKeys > that.indexer.options.batchSize) { - that.push({totalKeys: totalKeys}) - that.indexer.options.log.info( - 'deltaIndex is ' + totalKeys + ' long, emitting') - emitIndexKeys(that) - } - return end() - }) -} -IndexBatch.prototype._flush = function (end) { - // merge this index into main index - emitIndexKeys(this) - return end() + if (siOptions.indexes.isClosed()) { + if (siOptions.log) siOptions.log.info('closed...') + callback(err) + } + }) + } + + return siUtil } -},{"stream":223,"util":229}],3:[function(require,module,exports){ -// deletes all references to a document from the search index +},{}],3:[function(require,module,exports){ +(function (process,Buffer){ -const util = require('util') -const Transform = require('stream').Transform -// Remove all keys in DB -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) { - options.log.error(err, ' failed to empty index') - return callback(err) - }) - .on('end', function () { - options.indexes.batch(deleteOps, callback) - }) -} - -const DocVector = function (options) { - this.options = options - Transform.call(this, { objectMode: true }) -} -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 - var docKey = 'DOCUMENT' + sep + docId + sep - this.options.indexes.get(docKey, function (err, val) { - if (err) return end() - var docFields = Object.keys(val) - docFields.push('*') - docFields = docFields.map(function (item) { - return 'DOCUMENT-VECTOR' + sep + item + sep + docId + sep - }) - var i = 0 - // get value from db and push it to the stream - var pushValue = function (key) { - that.options.indexes.get(key, function (err, val) { - if (err) that.options.log.info(err) - if (i === docFields.length) return end() - that.push({ - key: key, - value: val, - lastPass: (++i === docFields.length) || false - }) - pushValue(docFields[i]) - }) - } - pushValue(docFields[0]) - }) -} - -const DBEntries = function (options) { - this.options = options - Transform.call(this, { objectMode: true }) -} -exports.DBEntries = DBEntries -util.inherits(DBEntries, Transform) -DBEntries.prototype._transform = function (vector, encoding, end) { - const sep = this.options.keySeparator - var that = this - var field = vector.key.split(sep)[1] - var docId = vector.key.split(sep)[2] - var vectorKeys = Object.keys(vector.value) - var i = 0 - var pushRecalibrationvalues = function (vec) { - that.push({ - key: 'TF' + sep + field + sep + vectorKeys[i], - value: docId - }) - that.push({ - key: 'DF' + sep + field + sep + vectorKeys[i], - value: docId - }) - if (++i === vectorKeys.length) { - that.push({key: vector.key}) - if (vector.lastPass === true) { - that.push({key: 'DOCUMENT' + sep + docId + sep}) - } - return end() - } else { - pushRecalibrationvalues(vector[vectorKeys[i]]) - } - } - pushRecalibrationvalues(vector[vectorKeys[0]]) - - // TODO: fix this! - // this.push({key: 'DOCUMENT-COUNT'}) -} - -const RecalibrateDB = function (options) { - this.options = options - this.batch = [] - Transform.call(this, { objectMode: true }) -} -exports.RecalibrateDB = RecalibrateDB -util.inherits(RecalibrateDB, Transform) -// todo: handle deletion of wildcards, and do batched deletes -RecalibrateDB.prototype._transform = function (dbEntry, encoding, end) { - const sep = this.options.keySeparator - var that = this - this.options.indexes.get(dbEntry.key, function (err, value) { - if (err) { - that.options.log.info(err) - } - // handle errors better - if (!value) value = [] - var docId = dbEntry.value - var dbInstruction = {} - dbInstruction.key = dbEntry.key - if (dbEntry.key.substring(0, 3) === 'TF' + sep) { - dbInstruction.value = value.filter(function (item) { - return (item[1] !== docId) - }) - if (dbInstruction.value.length === 0) { - dbInstruction.type = 'del' - } else { - dbInstruction.type = 'put' - } - that.batch.push(dbInstruction) - return end() - } else if (dbEntry.key.substring(0, 3) === 'DF' + sep) { - value.splice(value.indexOf(docId), 1) - dbInstruction.value = value - if (dbInstruction.value.length === 0) { - dbInstruction.type = 'del' - } else { - dbInstruction.type = 'put' - } - that.batch.push(dbInstruction) - return end() - } else if (dbEntry.key.substring(0, 16) === 'DOCUMENT-VECTOR' + sep) { - dbInstruction.type = 'del' - that.batch.push(dbInstruction) - return end() - } else if (dbEntry.key.substring(0, 9) === 'DOCUMENT' + sep) { - dbInstruction.type = 'del' - that.batch.push(dbInstruction) - // "DOCUMENT" should be the last instruction for the document - that.options.indexes.batch(that.batch, function (err) { - if (err) { - // then what? - } - that.batch = [] - return end() - }) - } - }) -} - -},{"stream":223,"util":229}],4:[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 - Writable.call(this, { objectMode: true }) -} -exports.DBWriteMergeStream = DBWriteMergeStream -util.inherits(DBWriteMergeStream, Writable) -DBWriteMergeStream.prototype._write = function (data, encoding, end) { - if (data.totalKeys) { - // this.push(data) - return end() - } - const sep = this.options.keySeparator - var that = this - this.options.indexes.get(data.key, function (err, val) { - err // do something with this error - var newVal - // concat to existing values (only if they exist) - 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 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() - } else if (data.key === 'DOCUMENT-COUNT') { - newVal = (+val) + (+data.value || 0) - } else { - newVal = data.value - } - that.options.indexes.put(data.key, newVal, function (err) { - err // do something with this error - // that.push(data) - end() - }) - }) -} - -const DBWriteCleanStream = function (options) { - this.currentBatch = [] - this.options = options - Transform.call(this, { objectMode: true }) -} -util.inherits(DBWriteCleanStream, Transform) -DBWriteCleanStream.prototype._transform = function (data, encoding, end) { - var that = this - this.currentBatch.push(data) - if (this.currentBatch.length % this.options.batchSize === 0) { - this.options.indexes.batch(this.currentBatch, function (err) { - // TODO: some nice error handling if things go wrong - err - that.push('indexing batch') - that.currentBatch = [] // reset batch - end() - }) - } else { - end() - } -} -DBWriteCleanStream.prototype._flush = function (end) { - var that = this - this.options.indexes.batch(this.currentBatch, function (err) { - // TODO: some nice error handling if things go wrong - err - that.push('remaining data indexed') - end() - }) -} -exports.DBWriteCleanStream = DBWriteCleanStream - -},{"stream":223,"util":229}],5:[function(require,module,exports){ -(function (process,Buffer){ - - -'use strict' +'use strict' var Parser = require('jsonparse') , through = require('through') @@ -751,665 +377,1159 @@ if(!module.parent && process.title !== 'browser') { }).call(this,require('_process'),require("buffer").Buffer) -},{"_process":206,"buffer":156,"jsonparse":38,"through":88}],6:[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 || {}))); -}(this, (function (exports) { 'use strict'; - -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]; - } - return newArr; -} +},{"_process":85,"buffer":9,"jsonparse":45,"through":152}],4:[function(require,module,exports){ +(function (global){ +'use strict'; -var initialParams = function (fn) { - return function (/*...args, callback*/) { - var args = slice(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; +// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true +/*! + * The buffer module from node.js, for the browser. * - * _.isObject(null); - * // => false + * @author Feross Aboukhadijeh + * @license MIT */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} - -var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; +function compare(a, b) { + if (a === b) { + return 0; + } -function fallback(fn) { - setTimeout(fn, 0); -} + var x = a.length; + var y = b.length; -function wrap(defer) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} - -var _defer; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); } -var setImmediate$1 = wrap(_defer); +// based on node assert, original notice: -/** - * 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, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @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)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return initialParams(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if (isObject(result) && typeof result.then === 'function') { - result.then(function(value) { - invokeCallback(callback, null, value); - }, function(err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); -} +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - setImmediate$1(rethrow, e); - } +var util = require('util/'); +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; +}()); +function pToString (obj) { + return Object.prototype.toString.call(obj); } - -function rethrow(error) { - throw error; +function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; } +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. -var supportsSymbol = typeof Symbol === 'function'; +var assert = module.exports = ok; -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; } +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; -function applyEach$1(eachfn) { - 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(fn).apply(that, args.concat(cb)); - }, callback); - }); - if (args.length) { - return go.apply(this, args); - } - else { - return go; - } - }; -} + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + this.stack = out; + } + } +}; -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); +} -/** Built-in value references. */ -var Symbol$1 = root.Symbol; +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. -/** Used for built-in method references. */ -var objectProto = Object.prototype; +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; -/** Built-in value references. */ -var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); } - return result; -} +}; -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString$1.call(value); -} +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; -/** `Object#toString` result references. */ -var nullTag = '[object Null]'; -var undefinedTag = '[object Undefined]'; +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; -/** Built-in value references. */ -var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - value = Object(value); - return (symToStringTag && symToStringTag in value) - ? getRawTag(value) - : objectToString(value); -} + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]'; -var funcTag = '[object Function]'; -var genTag = '[object GeneratorFunction]'; -var proxyTag = '[object Proxy]'; + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } +} + + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; +} + +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; + +assert.ifError = function(err) { if (err) throw err; }; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"util/":157}],5:[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 || {}))); +}(this, (function (exports) { 'use strict'; + +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]; + } + return newArr; } +var initialParams = function (fn) { + return function (/*...args, callback*/) { + var args = slice(arguments); + var callback = args.pop(); + fn.call(this, args, callback); + }; +}; + /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ - * @since 4.0.0 + * @since 0.1.0 * @category Lang * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * - * _.isArrayLike([1, 2, 3]); + * _.isObject({}); * // => true * - * _.isArrayLike(document.body.children); + * _.isObject([1, 2, 3]); * // => true * - * _.isArrayLike('abc'); + * _.isObject(_.noop); * // => true * - * _.isArrayLike(_.noop); + * _.isObject(null); * // => false */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); } -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -var breakLoop = {}; +var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. +function fallback(fn) { + setTimeout(fn, 0); } -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); +function wrap(defer) { + return function (fn/*, ...args*/) { + var args = slice(arguments, 1); + defer(function () { + fn.apply(null, args); + }); }; } -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - -var getIterator = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); +var _defer; - while (++index < n) { - result[index] = iteratee(index); - } - return result; +if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; } +var setImmediate$1 = wrap(_defer); + /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". + * 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, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. * + * @name asyncify * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @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)`. * @example * - * _.isObjectLike({}); - * // => true + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); * - * _.isObjectLike([1, 2, 3]); - * // => true + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); * - * _.isObjectLike(_.noop); - * // => false + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); * - * _.isObjectLike(null); - * // => false + * q.push(files); */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; +function asyncify(func) { + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (isObject(result) && typeof result.then === 'function') { + result.then(function(value) { + invokeCallback(callback, null, value); + }, function(err) { + invokeCallback(callback, err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); } -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (e) { + setImmediate$1(rethrow, e); + } +} -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; +function rethrow(error) { + throw error; +} + +var supportsSymbol = typeof Symbol === 'function'; + +function isAsync(fn) { + return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function wrapAsync(asyncFn) { + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; +} + +function applyEach$1(eachfn) { + 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(fn).apply(that, args.concat(cb)); + }, callback); + }); + if (args.length) { + return go.apply(this, args); + } + else { + return go; + } + }; } +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Built-in value references. */ +var Symbol$1 = root.Symbol; + /** Used for built-in method references. */ -var objectProto$3 = Object.prototype; +var objectProto = Object.prototype; /** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$3.hasOwnProperty; +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; /** Built-in value references. */ -var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; +var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * - * _.isArguments([1, 2, 3]); - * // => false + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. */ -var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag$1), + tag = value[symToStringTag$1]; + + try { + value[symToStringTag$1] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag$1] = tag; + } else { + delete value[symToStringTag$1]; + } + } + return result; +} + +/** Used for built-in method references. */ +var objectProto$1 = Object.prototype; /** - * Checks if `value` is classified as an `Array` object. + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString$1 = objectProto$1.toString; + +/** + * Converts `value` to a string using `Object.prototype.toString`. * - * @static - * @memberOf _ - * @since 0.1.0 + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString$1.call(value); +} + +/** `Object#toString` result references. */ +var nullTag = '[object Null]'; +var undefinedTag = '[object Undefined]'; + +/** Built-in value references. */ +var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + value = Object(value); + return (symToStringTag && symToStringTag in value) + ? getRawTag(value) + : objectToString(value); +} + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]'; +var funcTag = '[object Function]'; +var genTag = '[object GeneratorFunction]'; +var proxyTag = '[object Proxy]'; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 * @category Lang * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * - * _.isArray([1, 2, 3]); + * _.isFunction(_); * // => true * - * _.isArray(document.body.children); + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); * // => false * - * _.isArray('abc'); + * _.isLength(Infinity); * // => false * - * _.isArray(_.noop); + * _.isLength('3'); * // => false */ -var isArray = Array.isArray; +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} /** - * This method returns `false`. + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ - * @since 4.13.0 + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +var breakLoop = {}; + +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 * @category Util - * @returns {boolean} Returns `false`. * @example * - * _.times(2, _.stubFalse); - * // => [false, false] + * _.times(2, _.noop); + * // => [undefined, undefined] */ -function stubFalse() { - return false; +function noop() { + // No operation performed. } -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; +function once(fn) { + return function () { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; +} -/** Detect free variable `module`. */ -var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; +var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; +var getIterator = function (coll) { + return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); +}; -/** Built-in value references. */ -var Buffer = moduleExports ? root.Buffer : undefined; +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} /** - * Checks if `value` is a buffer. + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". * * @static * @memberOf _ - * @since 4.3.0 + * @since 4.0.0 * @category Lang * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * - * _.isBuffer(new Buffer(2)); + * _.isObjectLike({}); * // => true * - * _.isBuffer(new Uint8Array(2)); + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); * // => false */ -var isBuffer = nativeIsBuffer || stubFalse; - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; /** - * Checks if `value` is a valid array-like index. + * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER$1 : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; } -/** `Object#toString` result references. */ -var argsTag$1 = '[object Arguments]'; -var arrayTag = '[object Array]'; -var boolTag = '[object Boolean]'; -var dateTag = '[object Date]'; -var errorTag = '[object Error]'; -var funcTag$1 = '[object Function]'; -var mapTag = '[object Map]'; -var numberTag = '[object Number]'; -var objectTag = '[object Object]'; -var regexpTag = '[object RegExp]'; -var setTag = '[object Set]'; -var stringTag = '[object String]'; -var weakMapTag = '[object WeakMap]'; +/** Used for built-in method references. */ +var objectProto$3 = Object.prototype; -var arrayBufferTag = '[object ArrayBuffer]'; -var dataViewTag = '[object DataView]'; -var float32Tag = '[object Float32Array]'; -var float64Tag = '[object Float64Array]'; -var int8Tag = '[object Int8Array]'; -var int16Tag = '[object Int16Array]'; -var int32Tag = '[object Int32Array]'; -var uint8Tag = '[object Uint8Array]'; -var uint8ClampedTag = '[object Uint8ClampedArray]'; -var uint16Tag = '[object Uint16Array]'; -var uint32Tag = '[object Uint32Array]'; +/** Used to check objects for own properties. */ +var hasOwnProperty$2 = objectProto$3.hasOwnProperty; -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +/** Built-in value references. */ +var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$1 = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER$1 : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** `Object#toString` result references. */ +var argsTag$1 = '[object Arguments]'; +var arrayTag = '[object Array]'; +var boolTag = '[object Boolean]'; +var dateTag = '[object Date]'; +var errorTag = '[object Error]'; +var funcTag$1 = '[object Function]'; +var mapTag = '[object Map]'; +var numberTag = '[object Number]'; +var objectTag = '[object Object]'; +var regexpTag = '[object RegExp]'; +var setTag = '[object Set]'; +var stringTag = '[object String]'; +var weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]'; +var dataViewTag = '[object DataView]'; +var float32Tag = '[object Float32Array]'; +var float64Tag = '[object Float64Array]'; +var int8Tag = '[object Int8Array]'; +var int16Tag = '[object Int16Array]'; +var int32Tag = '[object Int32Array]'; +var uint8Tag = '[object Uint8Array]'; +var uint8ClampedTag = '[object Uint8ClampedArray]'; +var uint16Tag = '[object Uint16Array]'; +var uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = @@ -2990,9 +3110,10 @@ function queue(worker, concurrency, payload) { for (var i = 0, l = tasks.length; i < l; i++) { var task = tasks[i]; + var index = baseIndexOf(workersList, task, 0); if (index >= 0) { - workersList.splice(index); + workersList.splice(index, 1); } task.callback.apply(task, arguments); @@ -3053,11 +3174,11 @@ function queue(worker, concurrency, payload) { for (var i = 0; i < l; i++) { var node = q._tasks.shift(); tasks.push(node); + workersList.push(node); data.push(node.data); } numRunning += 1; - workersList.push(tasks[0]); if (q._tasks.length === 0) { q.empty(); @@ -3351,17 +3472,45 @@ var compose = function(/*...args*/) { return seq.apply(null, slice(arguments).reverse()); }; -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); +var _concat = Array.prototype.concat; + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + */ +var concatLimit = function(coll, limit, iteratee, callback) { + callback = callback || noop; + var _iteratee = wrapAsync(iteratee); + mapLimit(coll, limit, function(val, callback) { + _iteratee(val, function(err /*, ...args*/) { + if (err) return callback(err); + return callback(null, slice(arguments, 1)); }); - }, function (err) { - callback(err, result); + }, function(err, mapResults) { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = _concat.apply(result, mapResults[i]); + } + } + + return callback(err, result); }); -} +}; /** * Applies `iteratee` to each item in `coll`, concatenating the results. Returns @@ -3388,13 +3537,7 @@ function concat$1(eachfn, arr, fn, callback) { * // files is now a list of filenames that exist in the 3 directories * }); */ -var concat = doParallel(concat$1); - -function doSeries(fn) { - return function (obj, iteratee, callback) { - return fn(eachOfSeries, obj, wrapAsync(iteratee), callback); - }; -} +var concat = doLimit(concatLimit, Infinity); /** * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. @@ -3414,7 +3557,7 @@ function doSeries(fn) { * containing the concatenated results of the `iteratee` function. Invoked with * (err, results). */ -var concatSeries = doSeries(concat$1); +var concatSeries = doLimit(concatLimit, 1); /** * Returns a function that when called, calls-back with the values provided. @@ -4740,7 +4883,8 @@ function parallelLimit$1(tasks, limit, callback) { * @property {Function} resume - a function that resumes the processing of * queued tasks when the queue is paused. Invoke with `queue.resume()`. * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. Invoke with `queue.kill()`. + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. */ /** @@ -6113,6 +6257,7 @@ var index = { cargo: cargo, compose: compose, concat: concat, + concatLimit: concatLimit, concatSeries: concatSeries, constant: constant, detect: detect, @@ -6209,6 +6354,7 @@ exports.autoInject = autoInject; exports.cargo = cargo; exports.compose = compose; exports.concat = concat; +exports.concatLimit = concatLimit; exports.concatSeries = concatSeries; exports.constant = constant; exports.detect = detect; @@ -6304,19063 +6450,11386 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":206}],7:[function(require,module,exports){ -(function (Buffer,process){ -/** - * Copyright (c) 2017 Trent Mick. - * Copyright (c) 2017 Joyent Inc. - * - * The bunyan logging library for node.js. - * - * -*- mode: js -*- - * vim: expandtab:ts=4:sw=4 - */ +},{"_process":85}],6:[function(require,module,exports){ +'use strict' -var VERSION = '1.8.10'; +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray -/* - * Bunyan log format version. This becomes the 'v' field on all log records. - * This will be incremented if there is any backward incompatible change to - * the log record format. Details will be in 'CHANGES.md' (the change log). - */ -var LOG_VERSION = 0; +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} -var xxx = function xxx(s) { // internal dev/debug logging - var args = ['XX' + 'X: '+s].concat( - Array.prototype.slice.call(arguments, 1)); - console.error.apply(this, args); -}; -var xxx = function xxx() {}; // comment out to turn on debug logging +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 +function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } -/* - * Runtime environment notes: - * - * Bunyan is intended to run in a number of runtime environments. Here are - * some notes on differences for those envs and how the code copes. - * - * - node.js: The primary target environment. - * - NW.js: http://nwjs.io/ An *app* environment that feels like both a - * node env -- it has node-like globals (`process`, `global`) and - * browser-like globals (`window`, `navigator`). My *understanding* is that - * bunyan can operate as if this is vanilla node.js. - * - browser: Failing the above, we sniff using the `window` global - * . - * - browserify: http://browserify.org/ A browser-targetting bundler of - * node.js deps. The runtime is a browser env, so can't use fs access, - * etc. Browserify's build looks for `require()` imports - * to bundle. For some imports it won't be able to handle, we "hide" - * from browserify with `require('frobshizzle' + '')`. - * - Other? Please open issues if things are broken. - */ -var runtimeEnv; -if (typeof (process) !== 'undefined' && process.versions) { - if (process.versions.nw) { - runtimeEnv = 'nw'; - } else if (process.versions.node) { - runtimeEnv = 'node'; - } -} -if (!runtimeEnv && typeof (window) !== 'undefined' && - window.window === window) { - runtimeEnv = 'browser'; -} -if (!runtimeEnv) { - throw new Error('unknown runtime environment'); + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } - -var os, fs, dtrace; -if (runtimeEnv === 'browser') { - os = { - hostname: function () { - return window.location.host; - } - }; - fs = {}; - dtrace = null; -} else { - os = require('os'); - fs = require('fs'); - try { - dtrace = require('dtrace-provider' + ''); - } catch (e) { - dtrace = null; - } +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return (b64.length * 3 / 4) - placeHoldersCount(b64) } -var util = require('util'); -var assert = require('assert'); -var EventEmitter = require('events').EventEmitter; -var stream = require('stream'); -try { - var safeJsonStringify = require('safe-json-stringify'); -} catch (e) { - safeJsonStringify = null; -} -if (process.env.BUNYAN_TEST_NO_SAFE_JSON_STRINGIFY) { - safeJsonStringify = null; -} +function toByteArray (b64) { + var i, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) -// The 'mv' module is required for rotating-file stream support. -try { - var mv = require('mv' + ''); -} catch (e) { - mv = null; -} + arr = new Arr((len * 3 / 4) - placeHolders) -try { - var sourceMapSupport = require('source-map-support' + ''); -} catch (_) { - sourceMapSupport = null; -} + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + var L = 0 -//---- Internal support stuff + 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 + arr[L++] = tmp & 0xFF + } -/** - * A shallow copy of an object. Bunyan logging attempts to never cause - * exceptions, so this function attempts to handle non-objects gracefully. - */ -function objCopy(obj) { - if (obj == null) { // null or undefined - return obj; - } else if (Array.isArray(obj)) { - return obj.slice(); - } else if (typeof (obj) === 'object') { - var copy = {}; - Object.keys(obj).forEach(function (k) { - copy[k] = obj[k]; - }); - return copy; - } else { - return obj; - } -} + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } -var format = util.format; -if (!format) { - // If node < 0.6, then use its `util.format`: - // : - var inspect = util.inspect; - var formatRegExp = /%[sdj%]/g; - format = function format(f) { - if (typeof (f) !== 'string') { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } + return arr +} - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function (x) { - if (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; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (x === null || typeof (x) !== 'object') { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} -/** - * Gather some caller info 3 stack levels up. - * See . - */ -function getCaller3Info() { - if (this === undefined) { - // Cannot access caller info in 'strict' mode. - return; - } - var obj = {}; - var saveLimit = Error.stackTraceLimit; - var savePrepare = Error.prepareStackTrace; - Error.stackTraceLimit = 3; +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 - Error.prepareStackTrace = function (_, stack) { - var caller = stack[2]; - if (sourceMapSupport) { - caller = sourceMapSupport.wrapCallSite(caller); - } - obj.file = caller.getFileName(); - obj.line = caller.getLineNumber(); - var func = caller.getFunctionName(); - if (func) - obj.func = func; - }; - Error.captureStackTrace(this, getCaller3Info); - this.stack; + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } - Error.stackTraceLimit = saveLimit; - Error.prepareStackTrace = savePrepare; - return obj; -} + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + parts.push(output) -function _indent(s, indent) { - if (!indent) indent = ' '; - var lines = s.split(/\r?\n/g); - return indent + lines.join('\n' + indent); + return parts.join('') } +},{}],7:[function(require,module,exports){ -/** - * Warn about an bunyan processing error. +},{}],8:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],9:[function(require,module,exports){ +(function (global){ +/*! + * The buffer module from node.js, for the browser. * - * @param msg {String} Message with which to warn. - * @param dedupKey {String} Optional. A short string key for this warning to - * have its warning only printed once. + * @author Feross Aboukhadijeh + * @license MIT */ -function _warn(msg, dedupKey) { - assert.ok(msg); - if (dedupKey) { - if (_warned[dedupKey]) { - return; - } - _warned[dedupKey] = true; - } - process.stderr.write(msg + '\n'); -} -function _haveWarned(dedupKey) { - return _warned[dedupKey]; -} -var _warned = {}; +/* eslint-disable no-proto */ +'use strict' -function ConsoleRawStream() {} -ConsoleRawStream.prototype.write = function (rec) { - if (rec.level < INFO) { - console.log(rec); - } else if (rec.level < WARN) { - console.info(rec); - } else if (rec.level < ERROR) { - console.warn(rec); - } else { - console.error(rec); - } -}; - - -//---- Levels - -var TRACE = 10; -var DEBUG = 20; -var INFO = 30; -var WARN = 40; -var ERROR = 50; -var FATAL = 60; - -var levelFromName = { - 'trace': TRACE, - 'debug': DEBUG, - 'info': INFO, - 'warn': WARN, - 'error': ERROR, - 'fatal': FATAL -}; -var nameFromLevel = {}; -Object.keys(levelFromName).forEach(function (name) { - nameFromLevel[levelFromName[name]] = name; -}); +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') -// Dtrace probes. -var dtp = undefined; -var probes = dtrace && {}; +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 /** - * Resolve a level number, name (upper or lowercase) to a level number value. + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) * - * @param nameOrNum {String|Number} A level name (case-insensitive) or positive - * integer level. - * @api public + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. */ -function resolveLevel(nameOrNum) { - var level; - var type = typeof (nameOrNum); - if (type === 'string') { - level = levelFromName[nameOrNum.toLowerCase()]; - if (!level) { - throw new Error(format('unknown level name: "%s"', nameOrNum)); - } - } else if (type !== 'number') { - throw new TypeError(format('cannot resolve level: invalid arg (%s):', - type, nameOrNum)); - } else if (nameOrNum < 0 || Math.floor(nameOrNum) !== nameOrNum) { - throw new TypeError(format('level is not a positive integer: %s', - nameOrNum)); - } else { - level = nameOrNum; - } - return level; -} +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() -function isWritable(obj) { - if (obj instanceof stream.Writable) { - return true; - } - return typeof (obj.write) === 'function'; +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } } +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} -//---- Logger class +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} /** - * Create a Logger instance. - * - * @param options {Object} See documentation for full details. At minimum - * this must include a 'name' string key. Configuration keys: - * - `streams`: specify the logger output streams. This is an array of - * objects with these fields: - * - `type`: The stream type. See README.md for full details. - * Often this is implied by the other fields. Examples are - * 'file', 'stream' and "raw". - * - `level`: Defaults to 'info'. - * - `path` or `stream`: The specify the file path or writeable - * stream to which log records are written. E.g. - * `stream: process.stdout`. - * - `closeOnExit` (boolean): Optional. Default is true for a - * 'file' stream when `path` is given, false otherwise. - * See README.md for full details. - * - `level`: set the level for a single output stream (cannot be used - * with `streams`) - * - `stream`: the output stream for a logger with just one, e.g. - * `process.stdout` (cannot be used with `streams`) - * - `serializers`: object mapping log record field names to - * serializing functions. See README.md for details. - * - `src`: Boolean (default false). Set true to enable 'src' automatic - * field with log call source info. - * All other keys are log record fields. - * - * An alternative *internal* call signature is used for creating a child: - * new Logger(, [, ]); + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. * - * @param _childSimple (Boolean) An assertion that the given `_childOptions` - * (a) only add fields (no config) and (b) no serialization handling is - * required for them. IOW, this is a fast path for frequent child - * creation. + * The `Uint8Array` prototype remains unmodified. */ -function Logger(options, _childOptions, _childSimple) { - xxx('Logger start:', options) - if (!(this instanceof Logger)) { - return new Logger(options, _childOptions); - } - // Input arg validation. - var parent; - if (_childOptions !== undefined) { - parent = options; - options = _childOptions; - if (!(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('options.name (string) is required'); - } - } else { - if (options.name) { - throw new TypeError( - 'invalid options.name: child cannot set logger name'); - } - } - 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 && (typeof (options.serializers) !== 'object' || - Array.isArray(options.serializers))) { - throw new TypeError('invalid options.serializers: must be an object') +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} - EventEmitter.call(this); +Buffer.poolSize = 8192 // not used by this implementation - // Fast path for simple child creation. - if (parent && _childSimple) { - // `_isSimpleChild` is a signal to stream close handling that this child - // owns none of its streams. - this._isSimpleChild = true; +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} - this._level = parent._level; - this.streams = parent.streams; - this.serializers = parent.serializers; - this.src = parent.src; - var fields = this.fields = {}; - var parentFieldNames = Object.keys(parent.fields); - for (var i = 0; i < parentFieldNames.length; i++) { - var name = parentFieldNames[i]; - fields[name] = parent.fields[name]; - } - var names = Object.keys(options); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - fields[name] = options[name]; - } - return; - } +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } - // Start values. - var self = this; - if (parent) { - this._level = parent._level; - this.streams = []; - for (var i = 0; i < parent.streams.length; i++) { - var s = objCopy(parent.streams[i]); - s.closeOnExit = false; // Don't own parent stream. - this.streams.push(s); - } - this.serializers = objCopy(parent.serializers); - this.src = parent.src; - this.fields = objCopy(parent.fields); - if (options.level) { - this.level(options.level); - } - } else { - this._level = Number.POSITIVE_INFINITY; - this.streams = []; - this.serializers = null; - this.src = false; - this.fields = {}; - } - - if (!dtp && dtrace) { - dtp = dtrace.createDTraceProvider('bunyan'); + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } - for (var level in levelFromName) { - var probe; + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } - probes[levelFromName[level]] = probe = - dtp.addProbe('log-' + level, 'char *'); + return fromObject(that, value) +} - // Explicitly add a reference to dtp to prevent it from being GC'd - probe.dtp = dtp; - } +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} - dtp.enable(); - } +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} - // Handle *config* options (i.e. options that are not just plain data - // for log records). - if (options.stream) { - self.addStream({ - type: 'stream', - stream: options.stream, - closeOnExit: false, - level: options.level - }); - } else if (options.streams) { - options.streams.forEach(function (s) { - self.addStream(s, options.level); - }); - } else if (parent && options.level) { - this.level(options.level); - } else if (!parent) { - if (runtimeEnv === 'browser') { - /* - * In the browser we'll be emitting to console.log by default. - * Any console.log worth its salt these days can nicely render - * and introspect objects (e.g. the Firefox and Chrome console) - * so let's emit the raw log record. Are there browsers for which - * that breaks things? - */ - self.addStream({ - type: 'raw', - stream: new ConsoleRawStream(), - closeOnExit: false, - level: options.level - }); - } else { - self.addStream({ - type: 'stream', - stream: process.stdout, - closeOnExit: false, - level: options.level - }); - } - } - if (options.serializers) { - self.addSerializers(options.serializers); - } - if (options.src) { - this.src = true; - } - xxx('Logger: ', self) +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} - // Fields. - // These are the default fields for log records (minus the attributes - // removed in this constructor). To allow storing raw log records - // (unrendered), `this.fields` must never be mutated. Create a copy for - // any changes. - var fields = objCopy(options); - delete fields.stream; - delete fields.level; - delete fields.streams; - delete fields.serializers; - delete fields.src; - if (this.serializers) { - this._applySerializers(fields); - } - if (!fields.hostname && !self.fields.hostname) { - fields.hostname = os.hostname(); - } - if (!fields.pid) { - fields.pid = process.pid; - } - Object.keys(fields).forEach(function (k) { - self.fields[k] = fields[k]; - }); +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) } -util.inherits(Logger, EventEmitter); +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} /** - * Add a stream - * - * @param stream {Object}. Object with these fields: - * - `type`: The stream type. See README.md for full details. - * Often this is implied by the other fields. Examples are - * 'file', 'stream' and "raw". - * - `path` or `stream`: The specify the file path or writeable - * stream to which log records are written. E.g. - * `stream: process.stdout`. - * - `level`: Optional. Falls back to `defaultLevel`. - * - `closeOnExit` (boolean): Optional. Default is true for a - * 'file' stream when `path` is given, false otherwise. - * See README.md for full details. - * @param defaultLevel {Number|String} Optional. A level to use if - * `stream.level` is not set. If neither is given, this defaults to INFO. + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ -Logger.prototype.addStream = function addStream(s, defaultLevel) { - var self = this; - if (defaultLevel === null || defaultLevel === undefined) { - defaultLevel = INFO; - } +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} - s = objCopy(s); +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } - // Implicit 'type' from other args. - if (!s.type) { - if (s.stream) { - s.type = 'stream'; - } else if (s.path) { - s.type = 'file' - } - } - s.raw = (s.type === 'raw'); // PERF: Allow for faster check in `_emit`. + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } - if (s.level !== undefined) { - s.level = resolveLevel(s.level); - } else { - s.level = resolveLevel(defaultLevel); - } - if (s.level < self._level) { - self._level = s.level; - } + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) - switch (s.type) { - case 'stream': - assert.ok(isWritable(s.stream), - '"stream" stream is not writable: ' + util.inspect(s.stream)); + var actual = that.write(string, encoding) - if (!s.closeOnExit) { - s.closeOnExit = false; - } - break; - case 'file': - if (s.reemitErrorEvents === undefined) { - s.reemitErrorEvents = true; - } - if (!s.stream) { - s.stream = fs.createWriteStream(s.path, - {flags: 'a', encoding: 'utf8'}); - if (!s.closeOnExit) { - s.closeOnExit = true; - } - } else { - if (!s.closeOnExit) { - s.closeOnExit = false; - } - } - break; - case 'rotating-file': - assert.ok(!s.stream, - '"rotating-file" stream should not give a "stream"'); - assert.ok(s.path); - assert.ok(mv, '"rotating-file" stream type is not supported: ' - + 'missing "mv" module'); - s.stream = new RotatingFileStream(s); - if (!s.closeOnExit) { - s.closeOnExit = true; - } - break; - case 'raw': - if (!s.closeOnExit) { - s.closeOnExit = false; - } - break; - default: - throw new TypeError('unknown stream type "' + s.type + '"'); - } - - if (s.reemitErrorEvents && typeof (s.stream.on) === 'function') { - // TODO: When we have `.close()`, it should remove event - // listeners to not leak Logger instances. - s.stream.on('error', function onStreamError(err) { - self.emit('error', err, s); - }); - } + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } - self.streams.push(s); - delete self.haveNonRawStreams; // reset + return that } +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} -/** - * Add serializers - * - * @param serializers {Object} Optional. Object mapping log record field names - * to serializing functions. See README.md for details. - */ -Logger.prototype.addSerializers = function addSerializers(serializers) { - var self = this; +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer - if (!self.serializers) { - self.serializers = {}; - } - Object.keys(serializers).forEach(function (field) { - var serializer = serializers[field]; - if (typeof (serializer) !== 'function') { - throw new TypeError(format( - 'invalid serializer for "%s" field: must be a function', - field)); - } else { - self.serializers[field] = serializer; - } - }); -} + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } -/** - * Create a child logger, typically to add a few log record fields. - * - * This can be useful when passing a logger to a sub-component, e.g. a - * 'wuzzle' component of your service: - * - * var wuzzleLog = log.child({component: 'wuzzle'}) - * var wuzzle = new Wuzzle({..., log: wuzzleLog}) - * - * Then log records from the wuzzle code will have the same structure as - * the app log, *plus the component='wuzzle' field*. - * - * @param options {Object} Optional. Set of options to apply to the child. - * All of the same options for a new Logger apply here. Notes: - * - The parent's streams are inherited and cannot be removed in this - * call. Any given `streams` are *added* to the set inherited from - * the parent. - * - The parent's serializers are inherited, though can effectively be - * overwritten by using duplicate keys. - * - Can use `level` to set the level of the streams inherited from - * the parent. The level for the parent is NOT affected. - * @param simple {Boolean} Optional. Set to true to assert that `options` - * (a) only add fields (no config) and (b) no serialization handling is - * required for them. IOW, this is a fast path for frequent child - * creation. See 'tools/timechild.js' for numbers. - */ -Logger.prototype.child = function (options, simple) { - return new (this.constructor)(this, options || {}, simple); + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that } +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) -/** - * A convenience method to reopen 'file' streams on a logger. This can be - * useful with external log rotation utilities that move and re-open log files - * (e.g. logrotate on Linux, logadm on SmartOS/Illumos). Those utilities - * typically have rotation options to copy-and-truncate the log file, but - * you may not want to use that. An alternative is to do this in your - * application: - * - * var log = bunyan.createLogger(...); - * ... - * process.on('SIGUSR2', function () { - * log.reopenFileStreams(); - * }); - * ... - * - * See . - */ -Logger.prototype.reopenFileStreams = function () { - var self = this; - self.streams.forEach(function (s) { - if (s.type === 'file') { - if (s.stream) { - // Not sure if typically would want this, or more immediate - // `s.stream.destroy()`. - s.stream.end(); - s.stream.destroySoon(); - delete s.stream; - } - s.stream = fs.createWriteStream(s.path, - {flags: 'a', encoding: 'utf8'}); - s.stream.on('error', function (err) { - self.emit('error', err, s); - }); - } - }); -}; + if (that.length === 0) { + return that + } + obj.copy(that, 0, 0, len) + return that + } -/* BEGIN JSSTYLED */ -/** - * Close this logger. - * - * This closes streams (that it owns, as per 'endOnClose' attributes on - * streams), etc. Typically you **don't** need to bother calling this. -Logger.prototype.close = function () { - if (this._closed) { - return; + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) } - if (!this._isSimpleChild) { - self.streams.forEach(function (s) { - if (s.endOnClose) { - xxx('closing stream s:', s); - s.stream.end(); - s.endOnClose = false; - } - }); + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) } - this._closed = true; + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } - */ -/* END JSSTYLED */ +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} -/** - * Get/set the level of all streams on this logger. - * - * Get Usage: - * // Returns the current log level (lowest level of all its streams). - * log.level() -> INFO - * - * Set Usage: - * log.level(INFO) // set all streams to level INFO - * log.level('info') // can use 'info' et al aliases - */ -Logger.prototype.level = function level(value) { - if (value === undefined) { - return this._level; - } - var newLevel = resolveLevel(value); - var len = this.streams.length; - for (var i = 0; i < len; i++) { - this.streams[i].level = newLevel; - } - this._level = newLevel; +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) } +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} -/** - * Get/set the level of a particular stream on this logger. - * - * Get Usage: - * // Returns an array of the levels of each stream. - * log.levels() -> [TRACE, INFO] - * - * // Returns a level of the identified stream. - * log.levels(0) -> TRACE // level of stream at index 0 - * log.levels('foo') // level of stream with name 'foo' - * - * Set Usage: - * log.levels(0, INFO) // set level of stream 0 to INFO - * log.levels(0, 'info') // can use 'info' et al aliases - * log.levels('foo', WARN) // set stream named 'foo' to WARN - * - * Stream names: When streams are defined, they can optionally be given - * a name. For example, - * log = new Logger({ - * streams: [ - * { - * name: 'foo', - * path: '/var/log/my-service/foo.log' - * level: 'trace' - * }, - * ... - * - * @param name {String|Number} The stream index or name. - * @param value {Number|String} The level value (INFO) or alias ('info'). - * If not given, this is a 'get' operation. - * @throws {Error} If there is no stream with the given name. - */ -Logger.prototype.levels = function levels(name, value) { - if (name === undefined) { - assert.equal(value, undefined); - return this.streams.map( - function (s) { return s.level }); - } - var stream; - if (typeof (name) === 'number') { - stream = this.streams[name]; - if (stream === undefined) { - throw new Error('invalid stream index: ' + name); - } - } else { - var len = this.streams.length; - for (var i = 0; i < len; 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 (value === undefined) { - return stream.level; - } else { - var newLevel = resolveLevel(value); - stream.level = newLevel; - if (newLevel < this._level) { - this._level = newLevel; - } - } -} +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + if (a === b) return 0 -/** - * Apply registered serializers to the appropriate keys in the given fields. - * - * Pre-condition: This is only called if there is at least one serializer. - * - * @param fields (Object) The log record fields. - * @param excludeFields (Object) Optional mapping of keys to `true` for - * keys to NOT apply a serializer. - */ -Logger.prototype._applySerializers = function (fields, excludeFields) { - var self = this; + var x = a.length + var y = b.length - xxx('_applySerializers: excludeFields', excludeFields); + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } - // Check each serializer against these (presuming number of serializers - // is typically less than number of fields). - Object.keys(this.serializers).forEach(function (name) { - if (fields[name] === undefined || - (excludeFields && excludeFields[name])) - { - return; - } - xxx('_applySerializers; apply to "%s" key', name) - try { - fields[name] = self.serializers[name](fields[name]); - } catch (err) { - _warn(format('bunyan: ERROR: Exception thrown from the "%s" ' - + 'Bunyan serializer. This should never happen. This is a bug ' - + 'in that serializer function.\n%s', - name, err.stack || err)); - fields[name] = format('(Error in Bunyan log "%s" serializer ' - + 'broke field. See stderr for details.)', name); - } - }); + if (x < y) return -1 + if (y < x) return 1 + return 0 } +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} -/** - * Emit a log record. - * - * @param rec {log record} - * @param noemit {Boolean} Optional. Set to true to skip emission - * and just return the JSON string. - */ -Logger.prototype._emit = function (rec, noemit) { - var i; +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } - // Lazily determine if this Logger has non-'raw' streams. If there are - // any, then we need to stringify the log record. - if (this.haveNonRawStreams === undefined) { - this.haveNonRawStreams = false; - for (i = 0; i < this.streams.length; i++) { - if (!this.streams[i].raw) { - this.haveNonRawStreams = true; - break; - } - } + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length } + } - // Stringify the object (creates a warning str on error). - var str; - if (noemit || this.haveNonRawStreams) { - str = fastAndSafeJsonStringify(rec) + '\n'; + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} - if (noemit) - return str; +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } - var level = rec.level; - for (i = 0; i < this.streams.length; i++) { - var s = this.streams[i]; - if (s.level <= level) { - xxx('writing log rec "%s" to "%s" stream (%d <= %d): %j', - rec.msg, s.type, s.level, level, rec); - s.stream.write(s.raw ? rec : str); - } - }; + var len = string.length + if (len === 0) return 0 - return str; + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } } +Buffer.byteLength = byteLength +function slowToString (encoding, start, end) { + var loweredCase = false -/** - * Build a record object suitable for emitting from the arguments - * provided to the a log emitter. - */ -function mkRecord(log, minLevel, args) { - var excludeFields, fields, msgArgs; - if (args[0] instanceof Error) { - // `log.(err, ...)` - fields = { - // Use this Logger's err serializer, if defined. - err: (log.serializers && log.serializers.err - ? log.serializers.err(args[0]) - : Logger.stdSerializers.err(args[0])) - }; - excludeFields = {err: true}; - if (args.length === 1) { - msgArgs = [fields.err.message]; - } else { - msgArgs = args.slice(1); - } - } else if (typeof (args[0]) !== 'object' || Array.isArray(args[0])) { - // `log.(msg, ...)` - fields = null; - msgArgs = args.slice(); - } else if (Buffer.isBuffer(args[0])) { // `log.(buf, ...)` - // Almost certainly an error, show `inspect(buf)`. See bunyan - // issue #35. - fields = null; - msgArgs = args.slice(); - msgArgs[0] = util.inspect(msgArgs[0]); - } else { // `log.(fields, msg, ...)` - fields = args[0]; - if (fields && args.length === 1 && fields.err && - fields.err instanceof Error) - { - msgArgs = [fields.err.message]; - } else { - msgArgs = args.slice(1); - } - } + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - // Build up the record object. - var rec = objCopy(log.fields); - var level = rec.level = minLevel; - var recFields = (fields ? objCopy(fields) : null); - if (recFields) { - if (log.serializers) { - log._applySerializers(recFields, excludeFields); - } - Object.keys(recFields).forEach(function (k) { - rec[k] = recFields[k]; - }); - } - rec.msg = format.apply(log, msgArgs); - if (!rec.time) { - rec.time = (new Date()); - } - // Get call source info - if (log.src && !rec.src) { - rec.src = getCaller3Info() - } - rec.v = LOG_VERSION; + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } - return rec; -}; + if (end === undefined || end > this.length) { + end = this.length + } + if (end <= 0) { + return '' + } -/** - * Build an array that dtrace-provider can use to fire a USDT probe. If we've - * already built the appropriate string, we use it. Otherwise, build the - * record object and stringify it. - */ -function mkProbeArgs(str, log, minLevel, msgArgs) { - return [ str || log._emit(mkRecord(log, minLevel, msgArgs), true) ]; -} + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + if (end <= start) { + return '' + } -/** - * Build a log emitter function for level minLevel. I.e. this is the - * creator of `log.info`, `log.error`, etc. - */ -function mkLogEmitter(minLevel) { - return function () { - var log = this; - var str = null; - var rec = null; + if (!encoding) encoding = 'utf8' - if (!this._emit) { - /* - * Show this invalid Bunyan usage warning *once*. - * - * See for - * an example of how this can happen. - */ - var dedupKey = 'unbound'; - if (!_haveWarned[dedupKey]) { - var caller = getCaller3Info(); - _warn(format('bunyan usage error: %s:%s: attempt to log ' - + 'with an unbound log method: `this` is: %s', - caller.file, caller.line, util.inspect(this)), - dedupKey); - } - return; - } else if (arguments.length === 0) { // `log.()` - return (this._level <= minLevel); - } + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - var msgArgs = new Array(arguments.length); - for (var i = 0; i < msgArgs.length; ++i) { - msgArgs[i] = arguments[i]; - } + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - if (this._level <= minLevel) { - rec = mkRecord(log, minLevel, msgArgs); - str = this._emit(rec); - } + case 'ascii': + return asciiSlice(this, start, end) - if (probes) { - probes[minLevel].fire(mkProbeArgs, str, log, minLevel, msgArgs); - } - } -} + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + case 'base64': + return base64Slice(this, start, end) -/** - * The functions below log a record at a specific level. - * - * Usages: - * log.() -> boolean is-trace-enabled - * log.( err, [ msg, ...]) - * log.( msg, ...) - * log.( fields, msg, ...) - * - * where is the lowercase version of the log level. E.g.: - * - * log.info() - * - * @params fields {Object} Optional set of additional fields to log. - * @params msg {String} Log message. This can be followed by additional - * arguments that are handled like - * [util.format](http://nodejs.org/docs/latest/api/all.html#util.format). - */ -Logger.prototype.trace = mkLogEmitter(TRACE); -Logger.prototype.debug = mkLogEmitter(DEBUG); -Logger.prototype.info = mkLogEmitter(INFO); -Logger.prototype.warn = mkLogEmitter(WARN); -Logger.prototype.error = mkLogEmitter(ERROR); -Logger.prototype.fatal = mkLogEmitter(FATAL); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true -//---- Standard serializers -// A serializer is a function that serializes a JavaScript object to a -// JSON representation for logging. There is a standard set of presumed -// interesting objects in node.js-land. +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} -Logger.stdSerializers = {}; +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} -// Serialize an HTTP request. -Logger.stdSerializers.req = function (req) { - if (!req || !req.connection) - return req; - return { - method: req.method, - url: req.url, - headers: req.headers, - remoteAddress: req.connection.remoteAddress, - remotePort: req.connection.remotePort - }; - // Trailers: Skipping for speed. If you need trailers in your app, then - // make a custom serializer. - //if (Object.keys(trailers).length > 0) { - // obj.trailers = req.trailers; - //} -}; +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} -// Serialize an HTTP response. -Logger.stdSerializers.res = function (res) { - if (!res || !res.statusCode) - return res; - return { - statusCode: res.statusCode, - header: res._header - } -}; +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} -/* - * This function dumps long stack traces for exceptions having a cause() - * method. The error classes from - * [verror](https://github.com/davepacheco/node-verror) and - * [restify v2.0](https://github.com/mcavage/node-restify) are examples. - * - * Based on `dumpException` in - * https://github.com/davepacheco/node-extsprintf/blob/master/lib/extsprintf.js - */ -function getFullErrorStack(ex) -{ - var ret = ex.stack || ex.toString(); - if (ex.cause && typeof (ex.cause) === 'function') { - var cex = ex.cause(); - if (cex) { - ret += '\nCaused by: ' + getFullErrorStack(cex); - } - } - return (ret); +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 } -// Serialize an Error object -// (Core error properties are enumerable in node 0.4, not in 0.6). -var errSerializer = Logger.stdSerializers.err = function (err) { - if (!err || !err.stack) - return err; - var obj = { - message: err.message, - name: err.name, - stack: getFullErrorStack(err), - code: err.code, - signal: err.signal - } - return obj; -}; - - -// A JSON stringifier that handles cycles safely - tracks seen values in a Set. -function safeCyclesSet() { - var seen = new Set(); - return function (key, val) { - if (!val || typeof (val) !== 'object') { - return val; - } - if (seen.has(val)) { - return '[Circular]'; - } - seen.add(val); - return val; - }; +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' } -/** - * A JSON stringifier that handles cycles safely - tracks seen vals in an Array. - * - * Note: This approach has performance problems when dealing with large objects, - * see trentm/node-bunyan#445, but since this is the only option for node 0.10 - * and earlier (as Set was introduced in Node 0.12), it's used as a fallback - * when Set is not available. - */ -function safeCyclesArray() { - var seen = []; - return function (key, val) { - if (!val || typeof (val) !== 'object') { - return val; - } - if (seen.indexOf(val) !== -1) { - return '[Circular]'; - } - seen.push(val); - return val; - }; -} +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } -/** - * A JSON stringifier that handles cycles safely. - * - * Usage: JSON.stringify(obj, safeCycles()) - * - * Choose the best safe cycle function from what is available - see - * trentm/node-bunyan#445. - */ -var safeCycles = typeof (Set) !== 'undefined' ? safeCyclesSet : safeCyclesArray; + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } -/** - * A fast JSON.stringify that handles cycles and getter exceptions (when - * safeJsonStringify is installed). - * - * This function attempts to use the regular JSON.stringify for speed, but on - * error (e.g. JSON cycle detection exception) it falls back to safe stringify - * handlers that can deal with cycles and/or getter exceptions. - */ -function fastAndSafeJsonStringify(rec) { - try { - return JSON.stringify(rec); - } catch (ex) { - try { - return JSON.stringify(rec, safeCycles()); - } catch (e) { - if (safeJsonStringify) { - return safeJsonStringify(rec); - } else { - var dedupKey = e.stack.split(/\n/g, 3).join('\n'); - _warn('bunyan: ERROR: Exception in ' - + '`JSON.stringify(rec)`. You can install the ' - + '"safe-json-stringify" module to have Bunyan fallback ' - + 'to safer stringification. Record:\n' - + _indent(format('%s\n%s', util.inspect(rec), e.stack)), - dedupKey); - return format('(Exception in JSON.stringify(rec): %j. ' - + 'See stderr for details.)', e.message); - } - } - } -} + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } -var RotatingFileStream = null; -if (mv) { + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 -RotatingFileStream = function RotatingFileStream(options) { - this.path = options.path; + if (this === target) return 0 - this.count = (options.count == null ? 10 : options.count); - assert.equal(typeof (this.count), 'number', - format('rotating-file stream "count" is not a number: %j (%s) in %j', - this.count, typeof (this.count), this)); - assert.ok(this.count >= 0, - format('rotating-file stream "count" is not >= 0: %j in %j', - this.count, this)); + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) - // Parse `options.period`. - if (options.period) { - // where scope is: - // h hours (at the start of the hour) - // d days (at the start of the day, i.e. just after midnight) - // w weeks (at the start of Sunday) - // m months (on the first of the month) - // y years (at the start of Jan 1st) - // with special values 'hourly' (1h), 'daily' (1d), "weekly" (1w), - // 'monthly' (1m) and 'yearly' (1y) - var period = { - 'hourly': '1h', - 'daily': '1d', - 'weekly': '1w', - 'monthly': '1m', - 'yearly': '1y' - }[options.period] || options.period; - var 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 thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) - var lastModified = null; - try { - var fileInfo = fs.statSync(this.path); - lastModified = fileInfo.mtime.getTime(); - } - catch (err) { - // file doesn't exist - } - var rotateAfterOpen = false; - if (lastModified) { - var lastRotTime = this._calcRotTime(0); - if (lastModified < lastRotTime) { - rotateAfterOpen = true; - } + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break } + } - // TODO: template support for backup files - // template: - // default is %P.%n - // '/var/log/archive/foo.log' -> foo.log.%n - // '/var/log/archive/foo.log.%n' - // codes: - // XXX support strftime codes (per node version of those) - // or whatever module. Pick non-colliding for extra - // codes - // %P `path` base value - // %n integer number of rotated log (1,2,3,...) - // %d datetime in YYYY-MM-DD_HH-MM-SS - // XXX what should default date format be? - // prior art? Want to avoid ':' in - // filenames (illegal on Windows for one). - - this.stream = fs.createWriteStream(this.path, - {flags: 'a', encoding: 'utf8'}); - - this.rotQueue = []; - this.rotating = false; - if (rotateAfterOpen) { - this._debug('rotateAfterOpen -> call rotate()'); - this.rotate(); - } else { - this._setupNextRot(); - } + if (x < y) return -1 + if (y < x) return 1 + return 0 } -util.inherits(RotatingFileStream, EventEmitter); - -RotatingFileStream.prototype._debug = function () { - // Set this to `true` to add debug logging. - if (false) { - if (arguments.length === 0) { - return true; - } - var args = Array.prototype.slice.call(arguments); - args[0] = '[' + (new Date().toISOString()) + ', ' - + this.path + '] ' + args[0]; - console.log.apply(this, args); - } else { - return false; - } -}; +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 -RotatingFileStream.prototype._setupNextRot = function () { - this.rotAt = this._calcRotTime(1); - this._setRotationTimer(); -} + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } -RotatingFileStream.prototype._setRotationTimer = function () { - var self = this; - var delay = this.rotAt - Date.now(); - // Cap timeout to Node's max setTimeout, see - // . - var TIMEOUT_MAX = 2147483647; // 2^31-1 - if (delay > TIMEOUT_MAX) { - delay = TIMEOUT_MAX; - } - this.timeout = setTimeout( - function () { - self._debug('_setRotationTimer timeout -> call rotate()'); - self.rotate(); - }, - delay); - if (typeof (this.timeout.unref) === 'function') { - this.timeout.unref(); - } -} + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } -RotatingFileStream.prototype._calcRotTime = -function _calcRotTime(periodOffset) { - this._debug('_calcRotTime: %s%s', this.periodNum, this.periodScope); - var d = new Date(); + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } - this._debug(' now local: %s', d); - this._debug(' now utc: %s', d.toISOString()); - var rotAt; - switch (this.periodScope) { - case 'ms': - // Hidden millisecond period for debugging. - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * periodOffset; - } else { - rotAt = Date.now() + this.periodNum * periodOffset; - } - break; - case 'h': - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * 60 * 60 * 1000 * periodOffset; - } else { - // First time: top of the next hour. - rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), - d.getUTCDate(), d.getUTCHours() + periodOffset); - } - break; - case 'd': - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * 24 * 60 * 60 * 1000 - * periodOffset; - } else { - // First time: start of tomorrow (i.e. at the coming midnight) UTC. - rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), - d.getUTCDate() + periodOffset); - } - break; - case 'w': - // Currently, always on Sunday morning at 00:00:00 (UTC). - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * 7 * 24 * 60 * 60 * 1000 - * periodOffset; - } else { - // First time: this coming Sunday. - var dayOffset = (7 - d.getUTCDay()); - if (periodOffset < 1) { - dayOffset = -d.getUTCDay(); - } - if (periodOffset > 1 || periodOffset < -1) { - dayOffset += 7 * periodOffset; - } - rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), - d.getUTCDate() + dayOffset); - } - break; - case 'm': - if (this.rotAt) { - rotAt = Date.UTC(d.getUTCFullYear(), - d.getUTCMonth() + this.periodNum * periodOffset, 1); - } else { - // First time: the start of the next month. - rotAt = Date.UTC(d.getUTCFullYear(), - d.getUTCMonth() + periodOffset, 1); - } - break; - case 'y': - if (this.rotAt) { - rotAt = Date.UTC(d.getUTCFullYear() + this.periodNum * periodOffset, - 0, 1); - } else { - // First time: the start of the next year. - rotAt = Date.UTC(d.getUTCFullYear() + periodOffset, 0, 1); - } - break; - default: - assert.fail(format('invalid period scope: "%s"', this.periodScope)); + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 } - - 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)/1000/60, - (rotAt-now)/1000/60/60); + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } } - return rotAt; -}; + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } -RotatingFileStream.prototype.rotate = function rotate() { - // XXX What about shutdown? - var self = this; + throw new TypeError('val must be string, number or Buffer') +} - // If rotation period is > ~25 days, we have to break into multiple - // setTimeout's. See . - if (self.rotAt && self.rotAt > Date.now()) { - return self._setRotationTimer(); - } +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length - this._debug('rotate'); - if (self.rotating) { - throw new TypeError('cannot start a rotation when already rotating'); + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 } - self.rotating = true; - - self.stream.end(); // XXX can do moves sync after this? test at high rate + } - function del() { - var toDel = self.path + '.' + String(n - 1); - if (n === 0) { - toDel = self.path; - } - n -= 1; - self._debug(' rm %s', toDel); - fs.unlink(toDel, function (delErr) { - //XXX handle err other than not exists - moves(); - }); + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) } + } - function moves() { - if (self.count === 0 || n < 0) { - return finish(); - } - var before = self.path; - var after = self.path + '.' + String(n); - if (n > 0) { - before += '.' + String(n - 1); - } - n -= 1; - fs.exists(before, function (exists) { - if (!exists) { - moves(); - } else { - self._debug(' mv %s %s', before, after); - mv(before, after, function (mvErr) { - if (mvErr) { - self.emit('error', mvErr); - finish(); // XXX finish here? - } else { - moves(); - } - }); - } - }) + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } } - - function finish() { - self._debug(' open %s', self.path); - self.stream = fs.createWriteStream(self.path, - {flags: 'a', encoding: 'utf8'}); - var q = self.rotQueue, len = q.length; - for (var i = 0; i < len; i++) { - self.stream.write(q[i]); + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break } - self.rotQueue = []; - self.rotating = false; - self.emit('drain'); - self._setupNextRot(); + } + if (found) return i } + } - var n = this.count; - del(); -}; - -RotatingFileStream.prototype.write = function write(s) { - if (this.rotating) { - this.rotQueue.push(s); - return false; - } else { - return this.stream.write(s); - } -}; - -RotatingFileStream.prototype.end = function end(s) { - this.stream.end(); -}; - -RotatingFileStream.prototype.destroy = function destroy(s) { - this.stream.destroy(); -}; - -RotatingFileStream.prototype.destroySoon = function destroySoon(s) { - this.stream.destroySoon(); -}; - -} /* if (mv) */ + return -1 +} +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} -/** - * RingBuffer is a Writable Stream that just stores the last N records in - * memory. - * - * @param options {Object}, with the following fields: - * - * - limit: number of records to keep in memory - */ -function RingBuffer(options) { - this.limit = options && options.limit ? options.limit : 100; - this.writable = true; - this.records = []; - EventEmitter.call(this); +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } -util.inherits(RingBuffer, EventEmitter); +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } -RingBuffer.prototype.write = function (record) { - if (!this.writable) - throw (new Error('RingBuffer has been ended already')); + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - this.records.push(record); + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} - if (this.records.length > this.limit) - this.records.shift(); +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} - return (true); -}; +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} -RingBuffer.prototype.end = function () { - if (arguments.length > 0) - this.write.apply(this, Array.prototype.slice.call(arguments)); - this.writable = false; -}; +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} -RingBuffer.prototype.destroy = function () { - this.writable = false; - this.emit('close'); -}; +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} -RingBuffer.prototype.destroySoon = function () { - this.destroy(); -}; +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } -//---- Exports + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining -module.exports = Logger; + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } -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; + if (!encoding) encoding = 'utf8' -module.exports.VERSION = VERSION; -module.exports.LOG_VERSION = LOG_VERSION; + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) -module.exports.createLogger = function createLogger(options) { - return new Logger(options); -}; + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) -module.exports.RingBuffer = RingBuffer; -module.exports.RotatingFileStream = RotatingFileStream; + case 'ascii': + return asciiWrite(this, string, offset, length) -// Useful for custom `type == 'raw'` streams that may do JSON stringification -// of log records themselves. Usage: -// var str = JSON.stringify(rec, bunyan.safeCycles()); -module.exports.safeCycles = safeCycles; + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) -}).call(this,{"isBuffer":require("../../../../search-index/node_modules/is-buffer/index.js")},require('_process')) -},{"../../../../search-index/node_modules/is-buffer/index.js":173,"_process":206,"assert":152,"events":169,"fs":155,"os":204,"safe-json-stringify":83,"stream":223,"util":229}],8:[function(require,module,exports){ -(function (Buffer){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; } -exports.isBoolean = isBoolean; -function isNull(arg) { - return arg === null; +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } } -exports.isNull = isNull; -function isNullOrUndefined(arg) { - return arg == null; +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } } -exports.isNullOrUndefined = isNullOrUndefined; -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; + res.push(codePoint) + i += bytesPerSequence + } -function isDate(d) { - return objectToString(d) === '[object Date]'; + return decodeCodePointsArray(res) } -exports.isDate = isDate; -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res } -exports.isPrimitive = isPrimitive; -exports.isBuffer = Buffer.isBuffer; +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) -function objectToString(o) { - return Object.prototype.toString.call(o); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret } -}).call(this,{"isBuffer":require("../../../../search-index/node_modules/is-buffer/index.js")}) -},{"../../../../search-index/node_modules/is-buffer/index.js":173}],9:[function(require,module,exports){ -var util = require('util') - , AbstractIterator = require('abstract-leveldown').AbstractIterator - - -function DeferredIterator (options) { - AbstractIterator.call(this, options) +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - this._options = options - this._iterator = null - this._operations = [] + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret } -util.inherits(DeferredIterator, AbstractIterator) +function hexSlice (buf, start, end) { + var len = buf.length -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) - }) -} + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len -DeferredIterator.prototype._operation = function (method, args) { - if (this._iterator) - return this._iterator[method].apply(this._iterator, args) - this._operations.push({ method: method, args: args }) + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out } -'next end'.split(' ').forEach(function (m) { - DeferredIterator.prototype['_' + m] = function () { - this._operation(m, arguments) +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } -}) - -module.exports = DeferredIterator; - -},{"abstract-leveldown":14,"util":229}],10:[function(require,module,exports){ -(function (Buffer,process){ -var util = require('util') - , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN - , DeferredIterator = require('./deferred-iterator') - -function DeferredLevelDOWN (location) { - AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '') // optional location, who cares? - this._db = undefined - this._operations = [] - this._iterators = [] + return res } -util.inherits(DeferredLevelDOWN, AbstractLevelDOWN) +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end -// called by LevelUP when we have a real DB to take its place -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) - }) -} + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } -DeferredLevelDOWN.prototype._open = function (options, callback) { - return process.nextTick(callback) -} + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } -// queue a new deferred operation -DeferredLevelDOWN.prototype._operation = function (method, args) { - if (this._db) - return this._db[method].apply(this._db, args) - this._operations.push({ method: method, args: args }) -} + if (end < start) end = start -// deferrables -'put get del batch approximateSize'.split(' ').forEach(function (m) { - DeferredLevelDOWN.prototype['_' + m] = function () { - this._operation(m, arguments) + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } } -}) -DeferredLevelDOWN.prototype._isBuffer = function (obj) { - return Buffer.isBuffer(obj) + return newBuf } -DeferredLevelDOWN.prototype._iterator = function (options) { - if (this._db) - return this._db.iterator.apply(this._db, arguments) - var it = new DeferredIterator(options) - this._iterators.push(it) - return it +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } -module.exports = DeferredLevelDOWN -module.exports.DeferredIterator = DeferredIterator +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) -}).call(this,{"isBuffer":require("../../../search-index/node_modules/is-buffer/index.js")},require('_process')) -},{"../../../search-index/node_modules/is-buffer/index.js":173,"./deferred-iterator":9,"_process":206,"abstract-leveldown":14,"util":229}],11:[function(require,module,exports){ -(function (process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } -function AbstractChainedBatch (db) { - this._db = db - this._operations = [] - this._written = false + return val } -AbstractChainedBatch.prototype._checkWritten = function () { - if (this._written) - throw new Error('write() already called on this batch') -} - -AbstractChainedBatch.prototype.put = function (key, value) { - this._checkWritten() +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } - var err = this._db._checkKey(key, 'key', this._db._isBuffer) - if (err) - throw err + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } - if (!this._db._isBuffer(key)) key = String(key) - if (!this._db._isBuffer(value)) value = String(value) + return val +} - if (typeof this._put == 'function' ) - this._put(key, value) - else - this._operations.push({ type: 'put', key: key, value: value }) +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} - return this +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) } -AbstractChainedBatch.prototype.del = function (key) { - this._checkWritten() +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} - var err = this._db._checkKey(key, 'key', this._db._isBuffer) - if (err) throw err +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - if (!this._db._isBuffer(key)) key = String(key) + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} - if (typeof this._del == 'function' ) - this._del(key) - else - this._operations.push({ type: 'del', key: key }) +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - return this + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) } -AbstractChainedBatch.prototype.clear = function () { - this._checkWritten() +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - this._operations = [] + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 - if (typeof this._clear == 'function' ) - this._clear() + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - return this + return val } -AbstractChainedBatch.prototype.write = function (options, callback) { - this._checkWritten() - - if (typeof options == 'function') - callback = options - if (typeof callback != 'function') - throw new Error('write() requires a callback argument') - if (typeof options != 'object') - options = {} - - this._written = true +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - if (typeof this._write == 'function' ) - return this._write(callback) + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 - if (typeof this._db._batch == 'function') - return this._db._batch(this._operations, options, callback) + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - process.nextTick(callback) + return val } -module.exports = AbstractChainedBatch -}).call(this,require('_process')) -},{"_process":206}],12:[function(require,module,exports){ -(function (process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} -function AbstractIterator (db) { - this.db = db - this._ended = false - this._nexting = false +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val } -AbstractIterator.prototype.next = function (callback) { - var self = this +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} - if (typeof callback != 'function') - throw new Error('next() requires a callback argument') +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - if (self._ended) - return callback(new Error('cannot call next() after end()')) - if (self._nexting) - return callback(new Error('cannot call next() before previous next() has completed')) + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} - self._nexting = true - if (typeof self._next == 'function') { - return self._next(function () { - self._nexting = false - callback.apply(null, arguments) - }) - } +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - process.nextTick(function () { - self._nexting = false - callback() - }) + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) } -AbstractIterator.prototype.end = function (callback) { - if (typeof callback != 'function') - throw new Error('end() requires a callback argument') +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} - if (this._ended) - return callback(new Error('end() already called on iterator')) +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} - this._ended = true +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} - if (typeof this._end == 'function') - return this._end(callback) +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} - process.nextTick(callback) +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') } -module.exports = AbstractIterator +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } -}).call(this,require('_process')) -},{"_process":206}],13:[function(require,module,exports){ -(function (Buffer,process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } -var xtend = require('xtend') - , AbstractIterator = require('./abstract-iterator') - , AbstractChainedBatch = require('./abstract-chained-batch') + return offset + byteLength +} -function AbstractLevelDOWN (location) { - if (!arguments.length || location === undefined) - throw new Error('constructor requires at least a location argument') +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } - if (typeof location != 'string') - throw new Error('constructor requires a location string argument') + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } - this.location = location - this.status = 'new' + return offset + byteLength } -AbstractLevelDOWN.prototype.open = function (options, callback) { - var self = this - , oldStatus = this.status - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('open() requires a callback argument') +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} - if (typeof options != 'object') - options = {} +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} - options.createIfMissing = options.createIfMissing != false - options.errorIfExists = !!options.errorIfExists +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} - if (typeof this._open == 'function') { - this.status = 'opening' - this._open(options, function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'open' - callback() - }) +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) } else { - this.status = 'open' - process.nextTick(callback) + objectWriteUInt16(this, value, offset, false) } + return offset + 2 } -AbstractLevelDOWN.prototype.close = function (callback) { - var self = this - , oldStatus = this.status +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} - if (typeof callback != 'function') - throw new Error('close() requires a callback argument') +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} - if (typeof this._close == 'function') { - this.status = 'closing' - this._close(function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'closed' - callback() - }) +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) } else { - this.status = 'closed' - process.nextTick(callback) + objectWriteUInt32(this, value, offset, false) } + return offset + 4 } -AbstractLevelDOWN.prototype.get = function (key, options, callback) { - var err +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) - if (typeof options == 'function') - callback = options + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - if (typeof callback != 'function') - throw new Error('get() requires a callback argument') + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - if (err = this._checkKey(key, 'key', this._isBuffer)) - return callback(err) + return offset + byteLength +} - if (!this._isBuffer(key)) - key = String(key) +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) - if (typeof options != 'object') - options = {} + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - options.asBuffer = options.asBuffer != false + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - if (typeof this._get == 'function') - return this._get(key, options, callback) + return offset + byteLength +} - process.nextTick(function () { callback(new Error('NotFound')) }) +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 } -AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { - var err +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} - if (typeof options == 'function') - callback = options +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} - if (typeof callback != 'function') - throw new Error('put() requires a callback argument') +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} - if (err = this._checkKey(key, 'key', this._isBuffer)) - return callback(err) +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} - if (!this._isBuffer(key)) - key = String(key) +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') +} - // coerce value to string in node, don't touch it in browser - // (indexeddb can store any JS type) - if (value != null && !this._isBuffer(value) && !process.browser) - value = String(value) +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} - if (typeof options != 'object') - options = {} +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} - if (typeof this._put == 'function') - return this._put(key, value, options, callback) +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} - process.nextTick(callback) +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 } -AbstractLevelDOWN.prototype.del = function (key, options, callback) { - var err +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} - if (typeof options == 'function') - callback = options +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} - if (typeof callback != 'function') - throw new Error('del() requires a callback argument') - - if (err = this._checkKey(key, 'key', this._isBuffer)) - return callback(err) - - if (!this._isBuffer(key)) - key = String(key) - - if (typeof options != 'object') - options = {} - - if (typeof this._del == 'function') - return this._del(key, options, callback) - - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.batch = function (array, options, callback) { - if (!arguments.length) - return this._chainedBatch() - - if (typeof options == 'function') - callback = options - - if (typeof array == 'function') - callback = array - - if (typeof callback != 'function') - throw new Error('batch(array) requires a callback argument') - - if (!Array.isArray(array)) - return callback(new Error('batch(array) requires an array argument')) +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start - if (!options || typeof options != 'object') - options = {} + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 - var i = 0 - , l = array.length - , e - , err + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') - for (; i < l; i++) { - e = array[i] - if (typeof e != 'object') - continue + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } - if (err = this._checkKey(e.type, 'type', this._isBuffer)) - return callback(err) + var len = end - start + var i - if (err = this._checkKey(e.key, 'key', this._isBuffer)) - return callback(err) + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) } - if (typeof this._batch == 'function') - return this._batch(array, options, callback) - - process.nextTick(callback) + return len } -//TODO: remove from here, not a necessary primitive -AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) { - if ( start == null - || end == null - || typeof start == 'function' - || typeof end == 'function') { - throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 } - if (typeof callback != 'function') - throw new Error('approximateSize() requires a callback argument') - - if (!this._isBuffer(start)) - start = String(start) - - if (!this._isBuffer(end)) - end = String(end) - - if (typeof this._approximateSize == 'function') - return this._approximateSize(start, end, callback) - - process.nextTick(function () { - callback(null, 0) - }) -} + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } -AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { - var self = this + if (end <= start) { + return this + } - options = xtend(options) + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) { - if (options[o] && self._isBuffer(options[o]) && options[o].length === 0) - delete options[o] - }) + if (!val) val = 0 - options.reverse = !!options.reverse - options.keys = options.keys != false - options.values = options.values != false - options.limit = 'limit' in options ? options.limit : -1 - options.keyAsBuffer = options.keyAsBuffer != false - options.valueAsBuffer = options.valueAsBuffer != false + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } - return options + return this } -AbstractLevelDOWN.prototype.iterator = function (options) { - if (typeof options != 'object') - options = {} - - options = this._setupIteratorOptions(options) +// HELPER FUNCTIONS +// ================ - if (typeof this._iterator == 'function') - return this._iterator(options) +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - return new AbstractIterator(this) +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str } -AbstractLevelDOWN.prototype._chainedBatch = function () { - return new AbstractChainedBatch(this) +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') } -AbstractLevelDOWN.prototype._isBuffer = function (obj) { - return Buffer.isBuffer(obj) +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) } -AbstractLevelDOWN.prototype._checkKey = function (obj, type) { +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] - if (obj === null || obj === undefined) - return new Error(type + ' cannot be `null` or `undefined`') + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) - if (this._isBuffer(obj)) { - if (obj.length === 0) - return new Error(type + ' cannot be an empty Buffer') - } else if (String(obj) === '') - return new Error(type + ' cannot be an empty String') -} + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } -module.exports = AbstractLevelDOWN + // valid lead + leadSurrogate = codePoint -}).call(this,{"isBuffer":require("../../../../../search-index/node_modules/is-buffer/index.js")},require('_process')) -},{"../../../../../search-index/node_modules/is-buffer/index.js":173,"./abstract-chained-batch":11,"./abstract-iterator":12,"_process":206,"xtend":92}],14:[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') + continue + } -},{"./abstract-chained-batch":11,"./abstract-iterator":12,"./abstract-leveldown":13,"./is-leveldown":15}],15:[function(require,module,exports){ -var AbstractLevelDOWN = require('./abstract-leveldown') + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } -function isLevelDOWN (db) { - if (!db || typeof db !== 'object') - return false - return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) { - // TODO remove approximateSize check when method is gone - return name[0] != '_' && name != 'approximateSize' - }).every(function (name) { - return typeof db[name] == 'function' - }) -} - -module.exports = isLevelDOWN + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } -},{"./abstract-leveldown":13}],16:[function(require,module,exports){ -const pumpify = require('pumpify') -const stopwords = [] + leadSurrogate = null -const CalculateTermFrequency = exports.CalculateTermFrequency = - require('./pipeline/CalculateTermFrequency.js') + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } -const CreateCompositeVector = exports.CreateCompositeVector = - require('./pipeline/CreateCompositeVector.js') + return bytes +} -const CreateSortVectors = exports.CreateSortVectors = - require('./pipeline/CreateSortVectors.js') +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} -const CreateStoredDocument = exports.CreateStoredDocument = - require('./pipeline/CreateStoredDocument.js') +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break -const FieldedSearch = exports.FieldedSearch = - require('./pipeline/FieldedSearch.js') + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } -const IngestDoc = exports.IngestDoc = - require('./pipeline/IngestDoc.js') + return byteArray +} -const LowCase = exports.LowCase = - require('./pipeline/LowCase.js') +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} -const NormaliseFields = exports.NormaliseFields = - require('./pipeline/NormaliseFields.js') +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} -const RemoveStopWords = exports.RemoveStopWords = - require('./pipeline/RemoveStopWords.js') +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} -const Spy = exports.Spy = - require('./pipeline/Spy.js') +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":6,"ieee754":39,"isarray":43}],10:[function(require,module,exports){ +(function (Buffer,process){ +/** + * Copyright (c) 2017 Trent Mick. + * Copyright (c) 2017 Joyent Inc. + * + * The bunyan logging library for node.js. + * + * -*- mode: js -*- + * vim: expandtab:ts=4:sw=4 + */ -Spy // appease linter +var VERSION = '1.8.12'; -const Tokeniser = exports.Tokeniser = - require('./pipeline/Tokeniser.js') +/* + * Bunyan log format version. This becomes the 'v' field on all log records. + * This will be incremented if there is any backward incompatible change to + * the log record format. Details will be in 'CHANGES.md' (the change log). + */ +var LOG_VERSION = 0; -exports.pipeline = function (options) { - options = Object.assign({}, { - separator: /[|' .,\-|(\\\n)]+/, - searchable: true, - stopwords: stopwords, - nGramLength: 1, - fieldedSearch: true - }, 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) -} +var xxx = function xxx(s) { // internal dev/debug logging + var args = ['XX' + 'X: '+s].concat( + Array.prototype.slice.call(arguments, 1)); + console.error.apply(this, args); +}; +var xxx = function xxx() {}; // comment out to turn on debug logging -},{"./pipeline/CalculateTermFrequency.js":17,"./pipeline/CreateCompositeVector.js":18,"./pipeline/CreateSortVectors.js":19,"./pipeline/CreateStoredDocument.js":20,"./pipeline/FieldedSearch.js":21,"./pipeline/IngestDoc.js":22,"./pipeline/LowCase.js":23,"./pipeline/NormaliseFields.js":24,"./pipeline/RemoveStopWords.js":25,"./pipeline/Spy.js":26,"./pipeline/Tokeniser.js":27,"pumpify":73}],17:[function(require,module,exports){ -const tv = require('term-vector') -const tf = require('term-frequency') -const Transform = require('stream').Transform -const util = require('util') -// convert term-frequency vectors into object maps -const objectify = function (result, item) { - result[item[0].join(' ')] = item[1] - return result +/* + * Runtime environment notes: + * + * Bunyan is intended to run in a number of runtime environments. Here are + * some notes on differences for those envs and how the code copes. + * + * - node.js: The primary target environment. + * - NW.js: http://nwjs.io/ An *app* environment that feels like both a + * node env -- it has node-like globals (`process`, `global`) and + * browser-like globals (`window`, `navigator`). My *understanding* is that + * bunyan can operate as if this is vanilla node.js. + * - browser: Failing the above, we sniff using the `window` global + * . + * - browserify: http://browserify.org/ A browser-targetting bundler of + * node.js deps. The runtime is a browser env, so can't use fs access, + * etc. Browserify's build looks for `require()` imports + * to bundle. For some imports it won't be able to handle, we "hide" + * from browserify with `require('frobshizzle' + '')`. + * - Other? Please open issues if things are broken. + */ +var runtimeEnv; +if (typeof (process) !== 'undefined' && process.versions) { + if (process.versions.nw) { + runtimeEnv = 'nw'; + } else if (process.versions.node) { + runtimeEnv = 'node'; + } } - -const CalculateTermFrequency = function (options) { - Transform.call(this, { objectMode: true }) +if (!runtimeEnv && typeof (window) !== 'undefined' && + window.window === window) { + runtimeEnv = 'browser'; } -module.exports = CalculateTermFrequency -util.inherits(CalculateTermFrequency, Transform) -CalculateTermFrequency.prototype._transform = function (doc, encoding, end) { - var options = Object.assign({}, { - fieldOptions: {}, - nGramLength: 1, - searchable: true, - 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]) - var field = doc.tokenised[fieldName] - if (fieldOptions.searchable) { - doc.vector[fieldName] = tf.getTermFrequency( - tv.getVector(field, fieldOptions.nGramLength), { - scheme: tf.doubleNormalization0point5, - weight: fieldOptions.weight +if (!runtimeEnv) { + throw new Error('unknown runtime environment'); +} + + +var os, fs, dtrace; +if (runtimeEnv === 'browser') { + os = { + hostname: function () { + return window.location.host; } - ).reduce(objectify, {}) - doc.vector[fieldName]['*'] = 1 // wildcard search + }; + fs = {}; + dtrace = null; +} else { + os = require('os'); + fs = require('fs'); + try { + dtrace = require('dtrace-provider' + ''); + } catch (e) { + dtrace = null; } - } - this.push(doc) - return end() } +var util = require('util'); +var assert = require('assert'); +var EventEmitter = require('events').EventEmitter; +var stream = require('stream'); -},{"stream":223,"term-frequency":86,"term-vector":87,"util":229}],18:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') - -const CreateCompositeVector = function (options) { - Transform.call(this, { objectMode: true }) +try { + var safeJsonStringify = require('safe-json-stringify'); +} catch (e) { + safeJsonStringify = null; } -module.exports = CreateCompositeVector -util.inherits(CreateCompositeVector, Transform) -CreateCompositeVector.prototype._transform = function (doc, encoding, end) { - var options = Object.assign({}, { - fieldOptions: {}, - searchable: true - }, 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 - } - } - } - this.push(doc) - return end() +if (process.env.BUNYAN_TEST_NO_SAFE_JSON_STRINGIFY) { + safeJsonStringify = null; } -},{"stream":223,"util":229}],19:[function(require,module,exports){ -const tf = require('term-frequency') -const tv = require('term-vector') -const Transform = require('stream').Transform -const util = require('util') - -// convert term-frequency vectors into object maps -const objectify = function (result, item) { - result[item[0]] = item[1] - return result +// The 'mv' module is required for rotating-file stream support. +try { + var mv = require('mv' + ''); +} catch (e) { + mv = null; } -const CreateSortVectors = function (options) { - Transform.call(this, { objectMode: true }) +try { + var sourceMapSupport = require('source-map-support' + ''); +} catch (_) { + sourceMapSupport = null; } -module.exports = CreateSortVectors -util.inherits(CreateSortVectors, Transform) -CreateSortVectors.prototype._transform = function (doc, encoding, end) { - var options = Object.assign({}, { - fieldOptions: {}, - sortable: false - }, doc.options || {}) - for (var fieldName in doc.vector) { - var fieldOptions = Object.assign({}, { - sortable: options.sortable - }, options.fieldOptions[fieldName]) - if (fieldOptions.sortable) { - doc.vector[fieldName] = tf.getTermFrequency( - tv.getVector(doc.tokenised[fieldName]), - { scheme: tf.selfString } - ).reduce(objectify, {}) + + +//---- Internal support stuff + +/** + * A shallow copy of an object. Bunyan logging attempts to never cause + * exceptions, so this function attempts to handle non-objects gracefully. + */ +function objCopy(obj) { + if (obj == null) { // null or undefined + return obj; + } else if (Array.isArray(obj)) { + return obj.slice(); + } else if (typeof (obj) === 'object') { + var copy = {}; + Object.keys(obj).forEach(function (k) { + copy[k] = obj[k]; + }); + return copy; + } else { + return obj; } - } - this.push(doc) - return end() } -},{"stream":223,"term-frequency":86,"term-vector":87,"util":229}],20:[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 -const Transform = require('stream').Transform -const util = require('util') +var format = util.format; +if (!format) { + // If node < 0.6, then use its `util.format`: + // : + var inspect = util.inspect; + var formatRegExp = /%[sdj%]/g; + format = function format(f) { + if (typeof (f) !== 'string') { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } -const CreateStoredDocument = function (options) { - Transform.call(this, { objectMode: true }) + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function (x) { + if (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; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (x === null || typeof (x) !== 'object') { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; } -module.exports = CreateStoredDocument -util.inherits(CreateStoredDocument, Transform) -CreateStoredDocument.prototype._transform = function (doc, encoding, end) { - var options = Object.assign({}, { - fieldOptions: {}, - storeable: true - }, doc.options || {}) - for (var fieldName in doc.raw) { - var fieldOptions = Object.assign({}, { - // Store a cache of this field in the index - storeable: options.storeable - }, options.fieldOptions[fieldName]) - if (fieldName === 'id') fieldOptions.storeable = true - if (fieldOptions.storeable) { - doc.stored[fieldName] = JSON.parse(JSON.stringify(doc.raw[fieldName])) + + +/** + * Gather some caller info 3 stack levels up. + * See . + */ +function getCaller3Info() { + if (this === undefined) { + // Cannot access caller info in 'strict' mode. + return; } - } - this.push(doc) - return end() -} + var obj = {}; + var saveLimit = Error.stackTraceLimit; + var savePrepare = Error.prepareStackTrace; + Error.stackTraceLimit = 3; -},{"stream":223,"util":229}],21:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') + Error.prepareStackTrace = function (_, stack) { + var caller = stack[2]; + if (sourceMapSupport) { + caller = sourceMapSupport.wrapCallSite(caller); + } + obj.file = caller.getFileName(); + obj.line = caller.getLineNumber(); + var func = caller.getFunctionName(); + if (func) + obj.func = func; + }; + Error.captureStackTrace(this, getCaller3Info); + this.stack; -const FieldedSearch = function (options) { - Transform.call(this, { objectMode: true }) -} -module.exports = FieldedSearch -util.inherits(FieldedSearch, Transform) -FieldedSearch.prototype._transform = function (doc, encoding, end) { - var options = Object.assign({}, { - fieldOptions: {}, - fieldedSearch: true - }, doc.options || {}) - for (var fieldName in doc.vector) { - var fieldOptions = Object.assign({}, { - fieldedSearch: options.fieldedSearch - }, options.fieldOptions[fieldName]) // can this field be searched on? - if (!fieldOptions.fieldedSearch && fieldName !== '*') delete doc.vector[fieldName] - } - if (options.log) options.log.info(doc) - this.push(doc) - return end() + Error.stackTraceLimit = saveLimit; + Error.prepareStackTrace = savePrepare; + return obj; } -},{"stream":223,"util":229}],22:[function(require,module,exports){ -const util = require('util') -const Transform = require('stream').Transform -const IngestDoc = function (options) { - this.options = options - this.i = 0 - Transform.call(this, { objectMode: true }) +function _indent(s, indent) { + if (!indent) indent = ' '; + var lines = s.split(/\r?\n/g); + return indent + lines.join('\n' + indent); } -module.exports = IngestDoc -util.inherits(IngestDoc, Transform) -IngestDoc.prototype._transform = function (doc, encoding, end) { - var that = this - var ingestedDoc = { - normalised: {}, - options: that.options, - raw: JSON.parse(JSON.stringify(doc)), - stored: {}, - tokenised: {}, - vector: {} - } - // if there is no id, generate a a stringified one that is sorted - // by time (higher values more recent), so that a natural sort will - // yeild the most recent docs first - if (!doc.id) { - // TODO ++this.i should be left padded - ingestedDoc.id = Date.now() + '-' + ++this.i - } else { - ingestedDoc.id = String(doc.id) - } - this.push(ingestedDoc) // should this actually be stringified? - return end() +/** + * Warn about an bunyan processing error. + * + * @param msg {String} Message with which to warn. + * @param dedupKey {String} Optional. A short string key for this warning to + * have its warning only printed once. + */ +function _warn(msg, dedupKey) { + assert.ok(msg); + if (dedupKey) { + if (_warned[dedupKey]) { + return; + } + _warned[dedupKey] = true; + } + process.stderr.write(msg + '\n'); } +function _haveWarned(dedupKey) { + return _warned[dedupKey]; +} +var _warned = {}; -},{"stream":223,"util":229}],23:[function(require,module,exports){ -// insert all search tokens in lower case -const Transform = require('stream').Transform -const util = require('util') - -const LowCase = function () { - Transform.call(this, { objectMode: true }) -} -module.exports = LowCase -util.inherits(LowCase, Transform) -LowCase.prototype._transform = function (doc, encoding, end) { - var options = this.options = Object.assign({}, { - fieldOptions: {}, - preserveCase: false - }, doc.options || {}) - for (var fieldName in doc.normalised) { - if (fieldName === 'id') continue // dont lowcase ID field - var fieldOptions = Object.assign({}, { - preserveCase: options.preserveCase - }, options.fieldOptions[fieldName]) - if (!fieldOptions.preserveCase) { - if (Object.prototype.toString.call(doc.normalised[fieldName]) === '[object Array]') { - doc.normalised[fieldName].map(function (token) { - return token.toLowerCase() - }) - } else { - doc.normalised[fieldName] = doc.normalised[fieldName].toLowerCase() - } - } - } - this.push(doc) - return end() -} - -},{"stream":223,"util":229}],24:[function(require,module,exports){ -const util = require('util') -const Transform = require('stream').Transform - -const NormaliseFields = function () { - Transform.call(this, { objectMode: true }) -} -module.exports = NormaliseFields -util.inherits(NormaliseFields, Transform) -NormaliseFields.prototype._transform = function (doc, encoding, end) { - for (var fieldName in doc.raw) { - if (Object.prototype.toString.call(doc.raw[fieldName]) === '[object Array]') { - doc.normalised[fieldName] = doc.raw[fieldName].map(function (item) { - return JSON.stringify(item).split(/[[\],{}:"]+/).join(' ').trim() - }) - } else if (Object.prototype.toString.call(doc.raw[fieldName]) !== '[object String]') { - // if the input object is not a string: jsonify and split on JSON - // characters - doc.normalised[fieldName] = JSON.stringify(doc.raw[fieldName]) - .split(/[[\],{}:"]+/).join(' ').trim() +function ConsoleRawStream() {} +ConsoleRawStream.prototype.write = function (rec) { + if (rec.level < INFO) { + console.log(rec); + } else if (rec.level < WARN) { + console.info(rec); + } else if (rec.level < ERROR) { + console.warn(rec); } else { - doc.normalised[fieldName] = doc.raw[fieldName].trim() + console.error(rec); } - } - this.push(doc) - return end() -} +}; -},{"stream":223,"util":229}],25:[function(require,module,exports){ -// removes stopwords from indexed docs -const Transform = require('stream').Transform -const util = require('util') -const RemoveStopWords = function (options) { - Transform.call(this, { objectMode: true }) -} -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]) - // remove stopwords - doc.tokenised[fieldName] = - doc.tokenised[fieldName].filter(function (item) { - return (fieldOptions.stopwords.indexOf(item) === -1) - }).filter(function (i) { // strip out empty elements - return i - }) - } - this.push(doc) - return end() -} +//---- Levels -},{"stream":223,"util":229}],26:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') +var TRACE = 10; +var DEBUG = 20; +var INFO = 30; +var WARN = 40; +var ERROR = 50; +var FATAL = 60; -const Spy = function () { - Transform.call(this, { objectMode: true }) -} -module.exports = Spy -util.inherits(Spy, Transform) -Spy.prototype._transform = function (doc, encoding, end) { - console.log(JSON.stringify(doc, null, 2)) - this.push(doc) - return end() -} +var levelFromName = { + 'trace': TRACE, + 'debug': DEBUG, + 'info': INFO, + 'warn': WARN, + 'error': ERROR, + 'fatal': FATAL +}; +var nameFromLevel = {}; +Object.keys(levelFromName).forEach(function (name) { + nameFromLevel[levelFromName[name]] = name; +}); -},{"stream":223,"util":229}],27:[function(require,module,exports){ -// split up fields in to arrays of tokens -const Transform = require('stream').Transform -const util = require('util') +// Dtrace probes. +var dtp = undefined; +var probes = dtrace && {}; -const Tokeniser = function (options) { - Transform.call(this, { objectMode: true }) -} -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({}, { - // A string.split() expression to tokenize raw field input - separator: options.separator - }, options.fieldOptions[fieldName]) - // if field is already an array, simply leave it as such - if (Object.prototype.toString.call(doc.normalised[fieldName]) === '[object Array]') { - doc.tokenised[fieldName] = doc.normalised[fieldName] +/** + * Resolve a level number, name (upper or lowercase) to a level number value. + * + * @param nameOrNum {String|Number} A level name (case-insensitive) or positive + * integer level. + * @api public + */ +function resolveLevel(nameOrNum) { + var level; + var type = typeof (nameOrNum); + if (type === 'string') { + level = levelFromName[nameOrNum.toLowerCase()]; + if (!level) { + throw new Error(format('unknown level name: "%s"', nameOrNum)); + } + } else if (type !== 'number') { + throw new TypeError(format('cannot resolve level: invalid arg (%s):', + type, nameOrNum)); + } else if (nameOrNum < 0 || Math.floor(nameOrNum) !== nameOrNum) { + throw new TypeError(format('level is not a positive integer: %s', + nameOrNum)); } else { - doc.tokenised[fieldName] = - doc.normalised[fieldName].split(fieldOptions.separator) + level = nameOrNum; } - } - this.push(doc) - return end() -} - -},{"stream":223,"util":229}],28:[function(require,module,exports){ -(function (process,Buffer){ -var stream = require('readable-stream') -var eos = require('end-of-stream') -var inherits = require('inherits') -var shift = require('stream-shift') - -var SIGNAL_FLUSH = new Buffer([0]) - -var onuncork = function(self, fn) { - if (self._corked) self.once('uncork', fn) - else fn() -} - -var destroyer = function(self, end) { - return function(err) { - if (err) self.destroy(err.message === 'premature close' ? null : err) - else if (end && !self._ended) self.end() - } + return level; } -var end = function(ws, fn) { - if (!ws) return fn() - if (ws._writableState && ws._writableState.finished) return fn() - if (ws._writableState) return ws.end(fn) - ws.end() - fn() -} -var toStreams2 = function(rs) { - return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) +function isWritable(obj) { + if (obj instanceof stream.Writable) { + return true; + } + return typeof (obj.write) === 'function'; } -var 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 || opts.destroy !== false - this._forwardEnd = !opts || opts.end !== false - this._corked = 1 // start corked - this._ondrain = null - this._drained = false - this._forwarding = false - this._unwrite = null - this._unread = null - this._ended = false +//---- Logger class - this.destroyed = false +/** + * Create a Logger instance. + * + * @param options {Object} See documentation for full details. At minimum + * this must include a 'name' string key. Configuration keys: + * - `streams`: specify the logger output streams. This is an array of + * objects with these fields: + * - `type`: The stream type. See README.md for full details. + * Often this is implied by the other fields. Examples are + * 'file', 'stream' and "raw". + * - `level`: Defaults to 'info'. + * - `path` or `stream`: The specify the file path or writeable + * stream to which log records are written. E.g. + * `stream: process.stdout`. + * - `closeOnExit` (boolean): Optional. Default is true for a + * 'file' stream when `path` is given, false otherwise. + * See README.md for full details. + * - `level`: set the level for a single output stream (cannot be used + * with `streams`) + * - `stream`: the output stream for a logger with just one, e.g. + * `process.stdout` (cannot be used with `streams`) + * - `serializers`: object mapping log record field names to + * serializing functions. See README.md for details. + * - `src`: Boolean (default false). Set true to enable 'src' automatic + * field with log call source info. + * All other keys are log record fields. + * + * An alternative *internal* call signature is used for creating a child: + * new Logger(, [, ]); + * + * @param _childSimple (Boolean) An assertion that the given `_childOptions` + * (a) only add fields (no config) and (b) no serialization handling is + * required for them. IOW, this is a fast path for frequent child + * creation. + */ +function Logger(options, _childOptions, _childSimple) { + xxx('Logger start:', options) + if (!(this instanceof Logger)) { + return new Logger(options, _childOptions); + } - if (writable) this.setWritable(writable) - if (readable) this.setReadable(readable) -} - -inherits(Duplexify, stream.Duplex) - -Duplexify.obj = function(writable, readable, opts) { - if (!opts) opts = {} - opts.objectMode = true - opts.highWaterMark = 16 - return new Duplexify(writable, readable, opts) -} + // Input arg validation. + var parent; + if (_childOptions !== undefined) { + parent = options; + options = _childOptions; + if (!(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('options.name (string) is required'); + } + } else { + if (options.name) { + throw new TypeError( + 'invalid options.name: child cannot set logger name'); + } + } + 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 && (typeof (options.serializers) !== 'object' || + Array.isArray(options.serializers))) { + throw new TypeError('invalid options.serializers: must be an object') + } -Duplexify.prototype.cork = function() { - if (++this._corked === 1) this.emit('cork') -} + EventEmitter.call(this); -Duplexify.prototype.uncork = function() { - if (this._corked && --this._corked === 0) this.emit('uncork') -} + // Fast path for simple child creation. + if (parent && _childSimple) { + // `_isSimpleChild` is a signal to stream close handling that this child + // owns none of its streams. + this._isSimpleChild = true; -Duplexify.prototype.setWritable = function(writable) { - if (this._unwrite) this._unwrite() + this._level = parent._level; + this.streams = parent.streams; + this.serializers = parent.serializers; + this.src = parent.src; + var fields = this.fields = {}; + var parentFieldNames = Object.keys(parent.fields); + for (var i = 0; i < parentFieldNames.length; i++) { + var name = parentFieldNames[i]; + fields[name] = parent.fields[name]; + } + var names = Object.keys(options); + for (var i = 0; i < names.length; i++) { + var name = names[i]; + fields[name] = options[name]; + } + return; + } - if (this.destroyed) { - if (writable && writable.destroy) writable.destroy() - return - } + // Start values. + var self = this; + if (parent) { + this._level = parent._level; + this.streams = []; + for (var i = 0; i < parent.streams.length; i++) { + var s = objCopy(parent.streams[i]); + s.closeOnExit = false; // Don't own parent stream. + this.streams.push(s); + } + this.serializers = objCopy(parent.serializers); + this.src = parent.src; + this.fields = objCopy(parent.fields); + if (options.level) { + this.level(options.level); + } + } else { + this._level = Number.POSITIVE_INFINITY; + this.streams = []; + this.serializers = null; + this.src = false; + this.fields = {}; + } - if (writable === null || writable === false) { - this.end() - return - } + if (!dtp && dtrace) { + dtp = dtrace.createDTraceProvider('bunyan'); - var self = this - var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) + for (var level in levelFromName) { + var probe; - var ondrain = function() { - var ondrain = self._ondrain - self._ondrain = null - if (ondrain) ondrain() - } + probes[levelFromName[level]] = probe = + dtp.addProbe('log-' + level, 'char *'); - var clear = function() { - self._writable.removeListener('drain', ondrain) - unend() - } + // Explicitly add a reference to dtp to prevent it from being GC'd + probe.dtp = dtp; + } - if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks + dtp.enable(); + } - this._writable = writable - this._writable.on('drain', ondrain) - this._unwrite = clear + // Handle *config* options (i.e. options that are not just plain data + // for log records). + if (options.stream) { + self.addStream({ + type: 'stream', + stream: options.stream, + closeOnExit: false, + level: options.level + }); + } else if (options.streams) { + options.streams.forEach(function (s) { + self.addStream(s, options.level); + }); + } else if (parent && options.level) { + this.level(options.level); + } else if (!parent) { + if (runtimeEnv === 'browser') { + /* + * In the browser we'll be emitting to console.log by default. + * Any console.log worth its salt these days can nicely render + * and introspect objects (e.g. the Firefox and Chrome console) + * so let's emit the raw log record. Are there browsers for which + * that breaks things? + */ + self.addStream({ + type: 'raw', + stream: new ConsoleRawStream(), + closeOnExit: false, + level: options.level + }); + } else { + self.addStream({ + type: 'stream', + stream: process.stdout, + closeOnExit: false, + level: options.level + }); + } + } + if (options.serializers) { + self.addSerializers(options.serializers); + } + if (options.src) { + this.src = true; + } + xxx('Logger: ', self) - this.uncork() // always uncork setWritable + // Fields. + // These are the default fields for log records (minus the attributes + // removed in this constructor). To allow storing raw log records + // (unrendered), `this.fields` must never be mutated. Create a copy for + // any changes. + var fields = objCopy(options); + delete fields.stream; + delete fields.level; + delete fields.streams; + delete fields.serializers; + delete fields.src; + if (this.serializers) { + this._applySerializers(fields); + } + if (!fields.hostname && !self.fields.hostname) { + fields.hostname = os.hostname(); + } + if (!fields.pid) { + fields.pid = process.pid; + } + Object.keys(fields).forEach(function (k) { + self.fields[k] = fields[k]; + }); } -Duplexify.prototype.setReadable = function(readable) { - if (this._unread) this._unread() - - if (this.destroyed) { - if (readable && readable.destroy) readable.destroy() - return - } +util.inherits(Logger, EventEmitter); - if (readable === null || readable === false) { - this.push(null) - this.resume() - return - } - var self = this - var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) +/** + * Add a stream + * + * @param stream {Object}. Object with these fields: + * - `type`: The stream type. See README.md for full details. + * Often this is implied by the other fields. Examples are + * 'file', 'stream' and "raw". + * - `path` or `stream`: The specify the file path or writeable + * stream to which log records are written. E.g. + * `stream: process.stdout`. + * - `level`: Optional. Falls back to `defaultLevel`. + * - `closeOnExit` (boolean): Optional. Default is true for a + * 'file' stream when `path` is given, false otherwise. + * See README.md for full details. + * @param defaultLevel {Number|String} Optional. A level to use if + * `stream.level` is not set. If neither is given, this defaults to INFO. + */ +Logger.prototype.addStream = function addStream(s, defaultLevel) { + var self = this; + if (defaultLevel === null || defaultLevel === undefined) { + defaultLevel = INFO; + } - var onreadable = function() { - self._forward() - } + s = objCopy(s); - var onend = function() { - self.push(null) - } + // Implicit 'type' from other args. + if (!s.type) { + if (s.stream) { + s.type = 'stream'; + } else if (s.path) { + s.type = 'file' + } + } + s.raw = (s.type === 'raw'); // PERF: Allow for faster check in `_emit`. - var clear = function() { - self._readable2.removeListener('readable', onreadable) - self._readable2.removeListener('end', onend) - unend() - } + if (s.level !== undefined) { + s.level = resolveLevel(s.level); + } else { + s.level = resolveLevel(defaultLevel); + } + if (s.level < self._level) { + self._level = s.level; + } - this._drained = true - this._readable = readable - this._readable2 = readable._readableState ? readable : toStreams2(readable) - this._readable2.on('readable', onreadable) - this._readable2.on('end', onend) - this._unread = clear + switch (s.type) { + case 'stream': + assert.ok(isWritable(s.stream), + '"stream" stream is not writable: ' + util.inspect(s.stream)); - this._forward() -} + if (!s.closeOnExit) { + s.closeOnExit = false; + } + break; + case 'file': + if (s.reemitErrorEvents === undefined) { + s.reemitErrorEvents = true; + } + if (!s.stream) { + s.stream = fs.createWriteStream(s.path, + {flags: 'a', encoding: 'utf8'}); + if (!s.closeOnExit) { + s.closeOnExit = true; + } + } else { + if (!s.closeOnExit) { + s.closeOnExit = false; + } + } + break; + case 'rotating-file': + assert.ok(!s.stream, + '"rotating-file" stream should not give a "stream"'); + assert.ok(s.path); + assert.ok(mv, '"rotating-file" stream type is not supported: ' + + 'missing "mv" module'); + s.stream = new RotatingFileStream(s); + if (!s.closeOnExit) { + s.closeOnExit = true; + } + break; + case 'raw': + if (!s.closeOnExit) { + s.closeOnExit = false; + } + break; + default: + throw new TypeError('unknown stream type "' + s.type + '"'); + } -Duplexify.prototype._read = function() { - this._drained = true - this._forward() -} + if (s.reemitErrorEvents && typeof (s.stream.on) === 'function') { + // TODO: When we have `.close()`, it should remove event + // listeners to not leak Logger instances. + s.stream.on('error', function onStreamError(err) { + self.emit('error', err, s); + }); + } -Duplexify.prototype._forward = function() { - if (this._forwarding || !this._readable2 || !this._drained) return - this._forwarding = true + self.streams.push(s); + delete self.haveNonRawStreams; // reset +} - var data - while (this._drained && (data = shift(this._readable2)) !== null) { - if (this.destroyed) continue - this._drained = this.push(data) - } +/** + * Add serializers + * + * @param serializers {Object} Optional. Object mapping log record field names + * to serializing functions. See README.md for details. + */ +Logger.prototype.addSerializers = function addSerializers(serializers) { + var self = this; - this._forwarding = false + if (!self.serializers) { + self.serializers = {}; + } + Object.keys(serializers).forEach(function (field) { + var serializer = serializers[field]; + if (typeof (serializer) !== 'function') { + throw new TypeError(format( + 'invalid serializer for "%s" field: must be a function', + field)); + } else { + self.serializers[field] = serializer; + } + }); } -Duplexify.prototype.destroy = function(err) { - if (this.destroyed) return - this.destroyed = true - var self = this - process.nextTick(function() { - self._destroy(err) - }) -} -Duplexify.prototype._destroy = function(err) { - if (err) { - var ondrain = this._ondrain - this._ondrain = null - if (ondrain) ondrain(err) - else this.emit('error', err) - } +/** + * Create a child logger, typically to add a few log record fields. + * + * This can be useful when passing a logger to a sub-component, e.g. a + * 'wuzzle' component of your service: + * + * var wuzzleLog = log.child({component: 'wuzzle'}) + * var wuzzle = new Wuzzle({..., log: wuzzleLog}) + * + * Then log records from the wuzzle code will have the same structure as + * the app log, *plus the component='wuzzle' field*. + * + * @param options {Object} Optional. Set of options to apply to the child. + * All of the same options for a new Logger apply here. Notes: + * - The parent's streams are inherited and cannot be removed in this + * call. Any given `streams` are *added* to the set inherited from + * the parent. + * - The parent's serializers are inherited, though can effectively be + * overwritten by using duplicate keys. + * - Can use `level` to set the level of the streams inherited from + * the parent. The level for the parent is NOT affected. + * @param simple {Boolean} Optional. Set to true to assert that `options` + * (a) only add fields (no config) and (b) no serialization handling is + * required for them. IOW, this is a fast path for frequent child + * creation. See 'tools/timechild.js' for numbers. + */ +Logger.prototype.child = function (options, simple) { + return new (this.constructor)(this, options || {}, simple); +} - if (this._forwardDestroy) { - if (this._readable && this._readable.destroy) this._readable.destroy() - if (this._writable && this._writable.destroy) this._writable.destroy() - } - this.emit('close') -} +/** + * A convenience method to reopen 'file' streams on a logger. This can be + * useful with external log rotation utilities that move and re-open log files + * (e.g. logrotate on Linux, logadm on SmartOS/Illumos). Those utilities + * typically have rotation options to copy-and-truncate the log file, but + * you may not want to use that. An alternative is to do this in your + * application: + * + * var log = bunyan.createLogger(...); + * ... + * process.on('SIGUSR2', function () { + * log.reopenFileStreams(); + * }); + * ... + * + * See . + */ +Logger.prototype.reopenFileStreams = function () { + var self = this; + self.streams.forEach(function (s) { + if (s.type === 'file') { + if (s.stream) { + // Not sure if typically would want this, or more immediate + // `s.stream.destroy()`. + s.stream.end(); + s.stream.destroySoon(); + delete s.stream; + } + s.stream = fs.createWriteStream(s.path, + {flags: 'a', encoding: 'utf8'}); + s.stream.on('error', function (err) { + self.emit('error', err, s); + }); + } + }); +}; -Duplexify.prototype._write = function(data, enc, cb) { - if (this.destroyed) return cb() - if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) - if (data === SIGNAL_FLUSH) return this._finish(cb) - if (!this._writable) return cb() - if (this._writable.write(data) === false) this._ondrain = cb - else cb() +/* BEGIN JSSTYLED */ +/** + * Close this logger. + * + * This closes streams (that it owns, as per 'endOnClose' attributes on + * streams), etc. Typically you **don't** need to bother calling this. +Logger.prototype.close = function () { + if (this._closed) { + return; + } + if (!this._isSimpleChild) { + self.streams.forEach(function (s) { + if (s.endOnClose) { + xxx('closing stream s:', s); + s.stream.end(); + s.endOnClose = false; + } + }); + } + this._closed = true; } + */ +/* END JSSTYLED */ -Duplexify.prototype._finish = function(cb) { - var self = this - this.emit('preend') - onuncork(this, function() { - end(self._forwardEnd && self._writable, function() { - // haxx to not emit prefinish twice - if (self._writableState.prefinished === false) self._writableState.prefinished = true - self.emit('prefinish') - onuncork(self, cb) - }) - }) +/** + * Get/set the level of all streams on this logger. + * + * Get Usage: + * // Returns the current log level (lowest level of all its streams). + * log.level() -> INFO + * + * Set Usage: + * log.level(INFO) // set all streams to level INFO + * log.level('info') // can use 'info' et al aliases + */ +Logger.prototype.level = function level(value) { + if (value === undefined) { + return this._level; + } + var newLevel = resolveLevel(value); + var len = this.streams.length; + for (var i = 0; i < len; i++) { + this.streams[i].level = newLevel; + } + this._level = newLevel; } -Duplexify.prototype.end = function(data, enc, cb) { - if (typeof data === 'function') return this.end(null, null, data) - if (typeof enc === 'function') return this.end(data, null, enc) - this._ended = true - if (data) this.write(data) - if (!this._writableState.ending) this.write(SIGNAL_FLUSH) - return stream.Writable.prototype.end.call(this, cb) + +/** + * Get/set the level of a particular stream on this logger. + * + * Get Usage: + * // Returns an array of the levels of each stream. + * log.levels() -> [TRACE, INFO] + * + * // Returns a level of the identified stream. + * log.levels(0) -> TRACE // level of stream at index 0 + * log.levels('foo') // level of stream with name 'foo' + * + * Set Usage: + * log.levels(0, INFO) // set level of stream 0 to INFO + * log.levels(0, 'info') // can use 'info' et al aliases + * log.levels('foo', WARN) // set stream named 'foo' to WARN + * + * Stream names: When streams are defined, they can optionally be given + * a name. For example, + * log = new Logger({ + * streams: [ + * { + * name: 'foo', + * path: '/var/log/my-service/foo.log' + * level: 'trace' + * }, + * ... + * + * @param name {String|Number} The stream index or name. + * @param value {Number|String} The level value (INFO) or alias ('info'). + * If not given, this is a 'get' operation. + * @throws {Error} If there is no stream with the given name. + */ +Logger.prototype.levels = function levels(name, value) { + if (name === undefined) { + assert.equal(value, undefined); + return this.streams.map( + function (s) { return s.level }); + } + var stream; + if (typeof (name) === 'number') { + stream = this.streams[name]; + if (stream === undefined) { + throw new Error('invalid stream index: ' + name); + } + } else { + var len = this.streams.length; + for (var i = 0; i < len; 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 (value === undefined) { + return stream.level; + } else { + var newLevel = resolveLevel(value); + stream.level = newLevel; + if (newLevel < this._level) { + this._level = newLevel; + } + } } -module.exports = Duplexify -}).call(this,require('_process'),require("buffer").Buffer) -},{"_process":206,"buffer":156,"end-of-stream":29,"inherits":35,"readable-stream":81,"stream-shift":84}],29:[function(require,module,exports){ -var once = require('once'); +/** + * Apply registered serializers to the appropriate keys in the given fields. + * + * Pre-condition: This is only called if there is at least one serializer. + * + * @param fields (Object) The log record fields. + * @param excludeFields (Object) Optional mapping of keys to `true` for + * keys to NOT apply a serializer. + */ +Logger.prototype._applySerializers = function (fields, excludeFields) { + var self = this; -var noop = function() {}; + xxx('_applySerializers: excludeFields', excludeFields); -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; + // Check each serializer against these (presuming number of serializers + // is typically less than number of fields). + Object.keys(this.serializers).forEach(function (name) { + if (fields[name] === undefined || + (excludeFields && excludeFields[name])) + { + return; + } + xxx('_applySerializers; apply to "%s" key', name) + try { + fields[name] = self.serializers[name](fields[name]); + } catch (err) { + _warn(format('bunyan: ERROR: Exception thrown from the "%s" ' + + 'Bunyan serializer. This should never happen. This is a bug ' + + 'in that serializer function.\n%s', + name, err.stack || err)); + fields[name] = format('(Error in Bunyan log "%s" serializer ' + + 'broke field. See stderr for details.)', name); + } + }); +} -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); +/** + * Emit a log record. + * + * @param rec {log record} + * @param noemit {Boolean} Optional. Set to true to skip emission + * and just return the JSON string. + */ +Logger.prototype._emit = function (rec, noemit) { + var i; - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); + // Lazily determine if this Logger has non-'raw' streams. If there are + // any, then we need to stringify the log record. + if (this.haveNonRawStreams === undefined) { + this.haveNonRawStreams = false; + for (i = 0; i < this.streams.length; i++) { + if (!this.streams[i].raw) { + this.haveNonRawStreams = true; + break; + } + } + } - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; + // Stringify the object (creates a warning str on error). + var str; + if (noemit || this.haveNonRawStreams) { + str = fastAndSafeJsonStringify(rec) + '\n'; + } - var onfinish = function() { - writable = false; - if (!readable) callback(); - }; + if (noemit) + return str; - var onend = function() { - readable = false; - if (!writable) callback(); - }; + var level = rec.level; + for (i = 0; i < this.streams.length; i++) { + var s = this.streams[i]; + if (s.level <= level) { + xxx('writing log rec "%s" to "%s" stream (%d <= %d): %j', + rec.msg, s.type, s.level, level, rec); + s.stream.write(s.raw ? rec : str); + } + }; - var onclose = function() { - if (readable && !(rs && rs.ended)) return callback(new Error('premature close')); - if (writable && !(ws && ws.ended)) return callback(new Error('premature close')); - }; + return str; +} - var onrequest = function() { - stream.req.on('finish', onfinish); - }; - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } +/** + * Build a record object suitable for emitting from the arguments + * provided to the a log emitter. + */ +function mkRecord(log, minLevel, args) { + var excludeFields, fields, msgArgs; + if (args[0] instanceof Error) { + // `log.(err, ...)` + fields = { + // Use this Logger's err serializer, if defined. + err: (log.serializers && log.serializers.err + ? log.serializers.err(args[0]) + : Logger.stdSerializers.err(args[0])) + }; + excludeFields = {err: true}; + if (args.length === 1) { + msgArgs = [fields.err.message]; + } else { + msgArgs = args.slice(1); + } + } else if (typeof (args[0]) !== 'object' || Array.isArray(args[0])) { + // `log.(msg, ...)` + fields = null; + msgArgs = args.slice(); + } else if (Buffer.isBuffer(args[0])) { // `log.(buf, ...)` + // Almost certainly an error, show `inspect(buf)`. See bunyan + // issue #35. + fields = null; + msgArgs = args.slice(); + msgArgs[0] = util.inspect(msgArgs[0]); + } else { // `log.(fields, msg, ...)` + fields = args[0]; + if (fields && args.length === 1 && fields.err && + fields.err instanceof Error) + { + msgArgs = [fields.err.message]; + } else { + msgArgs = args.slice(1); + } + } - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', callback); - stream.on('close', onclose); + // Build up the record object. + var rec = objCopy(log.fields); + var level = rec.level = minLevel; + var recFields = (fields ? objCopy(fields) : null); + if (recFields) { + if (log.serializers) { + log._applySerializers(recFields, excludeFields); + } + Object.keys(recFields).forEach(function (k) { + rec[k] = recFields[k]; + }); + } + rec.msg = format.apply(log, msgArgs); + if (!rec.time) { + rec.time = (new Date()); + } + // Get call source info + if (log.src && !rec.src) { + rec.src = getCaller3Info() + } + rec.v = LOG_VERSION; - return function() { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (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); - }; + return rec; }; -module.exports = eos; -},{"once":30}],30:[function(require,module,exports){ -var wrappy = require('wrappy') -module.exports = wrappy(once) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) -}) -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f +/** + * Build an array that dtrace-provider can use to fire a USDT probe. If we've + * already built the appropriate string, we use it. Otherwise, build the + * record object and stringify it. + */ +function mkProbeArgs(str, log, minLevel, msgArgs) { + return [ str || log._emit(mkRecord(log, minLevel, msgArgs), true) ]; } -},{"wrappy":91}],31:[function(require,module,exports){ -var prr = require('prr') -function init (type, message, cause) { - prr(this, { - type : type - , name : type - // can be passed just a 'cause' - , cause : typeof message != 'string' ? message : cause - , message : !!message && typeof message != 'string' ? message.message : message +/** + * Build a log emitter function for level minLevel. I.e. this is the + * creator of `log.info`, `log.error`, etc. + */ +function mkLogEmitter(minLevel) { + return function () { + var log = this; + var str = null; + var rec = null; - }, 'ewr') -} + if (!this._emit) { + /* + * Show this invalid Bunyan usage warning *once*. + * + * See for + * an example of how this can happen. + */ + var dedupKey = 'unbound'; + if (!_haveWarned[dedupKey]) { + var caller = getCaller3Info(); + _warn(format('bunyan usage error: %s:%s: attempt to log ' + + 'with an unbound log method: `this` is: %s', + caller.file, caller.line, util.inspect(this)), + dedupKey); + } + return; + } else if (arguments.length === 0) { // `log.()` + return (this._level <= minLevel); + } -// generic prototype, not intended to be actually used - helpful for `instanceof` -function CustomError (message, cause) { - Error.call(this) - if (Error.captureStackTrace) - Error.captureStackTrace(this, arguments.callee) - init.call(this, 'CustomError', message, cause) + var msgArgs = new Array(arguments.length); + for (var i = 0; i < msgArgs.length; ++i) { + msgArgs[i] = arguments[i]; + } + + if (this._level <= minLevel) { + rec = mkRecord(log, minLevel, msgArgs); + str = this._emit(rec); + } + + if (probes) { + probes[minLevel].fire(mkProbeArgs, str, log, minLevel, msgArgs); + } + } } -CustomError.prototype = new Error() -function createError (errno, type, proto) { - var err = function (message, cause) { - init.call(this, type, message, cause) - //TODO: the specificity here is stupid, errno should be available everywhere - if (type == 'FilesystemError') { - 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 + ']' : '') +/** + * The functions below log a record at a specific level. + * + * Usages: + * log.() -> boolean is-trace-enabled + * log.( err, [ msg, ...]) + * log.( msg, ...) + * log.( fields, msg, ...) + * + * where is the lowercase version of the log level. E.g.: + * + * log.info() + * + * @params fields {Object} Optional set of additional fields to log. + * @params msg {String} Log message. This can be followed by additional + * arguments that are handled like + * [util.format](http://nodejs.org/docs/latest/api/all.html#util.format). + */ +Logger.prototype.trace = mkLogEmitter(TRACE); +Logger.prototype.debug = mkLogEmitter(DEBUG); +Logger.prototype.info = mkLogEmitter(INFO); +Logger.prototype.warn = mkLogEmitter(WARN); +Logger.prototype.error = mkLogEmitter(ERROR); +Logger.prototype.fatal = mkLogEmitter(FATAL); + + + +//---- Standard serializers +// A serializer is a function that serializes a JavaScript object to a +// JSON representation for logging. There is a standard set of presumed +// interesting objects in node.js-land. + +Logger.stdSerializers = {}; + +// Serialize an HTTP request. +Logger.stdSerializers.req = function (req) { + if (!req || !req.connection) + return req; + return { + method: req.method, + url: req.url, + headers: req.headers, + remoteAddress: req.connection.remoteAddress, + remotePort: req.connection.remotePort + }; + // Trailers: Skipping for speed. If you need trailers in your app, then + // make a custom serializer. + //if (Object.keys(trailers).length > 0) { + // obj.trailers = req.trailers; + //} +}; + +// Serialize an HTTP response. +Logger.stdSerializers.res = function (res) { + if (!res || !res.statusCode) + return res; + return { + statusCode: res.statusCode, + header: res._header } - Error.call(this) - if (Error.captureStackTrace) - Error.captureStackTrace(this, arguments.callee) - } - err.prototype = !!proto ? new proto() : new CustomError() - return err +}; + + +/* + * This function dumps long stack traces for exceptions having a cause() + * method. The error classes from + * [verror](https://github.com/davepacheco/node-verror) and + * [restify v2.0](https://github.com/mcavage/node-restify) are examples. + * + * Based on `dumpException` in + * https://github.com/davepacheco/node-extsprintf/blob/master/lib/extsprintf.js + */ +function getFullErrorStack(ex) +{ + var ret = ex.stack || ex.toString(); + if (ex.cause && typeof (ex.cause) === 'function') { + var cex = ex.cause(); + if (cex) { + ret += '\nCaused by: ' + getFullErrorStack(cex); + } + } + return (ret); } -module.exports = function (errno) { - var ce = function (type, proto) { - return createError(errno, type, proto) - } - return { - CustomError : CustomError - , FilesystemError : ce('FilesystemError') - , createError : ce - } -} - -},{"prr":33}],32:[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":31}],33:[function(require,module,exports){ -/*! - * prr - * (c) 2013 Rod Vagg - * https://github.com/rvagg/prr - * License: MIT - */ - -(function (name, context, definition) { - if (typeof module != 'undefined' && module.exports) - module.exports = definition() - else - context[name] = definition() -})('prr', this, function() { - - var setProperty = typeof Object.defineProperty == 'function' - ? function (obj, key, options) { - Object.defineProperty(obj, key, options) - return obj - } - : function (obj, key, options) { // < es5 - obj[key] = options.value - return obj - } - - , makeOptions = function (value, options) { - var oo = typeof options == 'object' - , os = !oo && typeof options == 'string' - , op = function (p) { - return oo - ? !!options[p] - : os - ? options.indexOf(p[0]) > -1 - : false - } - - return { - enumerable : op('enumerable') - , configurable : op('configurable') - , writable : op('writable') - , value : value - } - } - - , prr = function (obj, key, value, options) { - var k - - options = makeOptions(value, options) - - if (typeof key == 'object') { - for (k in key) { - if (Object.hasOwnProperty.call(key, k)) { - options.value = key[k] - setProperty(obj, k, options) - } - } - return obj - } - - return setProperty(obj, key, options) - } - - return prr -}) -},{}],34:[function(require,module,exports){ -/*global window:false, self:false, define:false, module:false */ - -/** - * @license IDBWrapper - A cross-browser wrapper for IndexedDB - * Version 1.7.1 - * Copyright (c) 2011 - 2016 Jens Arps - * http://jensarps.de/ - * - * Licensed under the MIT (X11) license - */ - -(function (name, definition, global) { - - 'use strict'; - - if (typeof define === 'function') { - define(definition); - } else if (typeof module !== 'undefined' && module.exports) { - module.exports = definition(); - } else { - global[name] = definition(); - } -})('IDBStore', function () { - - 'use strict'; - - var defaultErrorHandler = function (error) { - throw error; - }; - var defaultSuccessHandler = function () { - }; - - var defaults = { - storeName: 'Store', - storePrefix: 'IDBWrapper-', - dbVersion: 1, - keyPath: 'id', - autoIncrement: true, - onStoreReady: function () { - }, - onError: defaultErrorHandler, - indexes: [], - implementationPreference: [ - 'indexedDB', - 'webkitIndexedDB', - 'mozIndexedDB', - 'shimIndexedDB' - ] - }; - - /** - * - * The IDBStore constructor - * - * @constructor - * @name IDBStore - * @version 1.7.1 - * - * @param {Object} [kwArgs] An options object used to configure the store and - * set callbacks - * @param {String} [kwArgs.storeName='Store'] The name of the store - * @param {String} [kwArgs.storePrefix='IDBWrapper-'] A prefix that is - * internally used to construct the name of the database, which will be - * kwArgs.storePrefix + kwArgs.storeName - * @param {Number} [kwArgs.dbVersion=1] The version of the store - * @param {String} [kwArgs.keyPath='id'] The key path to use. If you want to - * setup IDBWrapper to work with out-of-line keys, you need to set this to - * `null` - * @param {Boolean} [kwArgs.autoIncrement=true] If set to true, IDBStore will - * automatically make sure a unique keyPath value is present on each object - * that is stored. - * @param {Function} [kwArgs.onStoreReady] A callback to be called when the - * store is ready to be used. - * @param {Function} [kwArgs.onError=throw] A callback to be called when an - * error occurred during instantiation of the store. - * @param {Array} [kwArgs.indexes=[]] An array of indexData objects - * defining the indexes to use with the store. For every index to be used - * one indexData object needs to be passed in the array. - * An indexData object is defined as follows: - * @param {Object} [kwArgs.indexes.indexData] An object defining the index to - * use - * @param {String} kwArgs.indexes.indexData.name The name of the index - * @param {String} [kwArgs.indexes.indexData.keyPath] The key path of the index - * @param {Boolean} [kwArgs.indexes.indexData.unique] Whether the index is unique - * @param {Boolean} [kwArgs.indexes.indexData.multiEntry] Whether the index is multi entry - * @param {Array} [kwArgs.implementationPreference=['indexedDB','webkitIndexedDB','mozIndexedDB','shimIndexedDB']] An array of strings naming implementations to be used, in order or preference - * @param {Function} [onStoreReady] A callback to be called when the store - * is ready to be used. - * @example - // create a store for customers with an additional index over the - // `lastname` property. - var myCustomerStore = new IDBStore({ - dbVersion: 1, - storeName: 'customer-index', - keyPath: 'customerid', - autoIncrement: true, - onStoreReady: populateTable, - indexes: [ - { name: 'lastname', keyPath: 'lastname', unique: false, multiEntry: false } - ] - }); - * @example - // create a generic store - var myCustomerStore = new IDBStore({ - storeName: 'my-data-store', - onStoreReady: function(){ - // start working with the store. - } - }); - */ - var IDBStore = function (kwArgs, onStoreReady) { - - if (typeof onStoreReady == 'undefined' && typeof kwArgs == 'function') { - onStoreReady = kwArgs; - } - if (Object.prototype.toString.call(kwArgs) != '[object Object]') { - kwArgs = {}; - } - - for (var key in defaults) { - this[key] = typeof kwArgs[key] != 'undefined' ? kwArgs[key] : defaults[key]; - } - - this.dbName = this.storePrefix + this.storeName; - this.dbVersion = parseInt(this.dbVersion, 10) || 1; - - onStoreReady && (this.onStoreReady = onStoreReady); - - var env = typeof window == 'object' ? window : self; - var 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(); - }; - - /** @lends IDBStore.prototype */ - var proto = { - - /** - * A pointer to the IDBStore ctor - * - * @private - * @type {Function} - * @constructs - */ - constructor: IDBStore, - - /** - * The version of IDBStore - * - * @type {String} - */ - version: '1.7.1', - - /** - * A reference to the IndexedDB object - * - * @type {IDBDatabase} - */ - db: null, - - /** - * The full name of the IndexedDB used by IDBStore, composed of - * this.storePrefix + this.storeName - * - * @type {String} - */ - dbName: null, - - /** - * The version of the IndexedDB used by IDBStore - * - * @type {Number} - */ - dbVersion: null, - - /** - * A reference to the objectStore used by IDBStore - * - * @type {IDBObjectStore} - */ - store: null, - - /** - * The store name - * - * @type {String} - */ - storeName: null, - - /** - * The prefix to prepend to the store name - * - * @type {String} - */ - storePrefix: null, - - /** - * The key path - * - * @type {String} - */ - keyPath: null, - - /** - * Whether IDBStore uses autoIncrement - * - * @type {Boolean} - */ - autoIncrement: null, - - /** - * The indexes used by IDBStore - * - * @type {Array} - */ - indexes: null, - - /** - * The implemantations to try to use, in order of preference - * - * @type {Array} - */ - implementationPreference: null, - - /** - * The actual implementation being used - * - * @type {String} - */ - implementation: '', - - /** - * The callback to be called when the store is ready to be used - * - * @type {Function} - */ - onStoreReady: null, - - /** - * The callback to be called if an error occurred during instantiation - * of the store - * - * @type {Function} - */ - onError: null, - - /** - * The internal insertID counter - * - * @type {Number} - * @private - */ - _insertIdCount: 0, - - /** - * Opens an IndexedDB; called by the constructor. - * - * Will check if versions match and compare provided index configuration - * with existing ones, and update indexes if necessary. - * - * Will call this.onStoreReady() if everything went well and the store - * is ready to use, and this.onError() is something went wrong. - * - * @private - * - */ - openDB: function () { - - var openRequest = this.idb.open(this.dbName, this.dbVersion); - var preventSuccessCallback = false; - - 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; - if ('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) { - return; - } - - if (this.db) { - this.onStoreReady(); - return; - } - - this.db = event.target.result; - - if (typeof this.db.version == 'string') { - this.onError(new Error('The IndexedDB implementation in this browser is outdated. Please upgrade your browser.')); - return; - } - - if (!this.db.objectStoreNames.contains(this.storeName)) { - // We should never ever get here. - // Lets notify the user anyway. - this.onError(new Error('Object store couldn\'t be created.')); - return; - } - - var emptyTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); - this.store = emptyTransaction.objectStore(this.storeName); - - // check indexes - var existingIndexes = Array.prototype.slice.call(this.getIndexList()); - this.indexes.forEach(function (indexData) { - var indexName = indexData.name; - - if (!indexName) { - preventSuccessCallback = true; - this.onError(new Error('Cannot create index: No index name given.')); - return; - } - - this.normalizeIndexData(indexData); - - if (this.hasIndex(indexName)) { - // check if it complies - var actualIndex = this.store.index(indexName); - var complies = this.indexComplies(actualIndex, indexData); - if (!complies) { - preventSuccessCallback = true; - 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 = true; - this.onError(new Error('Cannot create new index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.')); - } - - }, this); - - if (existingIndexes.length) { - preventSuccessCallback = true; - 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 (/* IDBVersionChangeEvent */ event) { - - this.db = event.target.result; - - if (this.db.objectStoreNames.contains(this.storeName)) { - this.store = event.target.transaction.objectStore(this.storeName); - } else { - var optionalParameters = {autoIncrement: this.autoIncrement}; - if (this.keyPath !== null) { - 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 = true; - this.onError(new Error('Cannot create index: No index name given.')); - } - - this.normalizeIndexData(indexData); - - if (this.hasIndex(indexName)) { - // check if it complies - var actualIndex = this.store.index(indexName); - var complies = this.indexComplies(actualIndex, indexData); - if (!complies) { - // index differs, need to delete and re-create - 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); - - if (existingIndexes.length) { - existingIndexes.forEach(function (_indexName) { - this.store.deleteIndex(_indexName); - }, this); - } - - }.bind(this); - }, - - /** - * Deletes the database used for this store if the IDB implementations - * provides that functionality. - * - * @param {Function} [onSuccess] A callback that is called if deletion - * was successful. - * @param {Function} [onError] A callback that is called if deletion - * failed. - */ - 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!')); - } - }, - - /********************* - * data manipulation * - *********************/ - - /** - * Puts an object into the store. If an entry with the given id exists, - * it will be overwritten. This method has a different signature for inline - * keys and out-of-line keys; please see the examples below. - * - * @param {*} [key] The key to store. This is only needed if IDBWrapper - * is set to use out-of-line keys. For inline keys - the default scenario - - * this can be omitted. - * @param {Object} value The data object to store. - * @param {Function} [onSuccess] A callback that is called if insertion - * was successful. - * @param {Function} [onError] A callback that is called if insertion - * failed. - * @returns {IDBTransaction} The transaction used for this operation. - * @example - // Storing an object, using inline keys (the default scenario): - var myCustomer = { - customerid: 2346223, - lastname: 'Doe', - firstname: 'John' - }; - myCustomerStore.put(myCustomer, mySuccessHandler, myErrorHandler); - // Note that passing success- and error-handlers is optional. - * @example - // Storing an object, using out-of-line keys: - var myCustomer = { - lastname: 'Doe', - firstname: 'John' - }; - myCustomerStore.put(2346223, myCustomer, mySuccessHandler, myErrorHandler); - // Note that passing success- and error-handlers is optional. - */ - put: function (key, value, onSuccess, onError) { - if (this.keyPath !== null) { - onError = onSuccess; - onSuccess = value; - value = key; - } - onError || (onError = defaultErrorHandler); - onSuccess || (onSuccess = defaultSuccessHandler); - - var hasSuccess = false, - result = null, - putRequest; - - var putTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE); - putTransaction.oncomplete = function () { - var callback = hasSuccess ? onSuccess : onError; - callback(result); - }; - putTransaction.onabort = onError; - putTransaction.onerror = onError; - - if (this.keyPath !== null) { // in-line keys - this._addIdPropertyIfNeeded(value); - putRequest = putTransaction.objectStore(this.storeName).put(value); - } else { // out-of-line keys - putRequest = putTransaction.objectStore(this.storeName).put(value, key); - } - putRequest.onsuccess = function (event) { - hasSuccess = true; - result = event.target.result; - }; - putRequest.onerror = onError; - - return putTransaction; - }, - - /** - * Retrieves an object from the store. If no entry exists with the given id, - * the success handler will be called with null as first and only argument. - * - * @param {*} key The id of the object to fetch. - * @param {Function} [onSuccess] A callback that is called if fetching - * was successful. Will receive the object as only argument. - * @param {Function} [onError] A callback that will be called if an error - * occurred during the operation. - * @returns {IDBTransaction} The transaction used for this operation. - */ - get: function (key, onSuccess, onError) { - onError || (onError = defaultErrorHandler); - onSuccess || (onSuccess = defaultSuccessHandler); - - var hasSuccess = false, - result = null; - - var 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); - getRequest.onsuccess = function (event) { - hasSuccess = true; - result = event.target.result; - }; - getRequest.onerror = onError; - - return getTransaction; - }, - - /** - * Removes an object from the store. - * - * @param {*} key The id of the object to remove. - * @param {Function} [onSuccess] A callback that is called if the removal - * was successful. - * @param {Function} [onError] A callback that will be called if an error - * occurred during the operation. - * @returns {IDBTransaction} The transaction used for this operation. - */ - remove: function (key, onSuccess, onError) { - onError || (onError = defaultErrorHandler); - onSuccess || (onSuccess = defaultSuccessHandler); - - var hasSuccess = false, - result = null; - - var 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); - deleteRequest.onsuccess = function (event) { - hasSuccess = true; - result = event.target.result; - }; - deleteRequest.onerror = onError; - - return removeTransaction; - }, - - /** - * Runs a batch of put and/or remove operations on the store. - * - * @param {Array} dataArray An array of objects containing the operation to run - * and the data object (for put operations). - * @param {Function} [onSuccess] A callback that is called if all operations - * were successful. - * @param {Function} [onError] A callback that is called if an error - * occurred during one of the operations. - * @returns {IDBTransaction} The transaction used for this operation. - */ - batch: function (dataArray, onSuccess, onError) { - onError || (onError = defaultErrorHandler); - onSuccess || (onSuccess = defaultSuccessHandler); - - if (Object.prototype.toString.call(dataArray) != '[object Array]') { - onError(new Error('dataArray argument must be of type Array.')); - } else if (dataArray.length === 0) { - return onSuccess(true); - } - - var count = dataArray.length; - var called = false; - var hasSuccess = false; - - var 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--; - if (count === 0 && !called) { - called = true; - hasSuccess = true; - } - }; - - dataArray.forEach(function (operation) { - var type = operation.type; - var key = operation.key; - var value = operation.value; - - var onItemError = function (err) { - batchTransaction.abort(); - if (!called) { - called = true; - onError(err, type, key); - } - }; - - if (type == 'remove') { - var deleteRequest = batchTransaction.objectStore(this.storeName)['delete'](key); - deleteRequest.onsuccess = onItemSuccess; - deleteRequest.onerror = onItemError; - } else if (type == 'put') { - var putRequest; - if (this.keyPath !== null) { // in-line keys - this._addIdPropertyIfNeeded(value); - putRequest = batchTransaction.objectStore(this.storeName).put(value); - } else { // out-of-line keys - putRequest = batchTransaction.objectStore(this.storeName).put(value, key); - } - putRequest.onsuccess = onItemSuccess; - putRequest.onerror = onItemError; - } - }, this); - - return batchTransaction; - }, - - /** - * Takes an array of objects and stores them in a single transaction. - * - * @param {Array} dataArray An array of objects to store - * @param {Function} [onSuccess] A callback that is called if all operations - * were successful. - * @param {Function} [onError] A callback that is called if an error - * occurred during one of the operations. - * @returns {IDBTransaction} The transaction used for this operation. - */ - putBatch: function (dataArray, onSuccess, onError) { - var batchData = dataArray.map(function (item) { - return {type: 'put', value: item}; - }); - - return this.batch(batchData, onSuccess, onError); - }, - - /** - * Like putBatch, takes an array of objects and stores them in a single - * transaction, but allows processing of the result values. Returns the - * processed records containing the key for newly created records to the - * onSuccess calllback instead of only returning true or false for success. - * In addition, added the option for the caller to specify a key field that - * should be set to the newly created key. - * - * @param {Array} dataArray An array of objects to store - * @param {Object} [options] An object containing optional options - * @param {String} [options.keyField=this.keyPath] Specifies a field in the record to update - * with the auto-incrementing key. Defaults to the store's keyPath. - * @param {Function} [onSuccess] A callback that is called if all operations - * were successful. - * @param {Function} [onError] A callback that is called if an error - * occurred during one of the operations. - * @returns {IDBTransaction} The transaction used for this operation. - * - */ - upsertBatch: function (dataArray, options, onSuccess, onError) { - // handle `dataArray, onSuccess, onError` signature - if (typeof options == 'function') { - onSuccess = options; - onError = onSuccess; - options = {}; - } - - onError || (onError = defaultErrorHandler); - onSuccess || (onSuccess = defaultSuccessHandler); - options || (options = {}); - - if (Object.prototype.toString.call(dataArray) != '[object Array]') { - onError(new Error('dataArray argument must be of type Array.')); - } - - var keyField = options.keyField || this.keyPath; - var count = dataArray.length; - var called = false; - var hasSuccess = false; - var index = 0; // assume success callbacks are executed in order - - var batchTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE); - batchTransaction.oncomplete = function () { - if (hasSuccess) { - onSuccess(dataArray); - } else { - onError(false); - } - }; - batchTransaction.onabort = onError; - batchTransaction.onerror = onError; - - var onItemSuccess = function (event) { - var record = dataArray[index++]; - record[keyField] = event.target.result; - - count--; - if (count === 0 && !called) { - called = true; - hasSuccess = true; - } - }; - - dataArray.forEach(function (record) { - var key = record.key; - - var onItemError = function (err) { - batchTransaction.abort(); - if (!called) { - called = true; - onError(err); - } - }; - - var putRequest; - if (this.keyPath !== null) { // in-line keys - this._addIdPropertyIfNeeded(record); - putRequest = batchTransaction.objectStore(this.storeName).put(record); - } else { // out-of-line keys - putRequest = batchTransaction.objectStore(this.storeName).put(record, key); - } - putRequest.onsuccess = onItemSuccess; - putRequest.onerror = onItemError; - }, this); - - return batchTransaction; - }, - - /** - * Takes an array of keys and removes matching objects in a single - * transaction. - * - * @param {Array} keyArray An array of keys to remove - * @param {Function} [onSuccess] A callback that is called if all operations - * were successful. - * @param {Function} [onError] A callback that is called if an error - * occurred during one of the operations. - * @returns {IDBTransaction} The transaction used for this operation. - */ - removeBatch: function (keyArray, onSuccess, onError) { - var batchData = keyArray.map(function (key) { - return {type: 'remove', key: key}; - }); - - return this.batch(batchData, onSuccess, onError); - }, - - /** - * Takes an array of keys and fetches matching objects - * - * @param {Array} keyArray An array of keys identifying the objects to fetch - * @param {Function} [onSuccess] A callback that is called if all operations - * were successful. - * @param {Function} [onError] A callback that is called if an error - * occurred during one of the operations. - * @param {String} [arrayType='sparse'] The type of array to pass to the - * success handler. May be one of 'sparse', 'dense' or 'skip'. Defaults to - * 'sparse'. This parameter specifies how to handle the situation if a get - * operation did not throw an error, but there was no matching object in - * the database. In most cases, 'sparse' provides the most desired - * behavior. See the examples for details. - * @returns {IDBTransaction} The transaction used for this operation. - * @example - // given that there are two objects in the database with the keypath - // values 1 and 2, and the call looks like this: - myStore.getBatch([1, 5, 2], onError, function (data) { … }, arrayType); - - // this is what the `data` array will be like: - - // arrayType == 'sparse': - // data is a sparse array containing two entries and having a length of 3: - [Object, 2: Object] - 0: Object - 2: Object - length: 3 - // calling forEach on data will result in the callback being called two - // times, with the index parameter matching the index of the key in the - // keyArray. - - // arrayType == 'dense': - // data is a dense array containing three entries and having a length of 3, - // where data[1] is of type undefined: - [Object, undefined, Object] - 0: Object - 1: undefined - 2: Object - length: 3 - // calling forEach on data will result in the callback being called three - // times, with the index parameter matching the index of the key in the - // keyArray, but the second call will have undefined as first argument. - - // arrayType == 'skip': - // data is a dense array containing two entries and having a length of 2: - [Object, Object] - 0: Object - 1: Object - length: 2 - // calling forEach on data will result in the callback being called two - // times, with the index parameter not matching the index of the key in the - // keyArray. - */ - getBatch: function (keyArray, onSuccess, onError, arrayType) { - onError || (onError = defaultErrorHandler); - onSuccess || (onSuccess = defaultSuccessHandler); - arrayType || (arrayType = 'sparse'); - - if (Object.prototype.toString.call(keyArray) != '[object Array]') { - onError(new Error('keyArray argument must be of type Array.')); - } else if (keyArray.length === 0) { - return onSuccess([]); - } - - var data = []; - var count = keyArray.length; - var called = false; - var hasSuccess = false; - var result = null; - - var 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) { - if (event.target.result || arrayType == 'dense') { - data.push(event.target.result); - } else if (arrayType == 'sparse') { - data.length++; - } - count--; - if (count === 0) { - called = true; - hasSuccess = true; - result = data; - } - }; - - keyArray.forEach(function (key) { - - var onItemError = function (err) { - called = true; - result = err; - onError(err); - batchTransaction.abort(); - }; - - var getRequest = batchTransaction.objectStore(this.storeName).get(key); - getRequest.onsuccess = onItemSuccess; - getRequest.onerror = onItemError; - - }, this); - - return batchTransaction; - }, - - /** - * Fetches all entries in the store. - * - * @param {Function} [onSuccess] A callback that is called if the operation - * was successful. Will receive an array of objects. - * @param {Function} [onError] A callback that will be called if an error - * occurred during the operation. - * @returns {IDBTransaction} The transaction used for this operation. - */ - getAll: function (onSuccess, onError) { - onError || (onError = defaultErrorHandler); - onSuccess || (onSuccess = defaultSuccessHandler); - var getAllTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); - var store = getAllTransaction.objectStore(this.storeName); - if (store.getAll) { - this._getAllNative(getAllTransaction, store, onSuccess, onError); - } else { - this._getAllCursor(getAllTransaction, store, onSuccess, onError); - } - - return getAllTransaction; - }, - - /** - * Implements getAll for IDB implementations that have a non-standard - * getAll() method. - * - * @param {IDBTransaction} getAllTransaction An open READ transaction. - * @param {IDBObjectStore} store A reference to the store. - * @param {Function} onSuccess A callback that will be called if the - * operation was successful. - * @param {Function} onError A callback that will be called if an - * error occurred during the operation. - * @private - */ - _getAllNative: function (getAllTransaction, store, onSuccess, onError) { - var hasSuccess = false, - 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 = true; - result = event.target.result; - }; - getAllRequest.onerror = onError; - }, - - /** - * Implements getAll for IDB implementations that do not have a getAll() - * method. - * - * @param {IDBTransaction} getAllTransaction An open READ transaction. - * @param {IDBObjectStore} store A reference to the store. - * @param {Function} onSuccess A callback that will be called if the - * operation was successful. - * @param {Function} onError A callback that will be called if an - * error occurred during the operation. - * @private - */ - _getAllCursor: function (getAllTransaction, store, onSuccess, onError) { - var all = [], - hasSuccess = false, - 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; - if (cursor) { - all.push(cursor.value); - cursor['continue'](); - } - else { - hasSuccess = true; - result = all; - } - }; - cursorRequest.onError = onError; - }, - - /** - * Clears the store, i.e. deletes all entries in the store. - * - * @param {Function} [onSuccess] A callback that will be called if the - * operation was successful. - * @param {Function} [onError] A callback that will be called if an - * error occurred during the operation. - * @returns {IDBTransaction} The transaction used for this operation. - */ - clear: function (onSuccess, onError) { - onError || (onError = defaultErrorHandler); - onSuccess || (onSuccess = defaultSuccessHandler); - - var hasSuccess = false, - result = null; - - var 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(); - clearRequest.onsuccess = function (event) { - hasSuccess = true; - result = event.target.result; - }; - clearRequest.onerror = onError; - - return clearTransaction; - }, - - /** - * Checks if an id property needs to present on a object and adds one if - * necessary. - * - * @param {Object} dataObj The data object that is about to be stored - * @private - */ - _addIdPropertyIfNeeded: function (dataObj) { - if (typeof dataObj[this.keyPath] == 'undefined') { - dataObj[this.keyPath] = this._insertIdCount++ + Date.now(); - } - }, - - /************ - * indexing * - ************/ - - /** - * Returns a DOMStringList of index names of the store. - * - * @return {DOMStringList} The list of index names - */ - getIndexList: function () { - return this.store.indexNames; - }, - - /** - * Checks if an index with the given name exists in the store. - * - * @param {String} indexName The name of the index to look for - * @return {Boolean} Whether the store contains an index with the given name - */ - hasIndex: function (indexName) { - return this.store.indexNames.contains(indexName); - }, - - /** - * Normalizes an object containing index data and assures that all - * properties are set. - * - * @param {Object} indexData The index data object to normalize - * @param {String} indexData.name The name of the index - * @param {String} [indexData.keyPath] The key path of the index - * @param {Boolean} [indexData.unique] Whether the index is unique - * @param {Boolean} [indexData.multiEntry] Whether the index is multi entry - */ - normalizeIndexData: function (indexData) { - indexData.keyPath = indexData.keyPath || indexData.name; - indexData.unique = !!indexData.unique; - indexData.multiEntry = !!indexData.multiEntry; - }, - - /** - * Checks if an actual index complies with an expected index. - * - * @param {IDBIndex} actual The actual index found in the store - * @param {Object} expected An Object describing an expected index - * @return {Boolean} Whether both index definitions are identical - */ - indexComplies: function (actual, expected) { - var complies = ['keyPath', 'unique', 'multiEntry'].every(function (key) { - // IE10 returns undefined for no multiEntry - if (key == 'multiEntry' && actual[key] === undefined && expected[key] === false) { - return true; - } - // Compound keys - if (key == 'keyPath' && Object.prototype.toString.call(expected[key]) == '[object Array]') { - var exp = expected.keyPath; - var act = actual.keyPath; - - // IE10 can't handle keyPath sequences and stores them as a string. - // The index will be unusable there, but let's still return true if - // the keyPath sequence matches. - if (typeof act == 'string') { - return exp.toString() == act; - } - - // Chrome/Opera stores keyPath squences as DOMStringList, Firefox - // as Array - if (!(typeof act.contains == 'function' || typeof act.indexOf == 'function')) { - return false; - } - - if (act.length !== exp.length) { - return false; - } - - for (var i = 0, m = exp.length; i < m; i++) { - if (!( (act.contains && act.contains(exp[i])) || act.indexOf(exp[i] !== -1) )) { - return false; - } - } - return true; - } - return expected[key] == actual[key]; - }); - return complies; - }, - - /********** - * cursor * - **********/ - - /** - * Iterates over the store using the given options and calling onItem - * for each entry matching the options. - * - * @param {Function} onItem A callback to be called for each match - * @param {Object} [options] An object defining specific options - * @param {String} [options.index=null] A name of an IDBIndex to operate on - * @param {String} [options.order=ASC] The order in which to provide the - * results, can be 'DESC' or 'ASC' - * @param {Boolean} [options.autoContinue=true] Whether to automatically - * iterate the cursor to the next result - * @param {Boolean} [options.filterDuplicates=false] Whether to exclude - * duplicate matches - * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use - * @param {Boolean} [options.writeAccess=false] Whether grant write access - * to the store in the onItem callback - * @param {Function} [options.onEnd=null] A callback to be called after - * iteration has ended - * @param {Function} [options.onError=throw] A callback to be called - * if an error occurred during the operation. - * @param {Number} [options.limit=Infinity] Limit the number of returned - * results to this number - * @param {Number} [options.offset=0] Skip the provided number of results - * in the resultset - * @param {Boolean} [options.allowItemRejection=false] Allows the onItem - * function to return a Boolean to accept or reject the current item - * @returns {IDBTransaction} The transaction used for this operation. - */ - iterate: function (onItem, options) { - options = mixin({ - index: null, - order: 'ASC', - autoContinue: true, - filterDuplicates: false, - keyRange: null, - writeAccess: false, - onEnd: null, - onError: defaultErrorHandler, - limit: Infinity, - offset: 0, - allowItemRejection: false - }, options || {}); - - var directionType = options.order.toLowerCase() == 'desc' ? 'PREV' : 'NEXT'; - if (options.filterDuplicates) { - directionType += '_NO_DUPLICATE'; - } - - var hasSuccess = false; - var cursorTransaction = this.db.transaction([this.storeName], this.consts[options.writeAccess ? 'READ_WRITE' : 'READ_ONLY']); - var cursorTarget = cursorTransaction.objectStore(this.storeName); - if (options.index) { - cursorTarget = cursorTarget.index(options.index); - } - var recordCount = 0; - - cursorTransaction.oncomplete = function () { - if (!hasSuccess) { - options.onError(null); - return; - } - if (options.onEnd) { - options.onEnd(); - } else { - onItem(null); - } - }; - cursorTransaction.onabort = options.onError; - cursorTransaction.onerror = options.onError; - - var cursorRequest = cursorTarget.openCursor(options.keyRange, this.consts[directionType]); - 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); - if (!options.allowItemRejection || onItemReturn !== false) { - recordCount++; - } - if (options.autoContinue) { - if (recordCount + options.offset < options.limit) { - cursor['continue'](); - } else { - hasSuccess = true; - } - } - } - } else { - hasSuccess = true; - } - }; - - return cursorTransaction; - }, - - /** - * Runs a query against the store and passes an array containing matched - * objects to the success handler. - * - * @param {Function} onSuccess A callback to be called when the operation - * was successful. - * @param {Object} [options] An object defining specific options - * @param {String} [options.index=null] A name of an IDBIndex to operate on - * @param {String} [options.order=ASC] The order in which to provide the - * results, can be 'DESC' or 'ASC' - * @param {Boolean} [options.filterDuplicates=false] Whether to exclude - * duplicate matches - * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use - * @param {Function} [options.onError=throw] A callback to be called - * if an error occurred during the operation. - * @param {Number} [options.limit=Infinity] Limit the number of returned - * results to this number - * @param {Number} [options.offset=0] Skip the provided number of results - * in the resultset - * @param {Function} [options.filter=null] A custom filter function to - * apply to query resuts before returning. Must return `false` to reject - * an item. Can be combined with keyRanges. - * @returns {IDBTransaction} The transaction used for this operation. - */ - query: function (onSuccess, options) { - var result = [], - processedItems = 0; - options = options || {}; - options.autoContinue = true; - options.writeAccess = false; - options.allowItemRejection = !!options.filter; - options.onEnd = function () { - onSuccess(result, processedItems); - }; - return this.iterate(function (item) { - processedItems++; - var accept = options.filter ? options.filter(item) : true; - if (accept !== false) { - result.push(item); - } - return accept; - }, options); - }, - - /** - * - * Runs a query against the store, but only returns the number of matches - * instead of the matches itself. - * - * @param {Function} onSuccess A callback to be called if the opration - * was successful. - * @param {Object} [options] An object defining specific options - * @param {String} [options.index=null] A name of an IDBIndex to operate on - * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use - * @param {Function} [options.onError=throw] A callback to be called if an error - * occurred during the operation. - * @returns {IDBTransaction} The transaction used for this operation. - */ - count: function (onSuccess, options) { - - options = mixin({ - index: null, - keyRange: null - }, options || {}); - - var onError = options.onError || defaultErrorHandler; - - var hasSuccess = false, - result = null; - - var cursorTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); - cursorTransaction.oncomplete = function () { - var callback = hasSuccess ? onSuccess : onError; - callback(result); - }; - cursorTransaction.onabort = onError; - cursorTransaction.onerror = onError; - - var cursorTarget = cursorTransaction.objectStore(this.storeName); - if (options.index) { - cursorTarget = cursorTarget.index(options.index); - } - var countRequest = cursorTarget.count(options.keyRange); - countRequest.onsuccess = function (evt) { - hasSuccess = true; - result = evt.target.result; - }; - countRequest.onError = onError; - - return cursorTransaction; - }, - - /**************/ - /* key ranges */ - /**************/ - - /** - * Creates a key range using specified options. This key range can be - * handed over to the count() and iterate() methods. - * - * Note: You must provide at least one or both of "lower" or "upper" value. - * - * @param {Object} options The options for the key range to create - * @param {*} [options.lower] The lower bound - * @param {Boolean} [options.excludeLower] Whether to exclude the lower - * bound passed in options.lower from the key range - * @param {*} [options.upper] The upper bound - * @param {Boolean} [options.excludeUpper] Whether to exclude the upper - * bound passed in options.upper from the key range - * @param {*} [options.only] A single key value. Use this if you need a key - * range that only includes one value for a key. Providing this - * property invalidates all other properties. - * @return {IDBKeyRange} The IDBKeyRange representing the specified options - */ - makeKeyRange: function (options) { - /*jshint onecase:true */ - var keyRange, - hasLower = typeof options.lower != 'undefined', - hasUpper = typeof options.upper != 'undefined', - isOnly = typeof options.only != 'undefined'; - - switch (true) { - case isOnly: - keyRange = this.keyRange.only(options.only); - break; - case hasLower && hasUpper: - keyRange = this.keyRange.bound(options.lower, options.upper, options.excludeLower, options.excludeUpper); - break; - case hasLower: - keyRange = this.keyRange.lowerBound(options.lower, options.excludeLower); - break; - case hasUpper: - keyRange = this.keyRange.upperBound(options.upper, options.excludeUpper); - break; - default: - throw new Error('Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.'); - } - - return keyRange; - - } - - }; - - /** helpers **/ - var empty = {}; - - function mixin (target, source) { - var name, s; - for (name in source) { - s = source[name]; - if (s !== empty[name] && s !== target[name]) { - target[name] = s; - } - } - return target; - } - - function hasVersionError(errorEvent) { - if ('error' in errorEvent.target) { - return errorEvent.target.error.name == 'VersionError'; - } else if ('errorCode' in errorEvent.target) { - return errorEvent.target.errorCode == 12; - } - return false; - } - - IDBStore.prototype = proto; - IDBStore.version = proto.version; - - return IDBStore; - -}, this); - -},{}],35:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],36:[function(require,module,exports){ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - -},{}],37:[function(require,module,exports){ -var Buffer = require('buffer').Buffer; - -module.exports = isBuffer; - -function isBuffer (o) { - return Buffer.isBuffer(o) - || /\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o)); -} - -},{"buffer":156}],38:[function(require,module,exports){ -(function (Buffer){ -/*global Buffer*/ -// Named constants with unique integer values -var C = {}; -// Tokens -var LEFT_BRACE = C.LEFT_BRACE = 0x1; -var RIGHT_BRACE = C.RIGHT_BRACE = 0x2; -var LEFT_BRACKET = C.LEFT_BRACKET = 0x3; -var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4; -var COLON = C.COLON = 0x5; -var COMMA = C.COMMA = 0x6; -var TRUE = C.TRUE = 0x7; -var FALSE = C.FALSE = 0x8; -var NULL = C.NULL = 0x9; -var STRING = C.STRING = 0xa; -var NUMBER = C.NUMBER = 0xb; -// Tokenizer States -var START = C.START = 0x11; -var STOP = C.STOP = 0x12; -var TRUE1 = C.TRUE1 = 0x21; -var TRUE2 = C.TRUE2 = 0x22; -var TRUE3 = C.TRUE3 = 0x23; -var FALSE1 = C.FALSE1 = 0x31; -var FALSE2 = C.FALSE2 = 0x32; -var FALSE3 = C.FALSE3 = 0x33; -var FALSE4 = C.FALSE4 = 0x34; -var NULL1 = C.NULL1 = 0x41; -var NULL2 = C.NULL2 = 0x42; -var NULL3 = C.NULL3 = 0x43; -var NUMBER1 = C.NUMBER1 = 0x51; -var NUMBER3 = C.NUMBER3 = 0x53; -var STRING1 = C.STRING1 = 0x61; -var STRING2 = C.STRING2 = 0x62; -var STRING3 = C.STRING3 = 0x63; -var STRING4 = C.STRING4 = 0x64; -var STRING5 = C.STRING5 = 0x65; -var STRING6 = C.STRING6 = 0x66; -// Parser States -var VALUE = C.VALUE = 0x71; -var KEY = C.KEY = 0x72; -// Parser Modes -var OBJECT = C.OBJECT = 0x81; -var ARRAY = C.ARRAY = 0x82; -// Character constants -var BACK_SLASH = "\\".charCodeAt(0); -var FORWARD_SLASH = "\/".charCodeAt(0); -var BACKSPACE = "\b".charCodeAt(0); -var FORM_FEED = "\f".charCodeAt(0); -var NEWLINE = "\n".charCodeAt(0); -var CARRIAGE_RETURN = "\r".charCodeAt(0); -var TAB = "\t".charCodeAt(0); - -var STRING_BUFFER_SIZE = 64 * 1024; - -function Parser() { - this.tState = START; - this.value = undefined; - - this.string = undefined; // string data - this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE); - this.stringBufferOffset = 0; - this.unicode = undefined; // unicode escapes - this.highSurrogate = undefined; - - this.key = undefined; - this.mode = undefined; - this.stack = []; - this.state = VALUE; - this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary - this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read - this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached - - // Stream offset - this.offset = -1; -} - -// Slow code to string converter (only used when throwing syntax errors) -Parser.toknam = function (code) { - var keys = Object.keys(C); - for (var i = 0, l = keys.length; i < l; i++) { - var key = keys[i]; - if (C[key] === code) { return key; } - } - return code && ("0x" + code.toString(16)); -}; - -var proto = Parser.prototype; -proto.onError = function (err) { throw err; }; -proto.charError = function (buffer, i) { - this.tState = STOP; - this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState))); -}; -proto.appendStringChar = function (char) { - if (this.stringBufferOffset >= STRING_BUFFER_SIZE) { - this.string += this.stringBuffer.toString('utf8'); - this.stringBufferOffset = 0; - } - - this.stringBuffer[this.stringBufferOffset++] = char; -}; -proto.appendStringBuf = function (buf, start, end) { - var size = buf.length; - if (typeof start === 'number') { - if (typeof end === 'number') { - if (end < 0) { - // adding a negative end decreeses the size - size = buf.length - start + end; - } else { - size = end - start; - } - } else { - size = buf.length - start; - } - } - - if (size < 0) { - size = 0; - } - - if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) { - this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); - this.stringBufferOffset = 0; - } - - buf.copy(this.stringBuffer, this.stringBufferOffset, start, end); - this.stringBufferOffset += size; -}; -proto.write = function (buffer) { - if (typeof buffer === "string") buffer = new Buffer(buffer); - var n; - for (var i = 0, l = buffer.length; i < l; i++) { - if (this.tState === START){ - n = buffer[i]; - this.offset++; - if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // { - }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // } - }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [ - }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ] - }else if(n === 0x3a){ this.onToken(COLON, ":"); // : - }else if(n === 0x2c){ this.onToken(COMMA, ","); // , - }else if(n === 0x74){ this.tState = TRUE1; // t - }else if(n === 0x66){ this.tState = FALSE1; // f - }else if(n === 0x6e){ this.tState = NULL1; // n - }else if(n === 0x22){ // " - this.string = ""; - this.stringBufferOffset = 0; - this.tState = STRING1; - }else if(n === 0x2d){ this.string = "-"; this.tState = NUMBER1; // - - }else{ - if (n >= 0x30 && n < 0x40) { // 1-9 - this.string = String.fromCharCode(n); this.tState = NUMBER3; - } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) { - // whitespace - } else { - return this.charError(buffer, i); - } - } - }else if (this.tState === STRING1){ // After open quote - n = buffer[i]; // get current byte from buffer - // check for carry over of a multi byte char split between data chunks - // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration - if (this.bytes_remaining > 0) { - for (var j = 0; j < this.bytes_remaining; j++) { - this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j]; - } - - this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]); - this.bytes_in_sequence = this.bytes_remaining = 0; - i = i + j - 1; - } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time - if (n <= 193 || n > 244) { - return this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + Parser.toknam(this.tState))); - } - if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; - if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; - if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; - if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split - for (var k = 0; k <= (buffer.length - 1 - i); k++) { - this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk - } - this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length; - i = buffer.length - 1; - } else { - this.appendStringBuf(buffer, i, i + this.bytes_in_sequence); - i = i + this.bytes_in_sequence - 1; - } - } else if (n === 0x22) { - this.tState = START; - this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); - this.stringBufferOffset = 0; - this.onToken(STRING, this.string); - this.offset += Buffer.byteLength(this.string, 'utf8') + 1; - this.string = undefined; - } - else if (n === 0x5c) { - this.tState = STRING2; - } - else if (n >= 0x20) { this.appendStringChar(n); } - else { - return this.charError(buffer, i); - } - }else if (this.tState === STRING2){ // After backslash - n = buffer[i]; - if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1; - }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1; - }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1; - }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1; - }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1; - }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1; - }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1; - }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1; - }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3; - }else{ - return this.charError(buffer, i); - } - }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes - n = buffer[i]; - // 0-9 A-F a-f - if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) { - this.unicode += String.fromCharCode(n); - if (this.tState++ === STRING6) { - var intVal = parseInt(this.unicode, 16); - this.unicode = undefined; - if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate - this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal))); - this.highSurrogate = undefined; - } else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate - this.highSurrogate = intVal; - } else { - if (this.highSurrogate !== undefined) { - this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))); - this.highSurrogate = undefined; - } - this.appendStringBuf(new Buffer(String.fromCharCode(intVal))); - } - this.tState = STRING1; - } - } else { - return this.charError(buffer, i); - } - } else if (this.tState === NUMBER1 || this.tState === NUMBER3) { - n = buffer[i]; - - switch (n) { - case 0x30: // 0 - case 0x31: // 1 - case 0x32: // 2 - case 0x33: // 3 - case 0x34: // 4 - case 0x35: // 5 - case 0x36: // 6 - case 0x37: // 7 - case 0x38: // 8 - case 0x39: // 9 - case 0x2e: // . - case 0x65: // e - case 0x45: // E - case 0x2b: // + - case 0x2d: // - - this.string += String.fromCharCode(n); - this.tState = NUMBER3; - break; - default: - this.tState = START; - var result = Number(this.string); - - if (isNaN(result)){ - return this.charError(buffer, i); - } - - if ((this.string.match(/[0-9]+/) == this.string) && (result.toString() != this.string)) { - // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number - this.onToken(STRING, this.string); - } else { - this.onToken(NUMBER, result); - } - - this.offset += this.string.length - 1; - this.string = undefined; - i--; - break; - } - }else if (this.tState === TRUE1){ // r - if (buffer[i] === 0x72) { this.tState = TRUE2; } - else { return this.charError(buffer, i); } - }else if (this.tState === TRUE2){ // u - if (buffer[i] === 0x75) { this.tState = TRUE3; } - else { return this.charError(buffer, i); } - }else if (this.tState === TRUE3){ // e - if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; } - else { return this.charError(buffer, i); } - }else if (this.tState === FALSE1){ // a - if (buffer[i] === 0x61) { this.tState = FALSE2; } - else { return this.charError(buffer, i); } - }else if (this.tState === FALSE2){ // l - if (buffer[i] === 0x6c) { this.tState = FALSE3; } - else { return this.charError(buffer, i); } - }else if (this.tState === FALSE3){ // s - if (buffer[i] === 0x73) { this.tState = FALSE4; } - else { return this.charError(buffer, i); } - }else if (this.tState === FALSE4){ // e - if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; } - else { return this.charError(buffer, i); } - }else if (this.tState === NULL1){ // u - if (buffer[i] === 0x75) { this.tState = NULL2; } - else { return this.charError(buffer, i); } - }else if (this.tState === NULL2){ // l - if (buffer[i] === 0x6c) { this.tState = NULL3; } - else { return this.charError(buffer, i); } - }else if (this.tState === NULL3){ // l - if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; } - else { return this.charError(buffer, i); } - } - } -}; -proto.onToken = function (token, value) { - // Override this to get events -}; - -proto.parseError = function (token, value) { - this.tState = STOP; - this.onError(new Error("Unexpected " + Parser.toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + Parser.toknam(this.state))); -}; -proto.push = function () { - this.stack.push({value: this.value, key: this.key, mode: this.mode}); -}; -proto.pop = function () { - var value = this.value; - var parent = this.stack.pop(); - this.value = parent.value; - this.key = parent.key; - this.mode = parent.mode; - this.emit(value); - if (!this.mode) { this.state = VALUE; } -}; -proto.emit = function (value) { - if (this.mode) { this.state = COMMA; } - this.onValue(value); -}; -proto.onValue = function (value) { - // Override me -}; -proto.onToken = function (token, value) { - if(this.state === VALUE){ - if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){ - if (this.value) { - this.value[this.key] = value; - } - this.emit(value); - }else if(token === LEFT_BRACE){ - this.push(); - if (this.value) { - this.value = this.value[this.key] = {}; - } else { - this.value = {}; - } - this.key = undefined; - this.state = KEY; - this.mode = OBJECT; - }else if(token === LEFT_BRACKET){ - this.push(); - if (this.value) { - this.value = this.value[this.key] = []; - } else { - this.value = []; - } - this.key = 0; - this.mode = ARRAY; - this.state = VALUE; - }else if(token === RIGHT_BRACE){ - if (this.mode === OBJECT) { - this.pop(); - } else { - return this.parseError(token, value); - } - }else if(token === RIGHT_BRACKET){ - if (this.mode === ARRAY) { - this.pop(); - } else { - return this.parseError(token, value); - } - }else{ - return this.parseError(token, value); - } - }else if(this.state === KEY){ - if (token === STRING) { - this.key = value; - this.state = COLON; - } else if (token === RIGHT_BRACE) { - this.pop(); - } else { - return this.parseError(token, value); - } - }else if(this.state === COLON){ - if (token === COLON) { this.state = VALUE; } - else { return this.parseError(token, value); } - }else if(this.state === COMMA){ - if (token === COMMA) { - if (this.mode === ARRAY) { this.key++; this.state = VALUE; } - else if (this.mode === OBJECT) { this.state = KEY; } - - } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) { - this.pop(); - } else { - return this.parseError(token, value); - } - }else{ - return this.parseError(token, value); - } -}; - -Parser.C = C; - -module.exports = Parser; - -}).call(this,require("buffer").Buffer) -},{"buffer":156}],39:[function(require,module,exports){ -var encodings = require('./lib/encodings'); - -module.exports = Codec; - -function Codec(opts){ - this.opts = opts || {}; - this.encodings = encodings; -} - -Codec.prototype._encoding = function(encoding){ - if (typeof encoding == 'string') encoding = encodings[encoding]; - if (!encoding) encoding = encodings.id; - return 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) - }; - if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'; - if (_op.prefix) op.prefix = _op.prefix; - if ('value' in _op) { - op.value = self.encodeValue(_op.value, opts, _op); - if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'; - } - return op; - }); -}; - -var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']; - -Codec.prototype.encodeLtgt = function(ltgt){ - var self = this; - var ret = {}; - Object.keys(ltgt).forEach(function(key){ - ret[key] = ltgtKeys.indexOf(key) > -1 - ? self.encodeKey(ltgt[key], ltgt) - : ltgt[key] - }); - return ret; -}; - -Codec.prototype.createStreamDecoder = function(opts){ - var self = this; - - if (opts.keys && opts.values) { - return function(key, value){ - return { - key: self.decodeKey(key, opts), - value: self.decodeValue(value, opts) - }; - }; - } else if (opts.keys) { - return function(key) { - return self.decodeKey(key, opts); - }; - } else if (opts.values) { - return function(_, value){ - return self.decodeValue(value, opts); - } - } else { - return function(){}; - } -}; - -Codec.prototype.keyAsBuffer = function(opts){ - return this._keyEncoding(opts).buffer; -}; - -Codec.prototype.valueAsBuffer = function(opts){ - return this._valueEncoding(opts).buffer; -}; - - -},{"./lib/encodings":40}],40:[function(require,module,exports){ -(function (Buffer){ - -exports.utf8 = exports['utf-8'] = { - encode: function(data){ - return isBinary(data) - ? data - : String(data); - }, - decode: identity, - buffer: false, - type: 'utf8' -}; - -exports.json = { - encode: JSON.stringify, - decode: JSON.parse, - buffer: false, - type: 'json' -}; - -exports.binary = { - encode: function(data){ - return isBinary(data) - ? data - : new Buffer(data); - }, - decode: identity, - buffer: true, - type: 'binary' -}; - -exports.id = { - encode: function(data){ - return data; - }, - decode: function(data){ - return data; - }, - buffer: false, - 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: true, - type: type - }; -}); - -function identity(value){ - return value; -} - -function isBinary(data){ - return data === undefined - || data === null - || Buffer.isBuffer(data); -} - - -}).call(this,require("buffer").Buffer) -},{"buffer":156}],41:[function(require,module,exports){ -/* Copyright (c) 2012-2015 LevelUP contributors - * See list at - * MIT License - * - */ - -var createError = require('errno').create - , LevelUPError = createError('LevelUPError') - , NotFoundError = createError('NotFoundError', LevelUPError) - -NotFoundError.prototype.notFound = true -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":32}],42:[function(require,module,exports){ -var inherits = require('inherits'); -var Readable = require('readable-stream').Readable; -var extend = require('xtend'); -var EncodingError = require('level-errors').EncodingError; - -module.exports = ReadStream; -inherits(ReadStream, Readable); - -function ReadStream(iterator, options){ - if (!(this instanceof ReadStream)) return new ReadStream(iterator, options); - Readable.call(this, extend(options, { - objectMode: true - })); - this._iterator = iterator; - this._destroyed = false; - this._decoder = null; - if (options && options.decoder) this._decoder = options.decoder; - this.on('end', this._cleanup.bind(this)); -} - -ReadStream.prototype._read = function(){ - var self = this; - if (this._destroyed) return; - - this._iterator.next(function(err, key, value){ - if (self._destroyed) return; - if (err) return self.emit('error', err); - if (key === undefined && value === undefined) { - self.push(null); - } else { - if (!self._decoder) return self.push({ key: key, value: value }); - - try { - var value = self._decoder(key, value); - } catch (err) { - self.emit('error', new EncodingError(err)); - self.push(null); - return; - } - self.push(value); - } - }); -}; - -ReadStream.prototype.destroy = -ReadStream.prototype._cleanup = function(){ - var self = this; - if (this._destroyed) return; - this._destroyed = true; - - this._iterator.end(function(err){ - if (err) return self.emit('error', err); - self.emit('close'); - }); -}; - - -},{"inherits":35,"level-errors":41,"readable-stream":49,"xtend":92}],43:[function(require,module,exports){ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; - -},{}],44:[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 duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -module.exports = Duplex; - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -} -/**/ - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -forEach(objectKeys(Writable.prototype), function(method) { - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; -}); - -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) - this.readable = false; - - if (options && options.writable === false) - this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; - - this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(this.end.bind(this)); -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -}).call(this,require('_process')) -},{"./_stream_readable":46,"./_stream_writable":48,"_process":206,"core-util-is":8,"inherits":35}],45:[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. - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); -}; - -},{"./_stream_transform":47,"core-util-is":8,"inherits":35}],46:[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. - -module.exports = Readable; - -/**/ -var isArray = require('isarray'); -/**/ - - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Readable.ReadableState = ReadableState; - -var EE = require('events').EventEmitter; - -/**/ -if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -var Stream = require('stream'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var StringDecoder; - - -/**/ -var debug = require('util'); -if (debug && debug.debuglog) { - debug = debug.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - - -util.inherits(Readable, Stream); - -function ReadableState(options, stream) { - var Duplex = require('./_stream_duplex'); - - options = options || {}; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = options.objectMode ? 16 : 16 * 1024; - this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - 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. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) - this.objectMode = this.objectMode || !!options.readableObjectMode; - - // 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; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - var Duplex = require('./_stream_duplex'); - - if (!(this instanceof Readable)) - return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - Stream.call(this); -} - -// 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 (util.isString(chunk) && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; - -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 = false; - if (!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 { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - - if (!addToFront) - state.reading = false; - - // if we want the data now, just emit it. - 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); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// 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, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 128MB -var MAX_HWM = 0x800000; -function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; - } - return n; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; - - if (isNaN(n) || util.isNull(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; - } - - if (n <= 0) - return 0; - - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); - - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; - } - - return n; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function(n) { - debug('read', n); - var state = this._readableState; - var nOrig = n; - - if (!util.isNumber(n) || n > 0) - state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) - endReadable(this); - else - emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) - endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } - - if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - } - - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - - var ret; - if (n > 0) - ret = fromList(n, state); - else - ret = null; - - if (util.isNull(ret)) { - state.needReadable = true; - n = 0; - } - - state.length -= n; - - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended && state.length === 0) - endReadable(this); - - if (!util.isNull(ret)) - this.emit('data', ret); - - return ret; -}; - -function chunkInvalid(state, chunk) { - var er = null; - if (!util.isBuffer(chunk) && - !util.isString(chunk) && - !util.isNullOrUndefined(chunk) && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - - -function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(function() { - maybeReadMore_(stream, state); - }); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); -}; - -Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var 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); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - process.nextTick(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); - } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - 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); - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && - (!dest._writableState || dest._writableState.needDrain)) - ondrain(); - } - - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - if (false === ret) { - debug('false write response, pause', - src._readableState.awaitDrain); - src._readableState.awaitDrain++; - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; - - - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) - state.awaitDrain--; - if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - - -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; - - if (!dest) - dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - // If listening to data, and it has not explicitly been paused, - // then call resume to start the flow of data on the next tick. - if (ev === 'data' && false !== this._readableState.flowing) { - this.resume(); - } - - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - var self = this; - process.nextTick(function() { - debug('readable nexttick read 0'); - self.read(0); - }); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function() { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - if (!state.reading) { - debug('resume read 0'); - this.read(0); - } - resume(this, state); - } - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(function() { - resume_(stream, state); - }); - } -} - -function resume_(stream, state) { - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) - stream.read(0); -} - -Readable.prototype.pause = function() { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - if (state.flowing) { - do { - var chunk = stream.read(); - } while (null !== chunk && state.flowing); - } -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function() { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function(chunk) { - debug('wrapped data'); - if (state.decoder) - chunk = state.decoder.write(chunk); - if (!chunk || !state.objectMode && !chunk.length) - return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - - - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; - - // nothing in the list, definitely empty. - if (list.length === 0) - return null; - - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer(n); - - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} - -}).call(this,require('_process')) -},{"./_stream_duplex":44,"_process":206,"buffer":156,"core-util-is":8,"events":169,"inherits":35,"isarray":43,"stream":223,"string_decoder/":50,"util":154}],47:[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 -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - -module.exports = Transform; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(Transform, Duplex); - - -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (!util.isNullOrUndefined(data)) - stream.push(data); - - if (cb) - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - - -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - - Duplex.call(this, options); - - this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - this.once('prefinish', function() { - if (util.isFunction(this._flush)) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); -} - -Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); -}; - -Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function(n) { - var ts = this._transformState; - - if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - - -function done(stream, er) { - if (er) - return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; - - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); - - if (ts.transforming) - throw new Error('calling transform done when still transforming'); - - return stream.push(null); -} - -},{"./_stream_duplex":44,"core-util-is":8,"inherits":35}],48:[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, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Writable.WritableState = WritableState; - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Stream = require('stream'); - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - var Duplex = require('./_stream_duplex'); - - options = options || {}; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = options.objectMode ? 16 : 16 * 1024; - this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) - this.objectMode = this.objectMode || !!options.writableObjectMode; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = 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. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // 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'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // 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. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.buffer = []; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; -} - -function Writable(options) { - var Duplex = require('./_stream_duplex'); - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); -}; - - -function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); -} - -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!util.isBuffer(chunk) && - !util.isString(chunk) && - !util.isNullOrUndefined(chunk) && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; -} - -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (util.isFunction(encoding)) { - cb = encoding; - encoding = null; - } - - if (util.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (!util.isFunction(cb)) - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } - - return ret; -}; - -Writable.prototype.cork = function() { - var state = this._writableState; - - state.corked++; -}; - -Writable.prototype.uncork = function() { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && - !state.corked && - !state.finished && - !state.bufferProcessing && - state.buffer.length) - clearBuffer(this, state); - } -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - util.isString(chunk)) { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (util.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; - - if (state.writing || state.corked) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, false, len, chunk, encoding, cb); - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) - stream._writev(chunk, state.onwrite); - else - stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - if (sync) - process.nextTick(function() { - state.pendingcb--; - cb(er); - }); - else { - state.pendingcb--; - cb(er); - } - - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); - - if (!finished && - !state.corked && - !state.bufferProcessing && - state.buffer.length) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - - if (stream._writev && state.buffer.length > 1) { - // Fast case, write everything using _writev() - var cbs = []; - for (var c = 0; c < state.buffer.length; c++) - cbs.push(state.buffer[c].callback); - - // count the one we are adding, as well. - // TODO(isaacs) clean this up - state.pendingcb++; - doWrite(stream, state, true, state.length, state.buffer, '', function(err) { - for (var i = 0; i < cbs.length; i++) { - state.pendingcb--; - cbs[i](err); - } - }); - - // Clear buffer - state.buffer = []; - } else { - // Slow case, write chunks one-by-one - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } - } - - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; - } - - state.bufferProcessing = false; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); - -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (util.isFunction(chunk)) { - cb = chunk; - chunk = null; - encoding = null; - } else if (util.isFunction(encoding)) { - cb = encoding; - encoding = null; - } - - if (!util.isNullOrUndefined(chunk)) - this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); -}; - - -function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); -} - -function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } -} - -function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else - prefinish(stream, state); - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - process.nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; -} - -}).call(this,require('_process')) -},{"./_stream_duplex":44,"_process":206,"buffer":156,"core-util-is":8,"inherits":35,"stream":223}],49:[function(require,module,exports){ -(function (process){ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = require('stream'); -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'); -if (!process.browser && process.env.READABLE_STREAM === 'disable') { - module.exports = require('stream'); -} - -}).call(this,require('_process')) -},{"./lib/_stream_duplex.js":44,"./lib/_stream_passthrough.js":45,"./lib/_stream_readable.js":46,"./lib/_stream_transform.js":47,"./lib/_stream_writable.js":48,"_process":206,"stream":223}],50:[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. - -var Buffer = require('buffer').Buffer; - -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (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 true; - default: return false; - } - } - - -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; - - -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - 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; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; -}; - -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; -}; - -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); -} - -function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; -} - -function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; -} - -},{"buffer":156}],51:[function(require,module,exports){ -(function (Buffer){ -module.exports = Level - -var IDB = require('idb-wrapper') -var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN -var util = require('util') -var Iterator = require('./iterator') -var isBuffer = require('isbuffer') -var xtend = require('xtend') -var toBuffer = require('typedarray-to-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 -} - -util.inherits(Level, AbstractLevelDOWN) - -Level.prototype._open = function(options, callback) { - var self = this - - var idbOpts = { - storeName: this.location, - autoIncrement: false, - 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 (value === undefined) { - // 'NotFound' error, consistent with LevelDOWN API - return callback(new Error('NotFound')) - } - // by default return buffers, unless explicitly told not to - var asBuffer = true - if (options.asBuffer === false) asBuffer = false - if (options.raw) asBuffer = false - if (asBuffer) { - if (value instanceof Uint8Array) value = toBuffer(value) - else value = new Buffer(String(value)) - } - return 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) { - if (value instanceof ArrayBuffer) { - value = toBuffer(new Uint8Array(value)) - } - var obj = this.convertEncoding(key, value, options) - if (Buffer.isBuffer(obj.value)) { - if (typeof value.toArrayBuffer === 'function') { - obj.value = new Uint8Array(value.toArrayBuffer()) - } else { - 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() - if (stringed === 'NaN') value = 'NaN' - } - var valEnc = options.valueEncoding - var obj = {key: key, value: value} - if (value && (!valEnc || valEnc !== 'binary')) { - if (typeof obj.value !== 'object') { - obj.value = stringed - } - } - return obj -} - -Level.prototype.iterator = function (options) { - if (typeof options !== 'object') options = {} - return new Iterator(this.idb, options) -} - -Level.prototype._batch = function (array, options, callback) { - var op - var i - var k - var copiedOp - var currentOp - var modified = [] - - if (array.length === 0) return setTimeout(callback, 0) - - for (i = 0; i < array.length; i++) { - copiedOp = {} - currentOp = array[i] - modified[i] = copiedOp - - var converted = this.convertEncoding(currentOp.key, currentOp.value, options) - currentOp.key = converted.key - currentOp.value = converted.value - - for (k in currentOp) { - if (k === 'type' && currentOp[k] == 'del') { - copiedOp[k] = 'remove' - } else { - copiedOp[k] = currentOp[k] - } - } - } - - return this.idb.batch(modified, function(){ callback() }, callback) -} - -Level.prototype._close = function (callback) { - this.idb.db.close() - callback() -} - -Level.prototype._approximateSize = function (start, end, callback) { - var err = new Error('Not implemented') - if (callback) - return callback(err) - - throw err -} - -Level.prototype._isBuffer = function (obj) { - return Buffer.isBuffer(obj) -} - -Level.destroy = function (db, callback) { - if (typeof db === 'object') { - var prefix = db.IDBOptions.storePrefix || 'IDBWrapper-' - var dbname = db.location - } else { - var prefix = 'IDBWrapper-' - var dbname = db - } - var request = indexedDB.deleteDatabase(prefix + dbname) - request.onsuccess = function() { - callback() - } - request.onerror = function(err) { - callback(err) - } -} - -var checkKeyValue = Level.prototype._checkKeyValue = function (obj, type) { - if (obj === null || obj === undefined) - return new Error(type + ' cannot be `null` or `undefined`') - if (obj === null || obj === undefined) - return new Error(type + ' cannot be `null` or `undefined`') - if (isBuffer(obj) && obj.byteLength === 0) - return new Error(type + ' cannot be an empty ArrayBuffer') - if (String(obj) === '') - return new Error(type + ' cannot be an empty String') - if (obj.length === 0) - return new Error(type + ' cannot be an empty Array') -} - -}).call(this,require("buffer").Buffer) -},{"./iterator":52,"abstract-leveldown":55,"buffer":156,"idb-wrapper":34,"isbuffer":37,"typedarray-to-buffer":89,"util":229,"xtend":58}],52:[function(require,module,exports){ -var util = require('util') -var AbstractIterator = require('abstract-leveldown').AbstractIterator -var ltgt = require('ltgt') - -module.exports = Iterator - -function Iterator (db, options) { - if (!options) options = {} - this.options = options - AbstractIterator.call(this, db) - this._order = options.reverse ? 'DESC': 'ASC' - this._limit = options.limit - this._count = 0 - this._done = false - var lower = ltgt.lowerBound(options) - var upper = ltgt.upperBound(options) - try { - this._keyRange = lower || upper ? this.db.makeKeyRange({ - lower: lower, - upper: upper, - excludeLower: ltgt.lowerBoundExclusive(options), - excludeUpper: ltgt.upperBoundExclusive(options) - }) : null - } catch (e) { - // The lower key is greater than the upper key. - // IndexedDB throws an error, but we'll just return 0 results. - this._keyRangeError = true - } - this.callback = null -} - -util.inherits(Iterator, AbstractIterator) - -Iterator.prototype.createIterator = function() { - var self = this - - self.iterator = self.db.iterate(function () { - self.onItem.apply(self, arguments) - }, { - keyRange: self._keyRange, - autoContinue: false, - order: self._order, - onError: function(err) { console.log('horrible error', err) }, - }) -} - -// TODO the limit implementation here just ignores all reads after limit has been reached -// it should cancel the iterator instead but I don't know how -Iterator.prototype.onItem = function (value, cursor, cursorTransaction) { - if (!cursor && this.callback) { - this.callback() - this.callback = false - return - } - var shouldCall = true - - if (!!this._limit && this._limit > 0 && this._count++ >= this._limit) - shouldCall = false - - if (shouldCall) this.callback(false, cursor.key, cursor.value) - if (cursor) cursor['continue']() -} - -Iterator.prototype._next = function (callback) { - if (!callback) return new Error('next() requires a callback argument') - if (this._keyRangeError) return callback() - if (!this._started) { - this.createIterator() - this._started = true - } - this.callback = callback -} - -},{"abstract-leveldown":55,"ltgt":63,"util":229}],53:[function(require,module,exports){ -(function (process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ - -function AbstractChainedBatch (db) { - this._db = db - this._operations = [] - this._written = false -} - -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 - err = this._db._checkKeyValue(value, 'value', this._db._isBuffer) - if (err) throw err - - if (!this._db._isBuffer(key)) key = String(key) - if (!this._db._isBuffer(value)) value = String(value) - - if (typeof this._put == 'function' ) - this._put(key, value) - else - this._operations.push({ type: 'put', key: key, value: value }) - - return this -} - -AbstractChainedBatch.prototype.del = function (key) { - this._checkWritten() - - var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer) - if (err) throw err - - if (!this._db._isBuffer(key)) key = String(key) - - if (typeof this._del == 'function' ) - this._del(key) - else - this._operations.push({ type: 'del', key: key }) - - return this -} - -AbstractChainedBatch.prototype.clear = function () { - this._checkWritten() - - this._operations = [] - - if (typeof this._clear == 'function' ) - this._clear() - - return this -} - -AbstractChainedBatch.prototype.write = function (options, callback) { - this._checkWritten() - - if (typeof options == 'function') - callback = options - if (typeof callback != 'function') - throw new Error('write() requires a callback argument') - if (typeof options != 'object') - options = {} - - this._written = true - - if (typeof this._write == 'function' ) - return this._write(callback) - - if (typeof this._db._batch == 'function') - return this._db._batch(this._operations, options, callback) - - process.nextTick(callback) -} - -module.exports = AbstractChainedBatch -}).call(this,require('_process')) -},{"_process":206}],54:[function(require,module,exports){ -arguments[4][12][0].apply(exports,arguments) -},{"_process":206,"dup":12}],55:[function(require,module,exports){ -(function (Buffer,process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ - -var xtend = require('xtend') - , AbstractIterator = require('./abstract-iterator') - , AbstractChainedBatch = require('./abstract-chained-batch') - -function AbstractLevelDOWN (location) { - if (!arguments.length || location === undefined) - throw new Error('constructor requires at least a location argument') - - if (typeof location != 'string') - throw new Error('constructor requires a location string argument') - - this.location = location -} - -AbstractLevelDOWN.prototype.open = function (options, callback) { - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('open() requires a callback argument') - - if (typeof options != 'object') - options = {} - - if (typeof this._open == 'function') - return this._open(options, callback) - - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.close = function (callback) { - if (typeof callback != 'function') - throw new Error('close() requires a callback argument') - - if (typeof this._close == 'function') - return this._close(callback) - - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.get = function (key, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('get() requires a callback argument') - - if (err = this._checkKeyValue(key, 'key', this._isBuffer)) - return callback(err) - - if (!this._isBuffer(key)) - key = String(key) - - if (typeof options != 'object') - options = {} - - if (typeof this._get == 'function') - return this._get(key, options, callback) - - process.nextTick(function () { callback(new Error('NotFound')) }) -} - -AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('put() requires a callback argument') - - if (err = this._checkKeyValue(key, 'key', this._isBuffer)) - return callback(err) - - if (err = this._checkKeyValue(value, 'value', this._isBuffer)) - return callback(err) - - if (!this._isBuffer(key)) - key = String(key) - - // coerce value to string in node, don't touch it in browser - // (indexeddb can store any JS type) - if (!this._isBuffer(value) && !process.browser) - value = String(value) - - if (typeof options != 'object') - options = {} - - if (typeof this._put == 'function') - return this._put(key, value, options, callback) - - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.del = function (key, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('del() requires a callback argument') - - if (err = this._checkKeyValue(key, 'key', this._isBuffer)) - return callback(err) - - if (!this._isBuffer(key)) - key = String(key) - - if (typeof options != 'object') - options = {} - - if (typeof this._del == 'function') - return this._del(key, options, callback) - - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.batch = function (array, options, callback) { - if (!arguments.length) - return this._chainedBatch() - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('batch(array) requires a callback argument') - - if (!Array.isArray(array)) - return callback(new Error('batch(array) requires an array argument')) - - if (typeof options != 'object') - options = {} - - var i = 0 - , l = array.length - , e - , err - - for (; i < l; i++) { - e = array[i] - if (typeof e != 'object') - continue - - 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 (e.type == 'put') { - if (err = this._checkKeyValue(e.value, 'value', this._isBuffer)) - return callback(err) - } - } - - if (typeof this._batch == 'function') - return this._batch(array, options, callback) - - process.nextTick(callback) -} - -//TODO: remove from here, not a necessary primitive -AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) { - if ( start == null - || end == null - || typeof start == 'function' - || typeof end == 'function') { - throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') - } - - if (typeof callback != 'function') - throw new Error('approximateSize() requires a callback argument') - - if (!this._isBuffer(start)) - start = String(start) - - if (!this._isBuffer(end)) - end = String(end) - - if (typeof this._approximateSize == 'function') - return this._approximateSize(start, end, callback) - - process.nextTick(function () { - callback(null, 0) - }) -} - -AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { - var self = this - - options = xtend(options) - - ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) { - if (options[o] && self._isBuffer(options[o]) && options[o].length === 0) - delete options[o] - }) - - options.reverse = !!options.reverse - - // fix `start` so it takes into account gt, gte, lt, lte as appropriate - if (options.reverse && options.lt) - options.start = options.lt - if (options.reverse && options.lte) - options.start = options.lte - if (!options.reverse && options.gt) - options.start = options.gt - if (!options.reverse && options.gte) - options.start = options.gte - - if ((options.reverse && options.lt && !options.lte) - || (!options.reverse && options.gt && !options.gte)) - options.exclusiveStart = true // start should *not* include matching key - - return options -} - -AbstractLevelDOWN.prototype.iterator = function (options) { - if (typeof options != 'object') - options = {} - - options = this._setupIteratorOptions(options) - - if (typeof this._iterator == 'function') - return this._iterator(options) - - return 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 (obj === null || obj === undefined) - return new Error(type + ' cannot be `null` or `undefined`') - - if (this._isBuffer(obj)) { - if (obj.length === 0) - 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("../../../../../search-index/node_modules/is-buffer/index.js")},require('_process')) -},{"../../../../../search-index/node_modules/is-buffer/index.js":173,"./abstract-chained-batch":53,"./abstract-iterator":54,"_process":206,"xtend":56}],56:[function(require,module,exports){ -module.exports = extend - -function extend() { - var target = {} - - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (source.hasOwnProperty(key)) { - target[key] = source[key] - } - } - } - - return target -} - -},{}],57:[function(require,module,exports){ -module.exports = hasKeys - -function hasKeys(source) { - return source !== null && - (typeof source === "object" || - typeof source === "function") -} - -},{}],58:[function(require,module,exports){ -var Keys = require("object-keys") -var hasKeys = require("./has-keys") - -module.exports = extend - -function extend() { - var target = {} - - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] - - if (!hasKeys(source)) { - continue - } - - var keys = Keys(source) - - for (var j = 0; j < keys.length; j++) { - var name = keys[j] - target[name] = source[name] - } - } - - return target -} - -},{"./has-keys":57,"object-keys":65}],59:[function(require,module,exports){ -/* Copyright (c) 2012-2016 LevelUP contributors - * See list at - * MIT License - * - */ - -var util = require('./util') - , WriteError = require('level-errors').WriteError - - , getOptions = util.getOptions - , dispatchError = util.dispatchError - -function Batch (levelup, codec) { - this._levelup = levelup - this._codec = codec - this.batch = levelup.db.batch() - this.ops = [] - this.length = 0 -} - -Batch.prototype.put = function (key_, value_, options) { - options = getOptions(options) - - var key = this._codec.encodeKey(key_, options) - , value = this._codec.encodeValue(value_, options) - - try { - this.batch.put(key, value) - } catch (e) { - throw new WriteError(e) - } - this.ops.push({ type : 'put', key : key, value : value }) - this.length++ - - return this -} - -Batch.prototype.del = function (key_, options) { - options = getOptions(options) - - var key = this._codec.encodeKey(key_, options) - - try { - this.batch.del(key) - } catch (err) { - throw new WriteError(err) - } - this.ops.push({ type : 'del', key : key }) - this.length++ - - return this -} - -Batch.prototype.clear = function () { - try { - this.batch.clear() - } catch (err) { - throw new WriteError(err) - } - - this.ops = [] - this.length = 0 - return this -} - -Batch.prototype.write = function (callback) { - var levelup = this._levelup - , ops = this.ops - - try { - this.batch.write(function (err) { - if (err) - return dispatchError(levelup, new WriteError(err), callback) - levelup.emit('batch', ops) - if (callback) - callback() - }) - } catch (err) { - throw new WriteError(err) - } -} - -module.exports = Batch - -},{"./util":61,"level-errors":41}],60:[function(require,module,exports){ -(function (process){ -/* Copyright (c) 2012-2016 LevelUP contributors - * See list at - * MIT License - * - */ - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , deprecate = require('util').deprecate - , extend = require('xtend') - , prr = require('prr') - , DeferredLevelDOWN = require('deferred-leveldown') - , IteratorStream = require('level-iterator-stream') - - , errors = require('level-errors') - , WriteError = errors.WriteError - , ReadError = errors.ReadError - , NotFoundError = errors.NotFoundError - , OpenError = errors.OpenError - , EncodingError = errors.EncodingError - , InitializationError = errors.InitializationError - , LevelUPError = errors.LevelUPError - - , util = require('./util') - , Batch = require('./batch') - , Codec = require('level-codec') - - , getOptions = util.getOptions - , defaultOptions = util.defaultOptions - , getLevelDOWN = require('./leveldown') - , dispatchError = util.dispatchError - , isDefined = util.isDefined - -function getCallback (options, callback) { - return typeof options == 'function' ? options : callback -} - -// Possible LevelUP#_status values: -// - 'new' - newly created, not opened or closed -// - 'opening' - waiting for the database to be opened, post open() -// - 'open' - successfully opened the database, available for use -// - 'closing' - waiting for the database to be closed, post close() -// - 'closed' - database has been successfully closed, should not be -// used except for another open() operation - -function LevelUP (location, options, callback) { - if (!(this instanceof LevelUP)) - return new LevelUP(location, options, callback) - - var error - - EventEmitter.call(this) - this.setMaxListeners(Infinity) - - if (typeof location == 'function') { - options = typeof options == 'object' ? options : {} - options.db = location - location = null - } else if (typeof location == 'object' && typeof location.db == 'function') { - options = location - location = null - } - - - if (typeof options == 'function') { - callback = options - options = {} - } - - if ((!options || typeof options.db != 'function') && typeof location != 'string') { - error = new InitializationError( - 'Must provide a location for the database') - if (callback) { - return process.nextTick(function () { - callback(error) - }) - } - throw error - } - - options = getOptions(options) - this.options = extend(defaultOptions, options) - this._codec = new Codec(this.options) - this._status = 'new' - // set this.location as enumerable but not configurable or writable - prr(this, 'location', location, 'e') - - this.open(callback) -} - -inherits(LevelUP, EventEmitter) - -LevelUP.prototype.open = function (callback) { - var self = this - , dbFactory - , db - - if (this.isOpen()) { - if (callback) - process.nextTick(function () { callback(null, self) }) - return this - } - - if (this._isOpening()) { - return callback && this.once( - 'open' - , function () { callback(null, self) } - ) - } - - this.emit('opening') - this._status = 'opening' - this.db = new DeferredLevelDOWN(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) { - return dispatchError(self, new OpenError(err), callback) - } else { - self.db.setDb(db) - self.db = db - self._status = 'open' - if (callback) - callback(null, self) - self.emit('open') - self.emit('ready') - } - }) -} - -LevelUP.prototype.close = function (callback) { - var self = this - - if (this.isOpen()) { - this._status = 'closing' - this.db.close(function () { - self._status = 'closed' - self.emit('closed') - if (callback) - callback.apply(null, arguments) - }) - this.emit('closing') - this.db = new DeferredLevelDOWN(this.location) - } else if (this._status == 'closed' && callback) { - return process.nextTick(callback) - } else if (this._status == 'closing' && callback) { - this.once('closed', callback) - } else if (this._isOpening()) { - this.once('open', function () { - self.close(callback) - }) - } -} - -LevelUP.prototype.isOpen = function () { - return this._status == 'open' -} - -LevelUP.prototype._isOpening = function () { - return this._status == 'opening' -} - -LevelUP.prototype.isClosed = function () { - return (/^clos/).test(this._status) -} - -function maybeError(db, options, callback) { - if (!db._isOpening() && !db.isOpen()) { - dispatchError( - db - , new ReadError('Database is not open') - , callback - ) - return true - } -} - -function writeError (db, message, callback) { - dispatchError( - db - , new WriteError(message) - , callback - ) -} - -function readError (db, message, callback) { - dispatchError( - db - , new ReadError(message) - , callback - ) -} - - -LevelUP.prototype.get = function (key_, options, callback) { - var self = this - , key - - callback = getCallback(options, callback) - - if (maybeError(this, options, callback)) - return - - if (key_ === null || key_ === undefined || 'function' !== typeof callback) - return readError(this - , 'get() requires key and callback arguments', callback) - - options = util.getOptions(options) - key = this._codec.encodeKey(key_, options) - - options.asBuffer = this._codec.valueAsBuffer(options) - - this.db.get(key, options, function (err, value) { - if (err) { - if ((/notfound/i).test(err) || err.notFound) { - err = new NotFoundError( - 'Key not found in database [' + key_ + ']', err) - } else { - err = new ReadError(err) - } - return dispatchError(self, err, callback) - } - if (callback) { - try { - value = self._codec.decodeValue(value, options) - } catch (e) { - return callback(new EncodingError(e)) - } - callback(null, value) - } - }) -} - -LevelUP.prototype.put = function (key_, value_, options, callback) { - var self = this - , key - , value - - callback = getCallback(options, callback) - - if (key_ === null || key_ === undefined) - return writeError(this, 'put() requires a key argument', callback) - - if (maybeError(this, options, callback)) - return - - options = getOptions(options) - key = this._codec.encodeKey(key_, options) - value = this._codec.encodeValue(value_, options) - - this.db.put(key, value, options, function (err) { - if (err) { - return dispatchError(self, new WriteError(err), callback) - } else { - self.emit('put', key_, value_) - if (callback) - callback() - } - }) -} - -LevelUP.prototype.del = function (key_, options, callback) { - var self = this - , key - - callback = getCallback(options, callback) - - if (key_ === null || key_ === undefined) - return writeError(this, 'del() requires a key argument', callback) - - if (maybeError(this, options, callback)) - return - - options = getOptions(options) - key = this._codec.encodeKey(key_, options) - - this.db.del(key, options, function (err) { - if (err) { - return dispatchError(self, new WriteError(err), callback) - } else { - self.emit('del', key_) - if (callback) - callback() - } - }) -} - -LevelUP.prototype.batch = function (arr_, options, callback) { - var self = this - , keyEnc - , valueEnc - , arr - - if (!arguments.length) - return new Batch(this, this._codec) - - callback = getCallback(options, callback) - - if (!Array.isArray(arr_)) - return writeError(this, 'batch() requires an array argument', callback) - - if (maybeError(this, options, callback)) - return - - options = getOptions(options) - arr = self._codec.encodeBatch(arr_, options) - arr = arr.map(function (op) { - if (!op.type && op.key !== undefined && op.value !== undefined) - op.type = 'put' - return op - }) - - this.db.batch(arr, options, function (err) { - if (err) { - return dispatchError(self, new WriteError(err), callback) - } else { - self.emit('batch', arr_) - if (callback) - callback() - } - }) -} - -LevelUP.prototype.approximateSize = deprecate(function (start_, end_, options, callback) { - var self = this - , start - , end - - callback = getCallback(options, callback) - - options = getOptions(options) - - if (start_ === null || start_ === undefined - || end_ === null || end_ === undefined || 'function' !== typeof callback) - return readError(this, 'approximateSize() requires start, end and callback arguments', callback) - - start = this._codec.encodeKey(start_, options) - end = this._codec.encodeKey(end_, options) - - this.db.approximateSize(start, end, function (err, size) { - if (err) { - return dispatchError(self, new OpenError(err), callback) - } else if (callback) { - callback(null, size) - } - }) -}, 'db.approximateSize() is deprecated. Use db.db.approximateSize() instead') - -LevelUP.prototype.readStream = -LevelUP.prototype.createReadStream = function (options) { - options = extend( {keys: true, values: true}, this.options, options) - - options.keyEncoding = options.keyEncoding - options.valueEncoding = options.valueEncoding - - options = this._codec.encodeLtgt(options); - options.keyAsBuffer = this._codec.keyAsBuffer(options) - options.valueAsBuffer = this._codec.valueAsBuffer(options) - - if ('number' !== typeof options.limit) - options.limit = -1 - - return new IteratorStream(this.db.iterator(options), extend(options, { - decoder: this._codec.createStreamDecoder(options) - })) -} - -LevelUP.prototype.keyStream = -LevelUP.prototype.createKeyStream = function (options) { - return this.createReadStream(extend(options, { keys: true, values: false })) -} - -LevelUP.prototype.valueStream = -LevelUP.prototype.createValueStream = function (options) { - return this.createReadStream(extend(options, { keys: false, values: true })) -} - -LevelUP.prototype.toString = function () { - return 'LevelUP' -} - -function utilStatic (name) { - return function (location, callback) { - getLevelDOWN()[name](location, callback || function () {}) - } -} - -module.exports = LevelUP -module.exports.errors = require('level-errors') -module.exports.destroy = deprecate( - utilStatic('destroy') - , 'levelup.destroy() is deprecated. Use leveldown.destroy() instead' -) -module.exports.repair = deprecate( - utilStatic('repair') - , 'levelup.repair() is deprecated. Use leveldown.repair() instead' -) - - -}).call(this,require('_process')) -},{"./batch":59,"./leveldown":154,"./util":61,"_process":206,"deferred-leveldown":10,"events":169,"level-codec":39,"level-errors":41,"level-iterator-stream":42,"prr":70,"util":229,"xtend":92}],61:[function(require,module,exports){ -/* Copyright (c) 2012-2016 LevelUP contributors - * See list at - * MIT License - * - */ - -var extend = require('xtend') - , defaultOptions = { - createIfMissing : true - , errorIfExists : false - , keyEncoding : 'utf8' - , valueEncoding : 'utf8' - , compression : true - } - -function getOptions (options) { - if (typeof options == 'string') - options = { valueEncoding: options } - if (typeof options != 'object') - options = {} - return options -} - -function dispatchError (db, error, callback) { - typeof callback == 'function' ? callback(error) : db.emit('error', error) -} - -function isDefined (v) { - return typeof v !== 'undefined' -} - -module.exports = { - defaultOptions : defaultOptions - , getOptions : getOptions - , dispatchError : dispatchError - , isDefined : isDefined -} - -},{"xtend":92}],62:[function(require,module,exports){ -(function (global){ -/** - * Lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright JS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** `Object#toString` result references. */ -var 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]'; - -var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = -typedArrayTags[errorTag] = typedArrayTags[funcTag] = -typedArrayTags[mapTag] = typedArrayTags[numberTag] = -typedArrayTags[objectTag] = typedArrayTags[regexpTag] = -typedArrayTags[setTag] = typedArrayTags[stringTag] = -typedArrayTags[weakMapTag] = false; - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; - -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports && freeGlobal.process; - -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} -}()); - -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - -/** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ -function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; -} - -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} - -/** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ -function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; -} - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} - -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} - -/** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); -} - -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; -} - -/** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ -function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; -} - -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} - -/** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ -function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; -} - -/** Used for built-in method references. */ -var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; - -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; - -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); - -/** Built-in value references. */ -var Buffer = moduleExports ? root.Buffer : undefined, - Symbol = root.Symbol, - Uint8Array = root.Uint8Array, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - symToStringTag = Symbol ? Symbol.toStringTag : undefined; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeKeys = overArg(Object.keys, Object); - -/* Built-in method references that are verified to be native. */ -var DataView = getNative(root, 'DataView'), - Map = getNative(root, 'Map'), - Promise = getNative(root, 'Promise'), - Set = getNative(root, 'Set'), - WeakMap = getNative(root, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - -/** Used to detect maps, sets, and weakmaps. */ -var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; -} - -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; -} - -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; -} - -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); -} - -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; -} - -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; - -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; - this.size = 0; -} - -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; -} - -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; -} - -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; -} - -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} - -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; - -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; -} - -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; -} - -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); -} - -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); +// Serialize an Error object +// (Core error properties are enumerable in node 0.4, not in 0.6). +var errSerializer = Logger.stdSerializers.err = function (err) { + if (!err || !err.stack) + return err; + var obj = { + message: err.message, + name: err.name, + stack: getFullErrorStack(err), + code: err.code, + signal: err.signal + } + return obj; +}; + + +// A JSON stringifier that handles cycles safely - tracks seen values in a Set. +function safeCyclesSet() { + var seen = new Set(); + return function (key, val) { + if (!val || typeof (val) !== 'object') { + return val; + } + if (seen.has(val)) { + return '[Circular]'; + } + seen.add(val); + return val; + }; } /** - * Sets the map `key` to `value`. + * A JSON stringifier that handles cycles safely - tracks seen vals in an Array. * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. + * Note: This approach has performance problems when dealing with large objects, + * see trentm/node-bunyan#445, but since this is the only option for node 0.10 + * and earlier (as Set was introduced in Node 0.12), it's used as a fallback + * when Set is not available. */ -function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; +function safeCyclesArray() { + var seen = []; + return function (key, val) { + if (!val || typeof (val) !== 'object') { + return val; + } + if (seen.indexOf(val) !== -1) { + return '[Circular]'; + } + seen.push(val); + return val; + }; } -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; - /** + * A JSON stringifier that handles cycles safely. * - * Creates an array cache object to store unique values. + * Usage: JSON.stringify(obj, safeCycles()) * - * @private - * @constructor - * @param {Array} [values] The values to cache. + * Choose the best safe cycle function from what is available - see + * trentm/node-bunyan#445. */ -function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } -} +var safeCycles = typeof (Set) !== 'undefined' ? safeCyclesSet : safeCyclesArray; /** - * Adds `value` to the array cache. + * A fast JSON.stringify that handles cycles and getter exceptions (when + * safeJsonStringify is installed). * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. + * This function attempts to use the regular JSON.stringify for speed, but on + * error (e.g. JSON cycle detection exception) it falls back to safe stringify + * handlers that can deal with cycles and/or getter exceptions. */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; +function fastAndSafeJsonStringify(rec) { + try { + return JSON.stringify(rec); + } catch (ex) { + try { + return JSON.stringify(rec, safeCycles()); + } catch (e) { + if (safeJsonStringify) { + return safeJsonStringify(rec); + } else { + var dedupKey = e.stack.split(/\n/g, 3).join('\n'); + _warn('bunyan: ERROR: Exception in ' + + '`JSON.stringify(rec)`. You can install the ' + + '"safe-json-stringify" module to have Bunyan fallback ' + + 'to safer stringification. Record:\n' + + _indent(format('%s\n%s', util.inspect(rec), e.stack)), + dedupKey); + return format('(Exception in JSON.stringify(rec): %j. ' + + 'See stderr for details.)', e.message); + } + } + } } -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); -} -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; +var RotatingFileStream = null; +if (mv) { -/** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; -} +RotatingFileStream = function RotatingFileStream(options) { + this.path = options.path; -/** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ -function stackClear() { - this.__data__ = new ListCache; - this.size = 0; -} + this.count = (options.count == null ? 10 : options.count); + assert.equal(typeof (this.count), 'number', + format('rotating-file stream "count" is not a number: %j (%s) in %j', + this.count, typeof (this.count), this)); + assert.ok(this.count >= 0, + format('rotating-file stream "count" is not >= 0: %j in %j', + this.count, this)); -/** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); + // Parse `options.period`. + if (options.period) { + // where scope is: + // h hours (at the start of the hour) + // d days (at the start of the day, i.e. just after midnight) + // w weeks (at the start of Sunday) + // m months (on the first of the month) + // y years (at the start of Jan 1st) + // with special values 'hourly' (1h), 'daily' (1d), "weekly" (1w), + // 'monthly' (1m) and 'yearly' (1y) + var period = { + 'hourly': '1h', + 'daily': '1d', + 'weekly': '1w', + 'monthly': '1m', + 'yearly': '1y' + }[options.period] || options.period; + var 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'; + } - this.size = data.size; - return result; -} + var lastModified = null; + try { + var fileInfo = fs.statSync(this.path); + lastModified = fileInfo.mtime.getTime(); + } + catch (err) { + // file doesn't exist + } + var rotateAfterOpen = false; + if (lastModified) { + var lastRotTime = this._calcRotTime(0); + if (lastModified < lastRotTime) { + rotateAfterOpen = true; + } + } -/** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function stackGet(key) { - return this.__data__.get(key); -} + // TODO: template support for backup files + // template: + // default is %P.%n + // '/var/log/archive/foo.log' -> foo.log.%n + // '/var/log/archive/foo.log.%n' + // codes: + // XXX support strftime codes (per node version of those) + // or whatever module. Pick non-colliding for extra + // codes + // %P `path` base value + // %n integer number of rotated log (1,2,3,...) + // %d datetime in YYYY-MM-DD_HH-MM-SS + // XXX what should default date format be? + // prior art? Want to avoid ':' in + // filenames (illegal on Windows for one). -/** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function stackHas(key) { - return this.__data__.has(key); -} + this.stream = fs.createWriteStream(this.path, + {flags: 'a', encoding: 'utf8'}); -/** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ -function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; + this.rotQueue = []; + this.rotating = false; + if (rotateAfterOpen) { + this._debug('rotateAfterOpen -> call rotate()'); + this.rotate(); + } else { + this._setupNextRot(); } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; } -// Add methods to `Stack`. -Stack.prototype.clear = stackClear; -Stack.prototype['delete'] = stackDelete; -Stack.prototype.get = stackGet; -Stack.prototype.has = stackHas; -Stack.prototype.set = stackSet; +util.inherits(RotatingFileStream, EventEmitter); -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; +RotatingFileStream.prototype._debug = function () { + // Set this to `true` to add debug logging. + if (false) { + if (arguments.length === 0) { + return true; + } + var args = Array.prototype.slice.call(arguments); + args[0] = '[' + (new Date().toISOString()) + ', ' + + this.path + '] ' + args[0]; + console.log.apply(this, args); + } else { + return false; + } +}; - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); +RotatingFileStream.prototype._setupNextRot = function () { + this.rotAt = this._calcRotTime(1); + this._setRotationTimer(); +} + +RotatingFileStream.prototype._setRotationTimer = function () { + var self = this; + var delay = this.rotAt - Date.now(); + // Cap timeout to Node's max setTimeout, see + // . + var TIMEOUT_MAX = 2147483647; // 2^31-1 + if (delay > TIMEOUT_MAX) { + delay = TIMEOUT_MAX; + } + this.timeout = setTimeout( + function () { + self._debug('_setRotationTimer timeout -> call rotate()'); + self.rotate(); + }, + delay); + if (typeof (this.timeout.unref) === 'function') { + this.timeout.unref(); } - } - return result; } -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; +RotatingFileStream.prototype._calcRotTime = +function _calcRotTime(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': + // Hidden millisecond period for debugging. + if (this.rotAt) { + rotAt = this.rotAt + this.periodNum * periodOffset; + } else { + rotAt = Date.now() + this.periodNum * periodOffset; + } + break; + case 'h': + if (this.rotAt) { + rotAt = this.rotAt + this.periodNum * 60 * 60 * 1000 * periodOffset; + } else { + // First time: top of the next hour. + rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), + d.getUTCDate(), d.getUTCHours() + periodOffset); + } + break; + case 'd': + if (this.rotAt) { + rotAt = this.rotAt + this.periodNum * 24 * 60 * 60 * 1000 + * periodOffset; + } else { + // First time: start of tomorrow (i.e. at the coming midnight) UTC. + rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), + d.getUTCDate() + periodOffset); + } + break; + case 'w': + // Currently, always on Sunday morning at 00:00:00 (UTC). + if (this.rotAt) { + rotAt = this.rotAt + this.periodNum * 7 * 24 * 60 * 60 * 1000 + * periodOffset; + } else { + // First time: this coming Sunday. + var dayOffset = (7 - d.getUTCDay()); + if (periodOffset < 1) { + dayOffset = -d.getUTCDay(); + } + if (periodOffset > 1 || periodOffset < -1) { + dayOffset += 7 * periodOffset; + } + rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), + d.getUTCDate() + dayOffset); + } + break; + case 'm': + if (this.rotAt) { + rotAt = Date.UTC(d.getUTCFullYear(), + d.getUTCMonth() + this.periodNum * periodOffset, 1); + } else { + // First time: the start of the next month. + rotAt = Date.UTC(d.getUTCFullYear(), + d.getUTCMonth() + periodOffset, 1); + } + break; + case 'y': + if (this.rotAt) { + rotAt = Date.UTC(d.getUTCFullYear() + this.periodNum * periodOffset, + 0, 1); + } else { + // First time: the start of the next year. + rotAt = Date.UTC(d.getUTCFullYear() + periodOffset, 0, 1); + } + break; + default: + assert.fail(format('invalid period scope: "%s"', this.periodScope)); } - } - return -1; -} - -/** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ -function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); -} -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); -} - -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; -} + 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)/1000/60, + (rotAt-now)/1000/60/60); + } + return rotAt; +}; -/** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ -function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); -} +RotatingFileStream.prototype.rotate = function rotate() { + // XXX What about shutdown? + var self = this; -/** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag : getTag(object), - othTag = othIsArr ? arrayTag : getTag(other); + // If rotation period is > ~25 days, we have to break into multiple + // setTimeout's. See . + if (self.rotAt && self.rotAt > Date.now()) { + return self._setRotationTimer(); + } - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; + this._debug('rotate'); + if (self.rotating) { + throw new TypeError('cannot start a rotation when already rotating'); + } + self.rotating = true; - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; + self.stream.end(); // XXX can do moves sync after this? test at high rate - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; + function del() { + var toDel = self.path + '.' + String(n - 1); + if (n === 0) { + toDel = self.path; + } + n -= 1; + self._debug(' rm %s', toDel); + fs.unlink(toDel, function (delErr) { + //XXX handle err other than not exists + moves(); + }); } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + function moves() { + if (self.count === 0 || n < 0) { + return finish(); + } + var before = self.path; + var after = self.path + '.' + String(n); + if (n > 0) { + before += '.' + String(n - 1); + } + n -= 1; + fs.exists(before, function (exists) { + if (!exists) { + moves(); + } else { + self._debug(' mv %s %s', before, after); + mv(before, after, function (mvErr) { + if (mvErr) { + self.emit('error', mvErr); + finish(); // XXX finish here? + } else { + moves(); + } + }); + } + }) } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); -} -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); -} + function finish() { + self._debug(' open %s', self.path); + self.stream = fs.createWriteStream(self.path, + {flags: 'a', encoding: 'utf8'}); + var q = self.rotQueue, len = q.length; + for (var i = 0; i < len; i++) { + self.stream.write(q[i]); + } + self.rotQueue = []; + self.rotating = false; + self.emit('drain'); + self._setupNextRot(); + } -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; -} + var n = this.count; + del(); +}; -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); +RotatingFileStream.prototype.write = function write(s) { + if (this.rotating) { + this.rotQueue.push(s); + return false; + } else { + return this.stream.write(s); } - } - return result; -} +}; -/** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ -function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; +RotatingFileStream.prototype.end = function end(s) { + this.stream.end(); +}; - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; +RotatingFileStream.prototype.destroy = function destroy(s) { + this.stream.destroy(); +}; - stack.set(array, other); - stack.set(other, array); +RotatingFileStream.prototype.destroySoon = function destroySoon(s) { + this.stream.destroySoon(); +}; + +} /* if (mv) */ - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; -} /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. + * RingBuffer is a Writable Stream that just stores the last N records in + * memory. * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * @param options {Object}, with the following fields: * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + * - limit: number of records to keep in memory */ -function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; +function RingBuffer(options) { + this.limit = options && options.limit ? options.limit : 100; + this.writable = true; + this.records = []; + EventEmitter.call(this); +} - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; +util.inherits(RingBuffer, EventEmitter); - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); +RingBuffer.prototype.write = function (record) { + if (!this.writable) + throw (new Error('RingBuffer has been ended already')); - case errorTag: - return object.name == other.name && object.message == other.message; + this.records.push(record); - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); + if (this.records.length > this.limit) + this.records.shift(); - case mapTag: - var convert = mapToArray; + return (true); +}; - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); +RingBuffer.prototype.end = function () { + if (arguments.length > 0) + this.write.apply(this, Array.prototype.slice.call(arguments)); + this.writable = false; +}; - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; +RingBuffer.prototype.destroy = function () { + this.writable = false; + this.emit('close'); +}; - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; +RingBuffer.prototype.destroySoon = function () { + this.destroy(); +}; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; -} -/** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; +//---- Exports - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); +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 createLogger(options) { + return new Logger(options); +}; + +module.exports.RingBuffer = RingBuffer; +module.exports.RotatingFileStream = RotatingFileStream; + +// Useful for custom `type == 'raw'` streams that may do JSON stringification +// of log records themselves. Usage: +// var str = JSON.stringify(rec, bunyan.safeCycles()); +module.exports.safeCycles = safeCycles; + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process')) +},{"../../is-buffer/index.js":42,"_process":85,"assert":4,"events":37,"fs":8,"os":83,"safe-json-stringify":103,"stream":147,"util":157}],11:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; +function isBoolean(arg) { + return typeof arg === 'boolean'; } +exports.isBoolean = isBoolean; -/** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ -function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); +function isNull(arg) { + return arg === null; } +exports.isNull = isNull; -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; +function isNullOrUndefined(arg) { + return arg == null; } +exports.isNullOrUndefined = isNullOrUndefined; -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; +function isNumber(arg) { + return typeof arg === 'number'; } +exports.isNumber = isNumber; -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; +function isUndefined(arg) { + return arg === void 0; } +exports.isUndefined = isUndefined; -/** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ -var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); -}; +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; -/** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -var getTag = baseGetTag; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; -// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. -if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; - 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; - }; +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); } +exports.isError = isError; -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); +function isFunction(arg) { + return typeof arg === 'function'; } +exports.isFunction = isFunction; -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; } +exports.isPrimitive = isPrimitive; -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":42}],12:[function(require,module,exports){ +var util = require('util') + , AbstractIterator = require('abstract-leveldown').AbstractIterator + + +function DeferredIterator (options) { + AbstractIterator.call(this, options) + + this._options = options + this._iterator = null + this._operations = [] } -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; +util.inherits(DeferredIterator, AbstractIterator) - return value === proto; +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) + }) } -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString.call(value); +DeferredIterator.prototype._operation = function (method, args) { + if (this._iterator) + return this._iterator[method].apply(this._iterator, args) + this._operations.push({ method: method, args: args }) } -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} +'next end'.split(' ').forEach(function (m) { + DeferredIterator.prototype['_' + m] = function () { + this._operation(m, arguments) } - return ''; +}) + +module.exports = DeferredIterator; + +},{"abstract-leveldown":17,"util":157}],13:[function(require,module,exports){ +(function (Buffer,process){ +var util = require('util') + , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN + , DeferredIterator = require('./deferred-iterator') + +function DeferredLevelDOWN (location) { + AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '') // optional location, who cares? + this._db = undefined + this._operations = [] + this._iterators = [] } -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); +util.inherits(DeferredLevelDOWN, AbstractLevelDOWN) + +// called by LevelUP when we have a real DB to take its place +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) + }) } -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; +DeferredLevelDOWN.prototype._open = function (options, callback) { + return process.nextTick(callback) +} -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +// queue a new deferred operation +DeferredLevelDOWN.prototype._operation = function (method, args) { + if (this._db) + return this._db[method].apply(this._db, args) + this._operations.push({ method: method, args: args }) +} -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); +// deferrables +'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) } -/** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ -var isBuffer = nativeIsBuffer || stubFalse; +DeferredLevelDOWN.prototype._iterator = function (options) { + if (this._db) + return this._db.iterator.apply(this._db, arguments) + var it = new DeferredIterator(options) + this._iterators.push(it) + return it +} -/** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ -function isEqual(value, other) { - return baseIsEqual(value, other); +module.exports = DeferredLevelDOWN +module.exports.DeferredIterator = DeferredIterator + +}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process')) +},{"../is-buffer/index.js":42,"./deferred-iterator":12,"_process":85,"abstract-leveldown":17,"util":157}],14:[function(require,module,exports){ +(function (process){ +/* Copyright (c) 2017 Rod Vagg, MIT License */ + +function AbstractChainedBatch (db) { + this._db = db + this._operations = [] + this._written = false } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +AbstractChainedBatch.prototype._serializeKey = function (key) { + return this._db._serializeKey(key) } -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +AbstractChainedBatch.prototype._serializeValue = function (value) { + return this._db._serializeValue(value) } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); +AbstractChainedBatch.prototype._checkWritten = function () { + if (this._written) + throw new Error('write() already called on this batch') } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; +AbstractChainedBatch.prototype.put = function (key, value) { + this._checkWritten() + + var err = this._db._checkKey(key, 'key', this._db._isBuffer) + if (err) + throw err + + key = this._serializeKey(key) + value = this._serializeValue(value) + + if (typeof this._put == 'function' ) + this._put(key, value) + else + this._operations.push({ type: 'put', key: key, value: value }) + + return this } -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; +AbstractChainedBatch.prototype.del = function (key) { + this._checkWritten() -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + var err = this._db._checkKey(key, 'key', this._db._isBuffer) + if (err) throw err + + key = this._serializeKey(key) + + if (typeof this._del == 'function' ) + this._del(key) + else + this._operations.push({ type: 'del', key: key }) + + return this } -/** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ -function stubArray() { - return []; +AbstractChainedBatch.prototype.clear = function () { + this._checkWritten() + + this._operations = [] + + if (typeof this._clear == 'function' ) + this._clear() + + return this } -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ -function stubFalse() { - return false; +AbstractChainedBatch.prototype.write = function (options, callback) { + this._checkWritten() + + if (typeof options == 'function') + callback = options + if (typeof callback != 'function') + throw new Error('write() requires a callback argument') + if (typeof options != 'object') + options = {} + + this._written = true + + if (typeof this._write == 'function' ) + return this._write(callback) + + if (typeof this._db._batch == 'function') + return this._db._batch(this._operations, options, callback) + + process.nextTick(callback) } -module.exports = isEqual; +module.exports = AbstractChainedBatch -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],63:[function(require,module,exports){ -(function (Buffer){ +}).call(this,require('_process')) +},{"_process":85}],15:[function(require,module,exports){ +(function (process){ +/* Copyright (c) 2017 Rod Vagg, MIT License */ -exports.compare = function (a, b) { +function AbstractIterator (db) { + this.db = db + this._ended = false + this._nexting = false +} - if(Buffer.isBuffer(a)) { - var l = Math.min(a.length, b.length) - for(var i = 0; i < l; i++) { - var cmp = a[i] - b[i] - if(cmp) return cmp - } - return a.length - b.length +AbstractIterator.prototype.next = function (callback) { + var self = this + + if (typeof callback != 'function') + throw new Error('next() requires a callback argument') + + if (self._ended) + return callback(new Error('cannot call next() after end()')) + if (self._nexting) + return callback(new Error('cannot call next() before previous next() has completed')) + + self._nexting = true + if (typeof self._next == 'function') { + return self._next(function () { + self._nexting = false + callback.apply(null, arguments) + }) } - return a < b ? -1 : a > b ? 1 : 0 + process.nextTick(function () { + self._nexting = false + callback() + }) } -function has(obj, key) { - return Object.hasOwnProperty.call(obj, key) -} +AbstractIterator.prototype.end = function (callback) { + if (typeof callback != 'function') + throw new Error('end() requires a callback argument') -// to be compatible with the current abstract-leveldown tests -// nullish or empty strings. -// I could use !!val but I want to permit numbers and booleans, -// if possible. + if (this._ended) + return callback(new Error('end() already called on iterator')) -function isDef (val) { - return val !== undefined && val !== '' -} + this._ended = true -function has (range, name) { - return Object.hasOwnProperty.call(range, name) -} + if (typeof this._end == 'function') + return this._end(callback) -function hasKey(range, name) { - return Object.hasOwnProperty.call(range, name) && name + process.nextTick(callback) } -var lowerBoundKey = exports.lowerBoundKey = function (range) { - return ( - hasKey(range, 'gt') - || hasKey(range, 'gte') - || hasKey(range, 'min') - || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start')) - || undefined - ) -} +module.exports = AbstractIterator -var lowerBound = exports.lowerBound = function (range, def) { - var k = lowerBoundKey(range) - return k ? range[k] : def -} +}).call(this,require('_process')) +},{"_process":85}],16:[function(require,module,exports){ +(function (Buffer,process){ +/* Copyright (c) 2017 Rod Vagg, MIT License */ -var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) { - return has(range, 'gt') ? false : true +var xtend = require('xtend') + , AbstractIterator = require('./abstract-iterator') + , AbstractChainedBatch = require('./abstract-chained-batch') + +function AbstractLevelDOWN (location) { + if (!arguments.length || location === undefined) + throw new Error('constructor requires at least a location argument') + + if (typeof location != 'string') + throw new Error('constructor requires a location string argument') + + this.location = location + this.status = 'new' } -var upperBoundInclusive = exports.upperBoundInclusive = - function (range) { - return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true - } +AbstractLevelDOWN.prototype.open = function (options, callback) { + var self = this + , oldStatus = this.status -var lowerBoundExclusive = exports.lowerBoundExclusive = - function (range) { - return !lowerBoundInclusive(range) - } + if (typeof options == 'function') + callback = options -var upperBoundExclusive = exports.upperBoundExclusive = - function (range) { - return !upperBoundInclusive(range) - } + if (typeof callback != 'function') + throw new Error('open() requires a callback argument') -var upperBoundKey = exports.upperBoundKey = function (range) { - return ( - hasKey(range, 'lt') - || hasKey(range, 'lte') - || hasKey(range, 'max') - || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end')) - || undefined - ) -} + if (typeof options != 'object') + options = {} -var upperBound = exports.upperBound = function (range, def) { - var k = upperBoundKey(range) - return k ? range[k] : def -} + options.createIfMissing = options.createIfMissing != false + options.errorIfExists = !!options.errorIfExists -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) - ) + if (typeof this._open == 'function') { + this.status = 'opening' + this._open(options, function (err) { + if (err) { + self.status = oldStatus + return callback(err) + } + self.status = 'open' + callback() + }) + } else { + this.status = 'open' + process.nextTick(callback) + } } -function id (e) { return e } +AbstractLevelDOWN.prototype.close = function (callback) { + var self = this + , oldStatus = this.status -exports.toLtgt = function (range, _range, map, lower, upper) { - _range = _range || {} - map = map || id - var defaults = arguments.length > 3 - var lb = exports.lowerBoundKey(range) - var ub = exports.upperBoundKey(range) - if(lb) { - if(lb === 'gt') _range.gt = map(range.gt, false) - else _range.gte = map(range[lb], false) - } - else if(defaults) - _range.gte = map(lower, false) + if (typeof callback != 'function') + throw new Error('close() requires a callback argument') - if(ub) { - if(ub === 'lt') _range.lt = map(range.lt, true) - else _range.lte = map(range[ub], true) + if (typeof this._close == 'function') { + this.status = 'closing' + this._close(function (err) { + if (err) { + self.status = oldStatus + return callback(err) + } + self.status = 'closed' + callback() + }) + } else { + this.status = 'closed' + process.nextTick(callback) } - else if(defaults) - _range.lte = map(upper, true) +} - if(range.reverse != null) - _range.reverse = !!range.reverse +AbstractLevelDOWN.prototype.get = function (key, options, callback) { + var err - //if range was used mutably - //(in level-sublevel it's part of an options object - //that has more properties on it.) - if(has(_range, 'max')) delete _range.max - if(has(_range, 'min')) delete _range.min - if(has(_range, 'start')) delete _range.start - if(has(_range, 'end')) delete _range.end + if (typeof options == 'function') + callback = options - return _range -} + if (typeof callback != 'function') + throw new Error('get() requires a callback argument') -exports.contains = function (range, key, compare) { - compare = compare || exports.compare + if (err = this._checkKey(key, 'key')) + return callback(err) - var lb = lowerBound(range) - if(isDef(lb)) { - var cmp = compare(key, lb) - if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range))) - return false - } + key = this._serializeKey(key) - var ub = upperBound(range) - if(isDef(ub)) { - var cmp = compare(key, ub) - if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range)) - return false - } + if (typeof options != 'object') + options = {} - return true -} + options.asBuffer = options.asBuffer != false -exports.filter = function (range, compare) { - return function (key) { - return exports.contains(range, key, compare) - } + if (typeof this._get == 'function') + return this._get(key, options, callback) + + process.nextTick(function () { callback(new Error('NotFound')) }) } +AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { + var err + if (typeof options == 'function') + callback = options -}).call(this,{"isBuffer":require("../../../search-index/node_modules/is-buffer/index.js")}) -},{"../../../search-index/node_modules/is-buffer/index.js":173}],64:[function(require,module,exports){ -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; + if (typeof callback != 'function') + throw new Error('put() requires a callback argument') -var isFunction = function (fn) { - var isFunc = (typeof fn === 'function' && !(fn instanceof RegExp)) || toString.call(fn) === '[object Function]'; - if (!isFunc && typeof window !== 'undefined') { - isFunc = fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt; - } - return isFunc; -}; + if (err = this._checkKey(key, 'key')) + return callback(err) -module.exports = function forEach(obj, fn) { - if (!isFunction(fn)) { - throw new TypeError('iterator must be a function'); - } - var i, k, - isString = typeof obj === 'string', - l = obj.length, - context = arguments.length > 2 ? arguments[2] : null; - if (l === +l) { - for (i = 0; i < l; i++) { - if (context === null) { - fn(isString ? obj.charAt(i) : obj[i], i, obj); - } else { - fn.call(context, isString ? obj.charAt(i) : obj[i], i, obj); - } - } - } else { - for (k in obj) { - if (hasOwn.call(obj, k)) { - if (context === null) { - fn(obj[k], k, obj); - } else { - fn.call(context, obj[k], k, obj); - } - } - } - } -}; + key = this._serializeKey(key) + value = this._serializeValue(value) + if (typeof options != 'object') + options = {} -},{}],65:[function(require,module,exports){ -module.exports = Object.keys || require('./shim'); + if (typeof this._put == 'function') + return this._put(key, value, options, callback) + process.nextTick(callback) +} -},{"./shim":67}],66:[function(require,module,exports){ -var toString = Object.prototype.toString; +AbstractLevelDOWN.prototype.del = function (key, options, callback) { + var err -module.exports = function isArguments(value) { - var str = toString.call(value); - var isArguments = str === '[object Arguments]'; - if (!isArguments) { - isArguments = str !== '[object Array]' - && value !== null - && typeof value === 'object' - && typeof value.length === 'number' - && value.length >= 0 - && toString.call(value.callee) === '[object Function]'; - } - return isArguments; -}; + if (typeof options == 'function') + callback = options + if (typeof callback != 'function') + throw new Error('del() requires a callback argument') -},{}],67:[function(require,module,exports){ -(function () { - "use strict"; + if (err = this._checkKey(key, 'key')) + return callback(err) - // modified from https://github.com/kriskowal/es5-shim - var 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; + key = this._serializeKey(key) - keysShim = function keys(object) { - var isObject = object !== null && typeof object === 'object', - isFunction = toString.call(object) === '[object Function]', - isArguments = isArgs(object), - theKeys = []; + if (typeof options != 'object') + options = {} - if (!isObject && !isFunction && !isArguments) { - throw new TypeError("Object.keys called on a non-object"); - } + if (typeof this._del == 'function') + return this._del(key, options, callback) - if (isArguments) { - forEach(object, function (value) { - theKeys.push(value); - }); - } else { - var name, - skipProto = hasProtoEnumBug && isFunction; + process.nextTick(callback) +} - for (name in object) { - if (!(skipProto && name === 'prototype') && has.call(object, name)) { - theKeys.push(name); - } - } - } +AbstractLevelDOWN.prototype.batch = function (array, options, callback) { + if (!arguments.length) + return this._chainedBatch() - if (hasDontEnumBug) { - var ctor = object.constructor, - skipConstructor = ctor && ctor.prototype === object; + if (typeof options == 'function') + callback = options - forEach(dontEnums, function (dontEnum) { - if (!(skipConstructor && dontEnum === 'constructor') && has.call(object, dontEnum)) { - theKeys.push(dontEnum); - } - }); - } - return theKeys; - }; + if (typeof array == 'function') + callback = array - module.exports = keysShim; -}()); + if (typeof callback != 'function') + throw new Error('batch(array) requires a callback argument') + if (!Array.isArray(array)) + return callback(new Error('batch(array) requires an array argument')) -},{"./foreach":64,"./isArguments":66}],68:[function(require,module,exports){ -var wrappy = require('wrappy') -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + if (!options || typeof options != 'object') + options = {} -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) + var i = 0 + , l = array.length + , e + , err - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) + for (; i < l; i++) { + e = array[i] + if (typeof e != 'object') + continue -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} + if (err = this._checkKey(e.type, 'type')) + return callback(err) -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) + if (err = this._checkKey(e.key, 'key')) + return callback(err) } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} -},{"wrappy":91}],69:[function(require,module,exports){ -(function (process){ -'use strict'; + if (typeof this._batch == 'function') + return this._batch(array, options, callback) -if (!process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = nextTick; -} else { - module.exports = process.nextTick; + process.nextTick(callback) } -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); +//TODO: remove from here, not a necessary primitive +AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) { + if ( start == null + || end == null + || typeof start == 'function' + || typeof end == 'function') { + throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') } -} -}).call(this,require('_process')) -},{"_process":206}],70:[function(require,module,exports){ -arguments[4][33][0].apply(exports,arguments) -},{"dup":33}],71:[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 + if (typeof callback != 'function') + throw new Error('approximateSize() requires a callback argument') -var noop = function () {} + start = this._serializeKey(start) + end = this._serializeKey(end) -var isFn = function (fn) { - return typeof fn === 'function' -} + if (typeof this._approximateSize == 'function') + return this._approximateSize(start, end, callback) -var isFS = function (stream) { - if (!fs) return false // browser - return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) + process.nextTick(function () { + callback(null, 0) + }) } -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) -} +AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { + var self = this -var destroyer = function (stream, reading, writing, callback) { - callback = once(callback) + options = xtend(options) - var closed = false - stream.on('close', function () { - closed = true + ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) { + if (options[o] && self._isBuffer(options[o]) && options[o].length === 0) + delete options[o] }) - eos(stream, {readable: reading, writable: writing}, function (err) { - if (err) return callback(err) - closed = true - callback() - }) + options.reverse = !!options.reverse + options.keys = options.keys != false + options.values = options.values != false + options.limit = 'limit' in options ? options.limit : -1 + options.keyAsBuffer = options.keyAsBuffer != false + options.valueAsBuffer = options.valueAsBuffer != false - var destroyed = false - return function (err) { - if (closed) return - if (destroyed) return - destroyed = true + return options +} - if (isFS(stream)) return stream.close() // use close for fs streams to avoid fd leaks - if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want +AbstractLevelDOWN.prototype.iterator = function (options) { + if (typeof options != 'object') + options = {} - if (isFn(stream.destroy)) return stream.destroy() + options = this._setupIteratorOptions(options) - callback(err || new Error('stream was destroyed')) - } -} + if (typeof this._iterator == 'function') + return this._iterator(options) -var call = function (fn) { - fn() + return new AbstractIterator(this) } -var pipe = function (from, to) { - return from.pipe(to) +AbstractLevelDOWN.prototype._chainedBatch = function () { + return new AbstractChainedBatch(this) } -var pump = function () { - var streams = Array.prototype.slice.call(arguments) - var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop - - if (Array.isArray(streams[0])) streams = streams[0] - if (streams.length < 2) throw new Error('pump requires two streams per minimum') +AbstractLevelDOWN.prototype._isBuffer = function (obj) { + return Buffer.isBuffer(obj) +} - var error - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1 - var writing = i > 0 - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err - if (err) destroys.forEach(call) - if (reading) return - destroys.forEach(call) - callback(error) - }) - }) +AbstractLevelDOWN.prototype._serializeKey = function (key) { + return this._isBuffer(key) + ? key + : String(key) +} - return streams.reduce(pipe) +AbstractLevelDOWN.prototype._serializeValue = function (value) { + if (value == null) return '' + return this._isBuffer(value) || process.browser ? value : String(value) } -module.exports = pump +AbstractLevelDOWN.prototype._checkKey = function (obj, type) { + if (obj === null || obj === undefined) + return new Error(type + ' cannot be `null` or `undefined`') -},{"end-of-stream":72,"fs":154,"once":68}],72:[function(require,module,exports){ -var once = require('once'); + if (this._isBuffer(obj) && obj.length === 0) + return new Error(type + ' cannot be an empty Buffer') + else if (String(obj) === '') + return new Error(type + ' cannot be an empty String') +} -var noop = function() {}; +module.exports = AbstractLevelDOWN -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; +}).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) +},{"../../../is-buffer/index.js":42,"./abstract-chained-batch":14,"./abstract-iterator":15,"_process":85,"xtend":159}],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') -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 -}; +},{"./abstract-chained-batch":14,"./abstract-iterator":15,"./abstract-leveldown":16,"./is-leveldown":18}],18:[function(require,module,exports){ +var AbstractLevelDOWN = require('./abstract-leveldown') -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; +function isLevelDOWN (db) { + if (!db || typeof db !== 'object') + return false + return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) { + // TODO remove approximateSize check when method is gone + return name[0] != '_' && name != 'approximateSize' + }).every(function (name) { + return typeof db[name] == 'function' + }) +} - callback = once(callback || noop); +module.exports = isLevelDOWN - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); +},{"./abstract-leveldown":16}],19:[function(require,module,exports){ +const pumpify = require('pumpify') +const stopwords = [] - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; +const CalculateTermFrequency = exports.CalculateTermFrequency = + require('./pipeline/CalculateTermFrequency.js') - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; +const CharacterNormaliser = exports.CharacterNormaliser = + require('./pipeline/CharacterNormaliser.js') - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; +const CreateCompositeVector = exports.CreateCompositeVector = + require('./pipeline/CreateCompositeVector.js') - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; +const CreateSortVectors = exports.CreateSortVectors = + require('./pipeline/CreateSortVectors.js') - var onclose = function() { - if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); - }; +const CreateStoredDocument = exports.CreateStoredDocument = + require('./pipeline/CreateStoredDocument.js') - var onrequest = function() { - stream.req.on('finish', onfinish); - }; +const FieldedSearch = exports.FieldedSearch = + require('./pipeline/FieldedSearch.js') - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } +const IngestDoc = exports.IngestDoc = + require('./pipeline/IngestDoc.js') - if (isChildProcess(stream)) stream.on('exit', onexit); +const LowCase = exports.LowCase = + require('./pipeline/LowCase.js') - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', callback); - stream.on('close', onclose); +const NormaliseFields = exports.NormaliseFields = + require('./pipeline/NormaliseFields.js') - return function() { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (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); - }; -}; +const RemoveStopWords = exports.RemoveStopWords = + require('./pipeline/RemoveStopWords.js') -module.exports = eos; +const Spy = exports.Spy = require('./pipeline/Spy.js') // eslint-disable-line -},{"once":68}],73:[function(require,module,exports){ -var pump = require('pump') -var inherits = require('inherits') -var Duplexify = require('duplexify') +const Tokeniser = exports.Tokeniser = + require('./pipeline/Tokeniser.js') -var toArray = function(args) { - if (!args.length) return [] - return Array.isArray(args[0]) ? args[0] : Array.prototype.slice.call(args) +exports.pipeline = function (options) { + options = Object.assign({}, { + separator: /[|' .,\-|(\\\n)]+/, + searchable: true, + stopwords: stopwords, + nGramLength: 1, + fieldedSearch: true + }, options) + var pl = [ + new IngestDoc(options), + new CreateStoredDocument(), + new NormaliseFields(), + new LowCase(), + new Tokeniser(), + new RemoveStopWords(), + new CharacterNormaliser(), + new CalculateTermFrequency(), + new CreateCompositeVector(), + new CreateSortVectors(), + new FieldedSearch() + ] + return pumpify.obj.apply(this, pl) } -var define = function(opts) { - var Pumpify = function() { - var streams = toArray(arguments) - if (!(this instanceof Pumpify)) return new Pumpify(streams) - Duplexify.call(this, null, null, opts) - if (streams.length) this.setPipeline(streams) - } - - inherits(Pumpify, Duplexify) +exports.customPipeline = function (pl) { + return pumpify.obj.apply(this, pl) +} - Pumpify.prototype.setPipeline = function() { - var streams = toArray(arguments) - var self = this - var ended = false - var w = streams[0] - var r = streams[streams.length-1] +},{"./pipeline/CalculateTermFrequency.js":20,"./pipeline/CharacterNormaliser.js":21,"./pipeline/CreateCompositeVector.js":22,"./pipeline/CreateSortVectors.js":23,"./pipeline/CreateStoredDocument.js":24,"./pipeline/FieldedSearch.js":25,"./pipeline/IngestDoc.js":26,"./pipeline/LowCase.js":27,"./pipeline/NormaliseFields.js":28,"./pipeline/RemoveStopWords.js":29,"./pipeline/Spy.js":30,"./pipeline/Tokeniser.js":31,"pumpify":88}],20:[function(require,module,exports){ +const tv = require('term-vector') +const tf = require('term-frequency') +const Transform = require('stream').Transform +const util = require('util') - r = r.readable ? r : null - w = w.writable ? w : null +// convert term-frequency vectors into object maps +const objectify = function (result, item) { + result[item[0].join(' ')] = item[1] + return result +} - var onclose = function() { - streams[0].emit('error', new Error('stream was destroyed')) +const CalculateTermFrequency = function (options) { + Transform.call(this, { objectMode: true }) +} +module.exports = CalculateTermFrequency +util.inherits(CalculateTermFrequency, Transform) +CalculateTermFrequency.prototype._transform = function (doc, encoding, end) { + var options = Object.assign({}, { + fieldOptions: {}, + nGramLength: 1, + searchable: true, + weight: 0, + wildcard: true + }, doc.options || {}) + for (var fieldName in doc.tokenised) { + var fieldOptions = Object.assign({}, { + nGramLength: options.nGramLength, + searchable: options.searchable, + weight: options.weight, + wildcard: options.wildcard + }, options.fieldOptions[fieldName]) + var field = doc.tokenised[fieldName] + if (fieldOptions.searchable) { + doc.vector[fieldName] = tf.getTermFrequency( + tv.getVector(field, fieldOptions.nGramLength), { + scheme: tf.doubleNormalization0point5, + weight: fieldOptions.weight + } + ).reduce(objectify, {}) + if (fieldOptions.wildcard === true) doc.vector[fieldName]['*'] = 1 // wildcard search } + } + this.push(doc) + return end() +} - this.on('close', onclose) - this.on('prefinish', function() { - if (!ended) self.cork() - }) - - pump(streams, function(err) { - self.removeListener('close', onclose) - if (err) return self.destroy(err) - ended = true - self.uncork() - }) +},{"stream":147,"term-frequency":150,"term-vector":151,"util":157}],21:[function(require,module,exports){ +// removes stopwords from indexed docs +const Transform = require('stream').Transform +const util = require('util') - if (this.destroyed) return onclose() - this.setWritable(w) - this.setReadable(r) +const CharacterNormaliser = function (options) { + Transform.call(this, { objectMode: true }) +} +module.exports = CharacterNormaliser +util.inherits(CharacterNormaliser, Transform) +CharacterNormaliser.prototype._transform = function (doc, encoding, end) { + var options = Object.assign({}, { + fieldOptions: {}, + normaliseCharacters: false + }, doc.options || {}) + for (var fieldName in doc.normalised) { + var fieldOptions = Object.assign({}, { + normaliseCharacters: options.normaliseCharacters + }, options.fieldOptions[fieldName]) + // normalise characters + if (fieldOptions.normaliseCharacters && (fieldName !== 'id')) { + doc.tokenised[fieldName] = + doc.tokenised[fieldName].map(function (token) { + return Array.from(token).map(function (c) { + return c.normalize('NFKD')[0] + }).join('') + }) + } } - - return Pumpify + this.push(doc) + return end() } -module.exports = define({destroy:false}) -module.exports.obj = define({destroy:false, objectMode:true, highWaterMark:16}) +},{"stream":147,"util":157}],22:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') -},{"duplexify":28,"inherits":35,"pump":71}],74:[function(require,module,exports){ -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. +const CreateCompositeVector = function (options) { + Transform.call(this, { objectMode: true }) +} +module.exports = CreateCompositeVector +util.inherits(CreateCompositeVector, Transform) +CreateCompositeVector.prototype._transform = function (doc, encoding, end) { + var options = Object.assign({}, { + fieldOptions: {}, + compositeField: true, + searchable: true + }, doc.options || {}) + if (options.compositeField === false) { + this.push(doc) + return end() + } + 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 + } + } + } + this.push(doc) + return end() +} -'use strict'; +},{"stream":147,"util":157}],23:[function(require,module,exports){ +const tf = require('term-frequency') +const tv = require('term-vector') +const Transform = require('stream').Transform +const util = require('util') -/**/ +// convert term-frequency vectors into object maps +const objectify = function (result, item) { + result[item[0]] = item[1] + return result +} -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ +const CreateSortVectors = function (options) { + Transform.call(this, { objectMode: true }) +} +module.exports = CreateSortVectors +util.inherits(CreateSortVectors, Transform) +CreateSortVectors.prototype._transform = function (doc, encoding, end) { + var options = Object.assign({}, { + fieldOptions: {}, + sortable: false + }, doc.options || {}) + for (var fieldName in doc.vector) { + var fieldOptions = Object.assign({}, { + sortable: options.sortable + }, options.fieldOptions[fieldName]) + if (fieldOptions.sortable) { + doc.vector[fieldName] = tf.getTermFrequency( + tv.getVector(doc.tokenised[fieldName]), + { scheme: tf.selfString } + ).reduce(objectify, {}) + } + } + this.push(doc) + return end() +} -module.exports = Duplex; +},{"stream":147,"term-frequency":150,"term-vector":151,"util":157}],24:[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 +const Transform = require('stream').Transform +const util = require('util') -/**/ -var processNextTick = require('process-nextick-args'); -/**/ +const CreateStoredDocument = function (options) { + Transform.call(this, { objectMode: true }) +} +module.exports = CreateStoredDocument +util.inherits(CreateStoredDocument, Transform) +CreateStoredDocument.prototype._transform = function (doc, encoding, end) { + var options = Object.assign({}, { + fieldOptions: {}, + storeable: true + }, doc.options || {}) + for (var fieldName in doc.raw) { + var fieldOptions = Object.assign({}, { + // Store a cache of this field in the index + storeable: options.storeable + }, options.fieldOptions[fieldName]) + if (fieldName === 'id') fieldOptions.storeable = true + if (fieldOptions.storeable) { + doc.stored[fieldName] = JSON.parse(JSON.stringify(doc.raw[fieldName])) + } + } + this.push(doc) + return end() +} -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ +},{"stream":147,"util":157}],25:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); +const FieldedSearch = function (options) { + Transform.call(this, { objectMode: true }) +} +module.exports = FieldedSearch +util.inherits(FieldedSearch, Transform) +FieldedSearch.prototype._transform = function (doc, encoding, end) { + var options = Object.assign({}, { + fieldOptions: {}, + fieldedSearch: true + }, doc.options || {}) + for (var fieldName in doc.vector) { + var fieldOptions = Object.assign({}, { + fieldedSearch: options.fieldedSearch + }, options.fieldOptions[fieldName]) // can this field be searched on? + if (!fieldOptions.fieldedSearch && fieldName !== '*') delete doc.vector[fieldName] + } + if (options.log) options.log.info(doc) + this.push(doc) + return end() +} -util.inherits(Duplex, Readable); +},{"stream":147,"util":157}],26:[function(require,module,exports){ +const util = require('util') +const Transform = require('stream').Transform -var keys = objectKeys(Writable.prototype); -for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +const IngestDoc = function (options) { + this.options = options + this.i = 0 + Transform.call(this, { objectMode: true }) } +module.exports = IngestDoc +util.inherits(IngestDoc, Transform) +IngestDoc.prototype._transform = function (doc, encoding, end) { -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); + var ingestedDoc = { + normalised: {}, + options: this.options, + raw: JSON.parse(JSON.stringify(doc)), + stored: {}, + tokenised: {}, + vector: {} + } - if (options && options.readable === false) this.readable = false; + // if there is no id, generate a a stringified one that is sorted + // by time (higher values more recent), so that a natural sort will + // yeild the most recent docs first + if (!doc.id) { + // TODO ++this.i should be left padded + ingestedDoc.id = Date.now() + '-' + ++this.i + } else { + ingestedDoc.id = String(doc.id) + } - if (options && options.writable === false) this.writable = false; + this.push(ingestedDoc) // should this actually be stringified? + return end() +} - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; +},{"stream":147,"util":157}],27:[function(require,module,exports){ +// insert all search tokens in lower case +const Transform = require('stream').Transform +const util = require('util') - this.once('end', onend); +const LowCase = function () { + Transform.call(this, { objectMode: true }) +} +module.exports = LowCase +util.inherits(LowCase, Transform) +LowCase.prototype._transform = function (doc, encoding, end) { + var options = this.options = Object.assign({}, { + fieldOptions: {}, + preserveCase: false + }, doc.options || {}) + for (var fieldName in doc.normalised) { + if (fieldName === 'id') continue // dont lowcase ID field + var fieldOptions = Object.assign({}, { + preserveCase: options.preserveCase + }, options.fieldOptions[fieldName]) + if (fieldOptions.preserveCase === false) { + if (Object.prototype.toString.call(doc.normalised[fieldName]) === '[object Array]') { + doc.normalised[fieldName] = doc.normalised[fieldName].map(function (token) { + return token.toLowerCase() + }) + } else { + doc.normalised[fieldName] = doc.normalised[fieldName].toLowerCase() + } + } + } + this.push(doc) + return end() } -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); -} +},{"stream":147,"util":157}],28:[function(require,module,exports){ +const util = require('util') +const Transform = require('stream').Transform -function onEndNT(self) { - self.end(); +const NormaliseFields = function () { + Transform.call(this, { objectMode: true }) } - -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); +module.exports = NormaliseFields +util.inherits(NormaliseFields, Transform) +NormaliseFields.prototype._transform = function (doc, encoding, end) { + var options = this.options = Object.assign({}, { + fieldOptions: {}, + normaliser: /[[\],{}:"]+/g + }, doc.options || {}) + for (var fieldName in doc.raw) { + var fieldOptions = Object.assign({}, { + normaliser: options.normaliser + }, options.fieldOptions[fieldName]) + if (Object.prototype.toString.call(doc.raw[fieldName]) === '[object Array]') { + doc.normalised[fieldName] = doc.raw[fieldName].map(function (item) { + // if not array of strings then stringify each non-stringy item + if (Object.prototype.toString.call(item) !== '[object String]') { + item = JSON.stringify(item) + } + return item + .replace(fieldOptions.normaliser, ' ') + .replace(/\s\s+/g, ' ') + .trim() + }) + } else if (Object.prototype.toString.call(doc.raw[fieldName]) !== '[object String]') { + // if the input object is not a string: jsonify and split on JSON + // characters + doc.normalised[fieldName] = JSON.stringify(doc.raw[fieldName]) + .replace(fieldOptions.normaliser, ' ') + .replace(/\s\s+/g, ' ') + .trim() + } else { + doc.normalised[fieldName] = doc.raw[fieldName].trim() + } } + this.push(doc) + return end() } -},{"./_stream_readable":76,"./_stream_writable":78,"core-util-is":8,"inherits":35,"process-nextick-args":69}],75:[function(require,module,exports){ -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -'use strict'; -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); +},{"stream":147,"util":157}],29:[function(require,module,exports){ +// removes stopwords from indexed docs +const Transform = require('stream').Transform +const util = require('util') - Transform.call(this, options); +const RemoveStopWords = function (options) { + Transform.call(this, { objectMode: true }) +} +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]) + // remove stopwords + doc.tokenised[fieldName] = + doc.tokenised[fieldName].filter(function (item) { + return (fieldOptions.stopwords.indexOf(item) === -1) + }).filter(function (i) { // strip out empty elements + return i + }) + } + this.push(doc) + return end() } -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":77,"core-util-is":8,"inherits":35}],76:[function(require,module,exports){ -(function (process){ -'use strict'; - -module.exports = Readable; - -/**/ -var processNextTick = require('process-nextick-args'); -/**/ - -/**/ -var isArray = require('isarray'); -/**/ - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = require('events').EventEmitter; - -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = require('./internal/streams/stream'); -/**/ +},{"stream":147,"util":157}],30:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') -/**/ -var Buffer = require('safe-buffer').Buffer; -/**/ +const Spy = function () { + Transform.call(this, { objectMode: true }) +} +module.exports = Spy +util.inherits(Spy, Transform) +Spy.prototype._transform = function (doc, encoding, end) { + console.log(JSON.stringify(doc, null, 2)) + this.push(doc) + return end() +} -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ +},{"stream":147,"util":157}],31:[function(require,module,exports){ +// split up fields in to arrays of tokens +const Transform = require('stream').Transform +const util = require('util') -/**/ -var debugUtil = require('util'); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; +const Tokeniser = function (options) { + Transform.call(this, { objectMode: true }) +} +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({}, { + // A string.split() expression to tokenize raw field input + separator: options.separator + }, options.fieldOptions[fieldName]) + // if field is already an array, simply leave it as such + if (Object.prototype.toString.call(doc.normalised[fieldName]) === '[object Array]') { + doc.tokenised[fieldName] = doc.normalised[fieldName] + } else { + doc.tokenised[fieldName] = + doc.normalised[fieldName].split(fieldOptions.separator) + } + } + this.push(doc) + return end() } -/**/ -var BufferList = require('./internal/streams/BufferList'); -var StringDecoder; +},{"stream":147,"util":157}],32:[function(require,module,exports){ +(function (process,Buffer){ +var stream = require('readable-stream') +var eos = require('end-of-stream') +var inherits = require('inherits') +var shift = require('stream-shift') -util.inherits(Readable, Stream); +var SIGNAL_FLUSH = new Buffer([0]) -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +var onuncork = function(self, fn) { + if (self._corked) self.once('uncork', fn) + else fn() +} -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +var destroyer = function(self, end) { + return function(err) { + if (err) self.destroy(err.message === 'premature close' ? null : err) + else if (end && !self._ended) self.end() } } -function ReadableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); - - options = options || {}; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; +var end = function(ws, fn) { + if (!ws) return fn() + if (ws._writableState && ws._writableState.finished) return fn() + if (ws._writableState) return ws.end(fn) + ws.end() + fn() +} - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; +var toStreams2 = function(rs) { + return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) +} - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; +var Duplexify = function(writable, readable, opts) { + if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) + stream.Duplex.call(this, opts) - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + this._writable = null + this._readable = null + this._readable2 = null - // 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 - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + this._forwardDestroy = !opts || opts.destroy !== false + this._forwardEnd = !opts || opts.end !== false + this._corked = 1 // start corked + this._ondrain = null + this._drained = false + this._forwarding = false + this._unwrite = null + this._unread = null + this._ended = 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. - this.sync = true; + this.destroyed = false - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + if (writable) this.setWritable(writable) + if (readable) this.setReadable(readable) +} - // 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'; +inherits(Duplexify, stream.Duplex) - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; +Duplexify.obj = function(writable, readable, opts) { + if (!opts) opts = {} + opts.objectMode = true + opts.highWaterMark = 16 + return new Duplexify(writable, readable, opts) +} - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; +Duplexify.prototype.cork = function() { + if (++this._corked === 1) this.emit('cork') +} - // if true, a maybeReadMore has been scheduled - this.readingMore = false; +Duplexify.prototype.uncork = function() { + if (this._corked && --this._corked === 0) this.emit('uncork') +} - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; +Duplexify.prototype.setWritable = function(writable) { + if (this._unwrite) this._unwrite() + + if (this.destroyed) { + if (writable && writable.destroy) writable.destroy() + return } -} -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); + if (writable === null || writable === false) { + this.end() + return + } - if (!(this instanceof Readable)) return new Readable(options); + var self = this + var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) - this._readableState = new ReadableState(options, this); + var ondrain = function() { + var ondrain = self._ondrain + self._ondrain = null + if (ondrain) ondrain() + } - // legacy - this.readable = true; + var clear = function() { + self._writable.removeListener('drain', ondrain) + unend() + } - if (options && typeof options.read === 'function') this._read = options.read; + if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks - Stream.call(this); + this._writable = writable + this._writable.on('drain', ondrain) + this._unwrite = clear + + this.uncork() // always uncork setWritable } -// 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; +Duplexify.prototype.setReadable = function(readable) { + if (this._unread) this._unread() - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } + if (this.destroyed) { + if (readable && readable.destroy) readable.destroy() + return } - return readableAddChunk(this, state, chunk, encoding, false); -}; + if (readable === null || readable === false) { + this.push(null) + this.resume() + return + } -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; + var self = this + var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; + var onreadable = function() { + self._forward() + } -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else 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; - } + var onend = function() { + self.push(null) + } - if (!addToFront) state.reading = false; + var clear = function() { + self._readable2.removeListener('readable', onreadable) + self._readable2.removeListener('end', onend) + unend() + } - // 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); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + this._drained = true + this._readable = readable + this._readable2 = readable._readableState ? readable : toStreams2(readable) + this._readable2.on('readable', onreadable) + this._readable2.on('end', onend) + this._unread = clear - if (state.needReadable) emitReadable(stream); - } - } + this._forward() +} - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; +Duplexify.prototype._read = function() { + this._drained = true + this._forward() +} + +Duplexify.prototype._forward = function() { + if (this._forwarding || !this._readable2 || !this._drained) return + this._forwarding = true + + var data + + while (this._drained && (data = shift(this._readable2)) !== null) { + if (this.destroyed) continue + this._drained = this.push(data) } - return needMoreData(state); + this._forwarding = false } -// 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, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +Duplexify.prototype.destroy = function(err) { + if (this.destroyed) return + this.destroyed = true + + var self = this + process.nextTick(function() { + self._destroy(err) + }) } -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; +Duplexify.prototype._destroy = function(err) { + if (err) { + var ondrain = this._ondrain + this._ondrain = null + if (ondrain) ondrain(err) + else this.emit('error', err) + } -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + if (this._forwardDestroy) { + if (this._readable && this._readable.destroy) this._readable.destroy() + if (this._writable && this._writable.destroy) this._writable.destroy() } - return n; + + this.emit('close') } -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; +Duplexify.prototype._write = function(data, enc, cb) { + if (this.destroyed) return cb() + if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) + if (data === SIGNAL_FLUSH) return this._finish(cb) + if (!this._writable) return cb() + + if (this._writable.write(data) === false) this._ondrain = cb + else cb() +} + + +Duplexify.prototype._finish = function(cb) { + var self = this + this.emit('preend') + onuncork(this, function() { + end(self._forwardEnd && self._writable, function() { + // haxx to not emit prefinish twice + if (self._writableState.prefinished === false) self._writableState.prefinished = true + self.emit('prefinish') + onuncork(self, cb) + }) + }) } -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; +Duplexify.prototype.end = function(data, enc, cb) { + if (typeof data === 'function') return this.end(null, null, data) + if (typeof enc === 'function') return this.end(data, null, enc) + this._ended = true + if (data) this.write(data) + if (!this._writableState.ending) this.write(SIGNAL_FLUSH) + return stream.Writable.prototype.end.call(this, cb) +} - if (n !== 0) state.emittedReadable = false; +module.exports = Duplexify - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":85,"buffer":9,"end-of-stream":33,"inherits":40,"readable-stream":99,"stream-shift":148}],33:[function(require,module,exports){ +var once = require('once'); - n = howMuchToRead(n, state); +var noop = function() {}; - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } + callback = once(callback || noop); - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; - if (ret !== null) this.emit('data', ret); + var onclose = function() { + if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); + }; - return ret; + var onrequest = function() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + if (isChildProcess(stream)) stream.on('exit', onexit); + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', callback); + stream.on('close', onclose); + + return function() { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (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); + }; }; -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; -} +module.exports = eos; -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; +},{"once":82}],34:[function(require,module,exports){ +var prr = require('prr') - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} +function init (type, message, cause) { + prr(this, { + type : type + , name : type + // can be passed just a 'cause' + , cause : typeof message != 'string' ? message : cause + , message : !!message && typeof message != 'string' ? message.message : message -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); - } + }, 'ewr') } -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); +// generic prototype, not intended to be actually used - helpful for `instanceof` +function CustomError (message, cause) { + Error.call(this) + if (Error.captureStackTrace) + Error.captureStackTrace(this, arguments.callee) + init.call(this, 'CustomError', message, cause) } -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); - } -} +CustomError.prototype = new Error() -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; +function createError (errno, type, proto) { + var err = function (message, cause) { + init.call(this, type, message, cause) + //TODO: the specificity here is stupid, errno should be available everywhere + if (type == 'FilesystemError') { + 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) + if (Error.captureStackTrace) + Error.captureStackTrace(this, arguments.callee) } - state.readingMore = false; + err.prototype = !!proto ? new proto() : new CustomError() + return err } -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; +module.exports = function (errno) { + var ce = function (type, proto) { + return createError(errno, type, proto) + } + return { + CustomError : CustomError + , FilesystemError : ce('FilesystemError') + , createError : ce + } +} - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; +},{"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' } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; +] - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); +module.exports.errno = {} +module.exports.code = {} - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); - } - } +all.forEach(function (error) { + module.exports.errno[error.errno] = error + module.exports.code[error.code] = error +}) - function onend() { - debug('onend'); - dest.end(); - } +module.exports.custom = require('./custom')(module.exports) +module.exports.create = module.exports.custom.createError - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); +},{"./custom":34}],36:[function(require,module,exports){ +/*! + * prr + * (c) 2013 Rod Vagg + * https://github.com/rvagg/prr + * License: MIT + */ - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - 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); +(function (name, context, definition) { + if (typeof module != 'undefined' && module.exports) + module.exports = definition() + else + context[name] = definition() +})('prr', this, function() { - cleanedUp = true; + var setProperty = typeof Object.defineProperty == 'function' + ? function (obj, key, options) { + Object.defineProperty(obj, key, options) + return obj + } + : function (obj, key, options) { // < es5 + obj[key] = options.value + return obj + } - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + , makeOptions = function (value, options) { + var oo = typeof options == 'object' + , os = !oo && typeof options == 'string' + , op = function (p) { + return oo + ? !!options[p] + : os + ? options.indexOf(p[0]) > -1 + : false + } - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; + return { + enumerable : op('enumerable') + , configurable : op('configurable') + , writable : op('writable') + , value : value + } } - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + , prr = function (obj, key, value, options) { + var k - if (!dest) dest = state.pipes; + options = makeOptions(value, options) - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } + if (typeof key == 'object') { + for (k in key) { + if (Object.hasOwnProperty.call(key, k)) { + options.value = key[k] + setProperty(obj, k, options) + } + } + return obj + } - // slow case. multiple pipe destinations. + return setProperty(obj, key, options) + } - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + return prr +}) +},{}],37:[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. - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this); - }return this; - } +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - dest.emit('unpipe', this); +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; return this; }; -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - processNextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this, state); + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; } } } - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; + handler = this._events[type]; -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); - } -} + if (isUndefined(handler)) + return false; -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); } - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; + return true; }; -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; +EventEmitter.prototype.addListener = function(type, listener) { + var m; - var self = this; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - self.push(null); - }); + if (!this._events) + this._events = {}; - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; } - }); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } } } - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); - } + return this; +}; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - return self; -}; +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -// exposed for testing purposes only. -Readable._fromList = fromList; + var fired = false; -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + function g() { + this.removeListener(type, g); - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); + if (!fired) { + fired = true; + listener.apply(this, arguments); + } } - return ret; -} + g.listener = listener; + this.on(type, g); -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} + return this; +}; -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -function endReadable(stream) { - var state = stream._readableState; + if (!this._events || !this._events[type]) + return this; - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + list = this._events[type]; + length = list.length; + position = -1; - if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); - } -} + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} + if (position < 0) + return this; -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); } - return -1; -} -}).call(this,require('_process')) -},{"./_stream_duplex":74,"./internal/streams/BufferList":79,"./internal/streams/stream":80,"_process":206,"core-util-is":8,"events":169,"inherits":35,"isarray":36,"process-nextick-args":69,"safe-buffer":82,"string_decoder/":85,"util":154}],77:[function(require,module,exports){ -// 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 -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; + return this; +}; -module.exports = Transform; +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; -var Duplex = require('./_stream_duplex'); + if (!this._events) + return this; -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } -util.inherits(Transform, Duplex); + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } -function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; + listeners = this._events[type]; - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; -} + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + return this; +}; - var cb = ts.writecb; +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; - ts.writechunk = null; - ts.writecb = null; + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; - if (data !== null && data !== undefined) stream.push(data); +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; - cb(er); +function isFunction(arg) { + return typeof arg === 'function'; +} - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } +function isNumber(arg) { + return typeof arg === 'number'; } -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - Duplex.call(this, options); +function isUndefined(arg) { + return arg === void 0; +} - this._transformState = new TransformState(this); +},{}],38:[function(require,module,exports){ +/*global window:false, self:false, define:false, module:false */ - var stream = this; +/** + * @license IDBWrapper - A cross-browser wrapper for IndexedDB + * Version 1.7.1 + * Copyright (c) 2011 - 2016 Jens Arps + * http://jensarps.de/ + * + * Licensed under the MIT (X11) license + */ - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; +(function (name, definition, global) { - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + 'use strict'; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof define === 'function') { + define(definition); + } else if (typeof module !== 'undefined' && module.exports) { + module.exports = definition(); + } else { + global[name] = definition(); + } +})('IDBStore', function () { - if (typeof options.flush === 'function') this._flush = options.flush; - } + 'use strict'; - // When the writable side finishes, then flush out anything remaining. - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er, data) { - done(stream, er, data); - });else done(stream); - }); -} + var defaultErrorHandler = function (error) { + throw error; + }; + var defaultSuccessHandler = function () { + }; -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; + var defaults = { + storeName: 'Store', + storePrefix: 'IDBWrapper-', + dbVersion: 1, + keyPath: 'id', + autoIncrement: true, + onStoreReady: function () { + }, + onError: defaultErrorHandler, + indexes: [], + implementationPreference: [ + 'indexedDB', + 'webkitIndexedDB', + 'mozIndexedDB', + 'shimIndexedDB' + ] + }; -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; + /** + * + * The IDBStore constructor + * + * @constructor + * @name IDBStore + * @version 1.7.1 + * + * @param {Object} [kwArgs] An options object used to configure the store and + * set callbacks + * @param {String} [kwArgs.storeName='Store'] The name of the store + * @param {String} [kwArgs.storePrefix='IDBWrapper-'] A prefix that is + * internally used to construct the name of the database, which will be + * kwArgs.storePrefix + kwArgs.storeName + * @param {Number} [kwArgs.dbVersion=1] The version of the store + * @param {String} [kwArgs.keyPath='id'] The key path to use. If you want to + * setup IDBWrapper to work with out-of-line keys, you need to set this to + * `null` + * @param {Boolean} [kwArgs.autoIncrement=true] If set to true, IDBStore will + * automatically make sure a unique keyPath value is present on each object + * that is stored. + * @param {Function} [kwArgs.onStoreReady] A callback to be called when the + * store is ready to be used. + * @param {Function} [kwArgs.onError=throw] A callback to be called when an + * error occurred during instantiation of the store. + * @param {Array} [kwArgs.indexes=[]] An array of indexData objects + * defining the indexes to use with the store. For every index to be used + * one indexData object needs to be passed in the array. + * An indexData object is defined as follows: + * @param {Object} [kwArgs.indexes.indexData] An object defining the index to + * use + * @param {String} kwArgs.indexes.indexData.name The name of the index + * @param {String} [kwArgs.indexes.indexData.keyPath] The key path of the index + * @param {Boolean} [kwArgs.indexes.indexData.unique] Whether the index is unique + * @param {Boolean} [kwArgs.indexes.indexData.multiEntry] Whether the index is multi entry + * @param {Array} [kwArgs.implementationPreference=['indexedDB','webkitIndexedDB','mozIndexedDB','shimIndexedDB']] An array of strings naming implementations to be used, in order or preference + * @param {Function} [onStoreReady] A callback to be called when the store + * is ready to be used. + * @example + // create a store for customers with an additional index over the + // `lastname` property. + var myCustomerStore = new IDBStore({ + dbVersion: 1, + storeName: 'customer-index', + keyPath: 'customerid', + autoIncrement: true, + onStoreReady: populateTable, + indexes: [ + { name: 'lastname', keyPath: 'lastname', unique: false, multiEntry: false } + ] + }); + * @example + // create a generic store + var myCustomerStore = new IDBStore({ + storeName: 'my-data-store', + onStoreReady: function(){ + // start working with the store. + } + }); + */ + var IDBStore = function (kwArgs, onStoreReady) { -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; + if (typeof onStoreReady == 'undefined' && typeof kwArgs == 'function') { + onStoreReady = kwArgs; + } + if (Object.prototype.toString.call(kwArgs) != '[object Object]') { + kwArgs = {}; + } -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; + for (var key in defaults) { + this[key] = typeof kwArgs[key] != 'undefined' ? kwArgs[key] : defaults[key]; + } - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; + this.dbName = this.storePrefix + this.storeName; + this.dbVersion = parseInt(this.dbVersion, 10) || 1; -function done(stream, er, data) { - if (er) return stream.emit('error', er); + onStoreReady && (this.onStoreReady = onStoreReady); - if (data !== null && data !== undefined) stream.push(data); + var env = typeof window == 'object' ? window : self; + var 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; - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + this.consts = { + 'READ_ONLY': 'readonly', + 'READ_WRITE': 'readwrite', + 'VERSION_CHANGE': 'versionchange', + 'NEXT': 'next', + 'NEXT_NO_DUPLICATE': 'nextunique', + 'PREV': 'prev', + 'PREV_NO_DUPLICATE': 'prevunique' + }; - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + this.openDB(); + }; - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + /** @lends IDBStore.prototype */ + var proto = { - return stream.push(null); -} -},{"./_stream_duplex":74,"core-util-is":8,"inherits":35}],78:[function(require,module,exports){ -(function (process){ -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. + /** + * A pointer to the IDBStore ctor + * + * @private + * @type {Function} + * @constructs + */ + constructor: IDBStore, -'use strict'; + /** + * The version of IDBStore + * + * @type {String} + */ + version: '1.7.1', -module.exports = Writable; + /** + * A reference to the IndexedDB object + * + * @type {IDBDatabase} + */ + db: null, -/**/ -var processNextTick = require('process-nextick-args'); -/**/ + /** + * The full name of the IndexedDB used by IDBStore, composed of + * this.storePrefix + this.storeName + * + * @type {String} + */ + dbName: null, -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; -/**/ + /** + * The version of the IndexedDB used by IDBStore + * + * @type {Number} + */ + dbVersion: null, -/**/ -var Duplex; -/**/ + /** + * A reference to the objectStore used by IDBStore + * + * @type {IDBObjectStore} + */ + store: null, -Writable.WritableState = WritableState; + /** + * The store name + * + * @type {String} + */ + storeName: null, -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + /** + * The prefix to prepend to the store name + * + * @type {String} + */ + storePrefix: null, -/**/ -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ + /** + * The key path + * + * @type {String} + */ + keyPath: null, -/**/ -var Stream = require('./internal/streams/stream'); -/**/ + /** + * Whether IDBStore uses autoIncrement + * + * @type {Boolean} + */ + autoIncrement: null, -/**/ -var Buffer = require('safe-buffer').Buffer; -/**/ + /** + * The indexes used by IDBStore + * + * @type {Array} + */ + indexes: null, -util.inherits(Writable, Stream); + /** + * The implemantations to try to use, in order of preference + * + * @type {Array} + */ + implementationPreference: null, -function nop() {} + /** + * The actual implementation being used + * + * @type {String} + */ + implementation: '', -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} + /** + * The callback to be called when the store is ready to be used + * + * @type {Function} + */ + onStoreReady: null, -function WritableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); + /** + * The callback to be called if an error occurred during instantiation + * of the store + * + * @type {Function} + */ + onError: null, - options = options || {}; + /** + * The internal insertID counter + * + * @type {Number} + * @private + */ + _insertIdCount: 0, - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + /** + * Opens an IndexedDB; called by the constructor. + * + * Will check if versions match and compare provided index configuration + * with existing ones, and update indexes if necessary. + * + * Will call this.onStoreReady() if everything went well and the store + * is ready to use, and this.onError() is something went wrong. + * + * @private + * + */ + openDB: function () { - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + var openRequest = this.idb.open(this.dbName, this.dbVersion); + var preventSuccessCallback = false; - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + openRequest.onerror = function (errorEvent) { - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + if (hasVersionError(errorEvent)) { + this.onError(new Error('The version number provided is lower than the existing one.')); + } else { + var error; - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + if (errorEvent.target.error) { + error = errorEvent.target.error; + } else { + var errorMessage = 'IndexedDB unknown error occurred when opening DB ' + this.dbName + ' version ' + this.dbVersion; + if ('errorCode' in errorEvent.target) { + errorMessage += ' with error code ' + errorEvent.target.errorCode; + } + error = new Error(errorMessage); + } - // 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. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + this.onError(error); + } + }.bind(this); - // 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'; + openRequest.onsuccess = function (event) { - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + if (preventSuccessCallback) { + return; + } - // a flag to see when we're in the middle of a write. - this.writing = false; + if (this.db) { + this.onStoreReady(); + return; + } + + this.db = event.target.result; + + if (typeof this.db.version == 'string') { + this.onError(new Error('The IndexedDB implementation in this browser is outdated. Please upgrade your browser.')); + return; + } - // when true all writes will be buffered until .uncork() call - this.corked = 0; + if (!this.db.objectStoreNames.contains(this.storeName)) { + // We should never ever get here. + // Lets notify the user anyway. + this.onError(new Error('Object store couldn\'t be created.')); + return; + } - // 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. - this.sync = true; + var emptyTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); + this.store = emptyTransaction.objectStore(this.storeName); - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + // check indexes + var existingIndexes = Array.prototype.slice.call(this.getIndexList()); + this.indexes.forEach(function (indexData) { + var indexName = indexData.name; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + if (!indexName) { + preventSuccessCallback = true; + this.onError(new Error('Cannot create index: No index name given.')); + return; + } - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + this.normalizeIndexData(indexData); - // the amount that is being written when _write is called. - this.writelen = 0; + if (this.hasIndex(indexName)) { + // check if it complies + var actualIndex = this.store.index(indexName); + var complies = this.indexComplies(actualIndex, indexData); + if (!complies) { + preventSuccessCallback = true; + this.onError(new Error('Cannot modify index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.')); + } - this.bufferedRequest = null; - this.lastBufferedRequest = null; + existingIndexes.splice(existingIndexes.indexOf(indexName), 1); + } else { + preventSuccessCallback = true; + this.onError(new Error('Cannot create new index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.')); + } - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + }, this); - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + if (existingIndexes.length) { + preventSuccessCallback = true; + this.onError(new Error('Cannot delete index(es) "' + existingIndexes.toString() + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.')); + } - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + preventSuccessCallback || this.onStoreReady(); + }.bind(this); - // count buffered requests - this.bufferedRequestCount = 0; + openRequest.onupgradeneeded = function (/* IDBVersionChangeEvent */ event) { - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} + this.db = event.target.result; -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; + if (this.db.objectStoreNames.contains(this.storeName)) { + this.store = event.target.transaction.objectStore(this.storeName); + } else { + var optionalParameters = {autoIncrement: this.autoIncrement}; + if (this.keyPath !== null) { + optionalParameters.keyPath = this.keyPath; + } + this.store = this.db.createObjectStore(this.storeName, optionalParameters); + } -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - } catch (_) {} -})(); + var existingIndexes = Array.prototype.slice.call(this.getIndexList()); + this.indexes.forEach(function (indexData) { + var indexName = indexData.name; -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; + if (!indexName) { + preventSuccessCallback = true; + this.onError(new Error('Cannot create index: No index name given.')); + } - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} + this.normalizeIndexData(indexData); -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); + if (this.hasIndex(indexName)) { + // check if it complies + var actualIndex = this.store.index(indexName); + var complies = this.indexComplies(actualIndex, indexData); + if (!complies) { + // index differs, need to delete and re-create + this.store.deleteIndex(indexName); + this.store.createIndex(indexName, indexData.keyPath, { + unique: indexData.unique, + multiEntry: indexData.multiEntry + }); + } - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. + existingIndexes.splice(existingIndexes.indexOf(indexName), 1); + } else { + this.store.createIndex(indexName, indexData.keyPath, { + unique: indexData.unique, + multiEntry: indexData.multiEntry + }); + } - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } + }, this); - this._writableState = new WritableState(options, this); + if (existingIndexes.length) { + existingIndexes.forEach(function (_indexName) { + this.store.deleteIndex(_indexName); + }, this); + } - // legacy. - this.writable = true; + }.bind(this); + }, - if (options) { - if (typeof options.write === 'function') this._write = options.write; + /** + * Deletes the database used for this store if the IDB implementations + * provides that functionality. + * + * @param {Function} [onSuccess] A callback that is called if deletion + * was successful. + * @param {Function} [onError] A callback that is called if deletion + * failed. + */ + 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!')); + } + }, - if (typeof options.writev === 'function') this._writev = options.writev; - } + /********************* + * data manipulation * + *********************/ - Stream.call(this); -} + /** + * Puts an object into the store. If an entry with the given id exists, + * it will be overwritten. This method has a different signature for inline + * keys and out-of-line keys; please see the examples below. + * + * @param {*} [key] The key to store. This is only needed if IDBWrapper + * is set to use out-of-line keys. For inline keys - the default scenario - + * this can be omitted. + * @param {Object} value The data object to store. + * @param {Function} [onSuccess] A callback that is called if insertion + * was successful. + * @param {Function} [onError] A callback that is called if insertion + * failed. + * @returns {IDBTransaction} The transaction used for this operation. + * @example + // Storing an object, using inline keys (the default scenario): + var myCustomer = { + customerid: 2346223, + lastname: 'Doe', + firstname: 'John' + }; + myCustomerStore.put(myCustomer, mySuccessHandler, myErrorHandler); + // Note that passing success- and error-handlers is optional. + * @example + // Storing an object, using out-of-line keys: + var myCustomer = { + lastname: 'Doe', + firstname: 'John' + }; + myCustomerStore.put(2346223, myCustomer, mySuccessHandler, myErrorHandler); + // Note that passing success- and error-handlers is optional. + */ + put: function (key, value, onSuccess, onError) { + if (this.keyPath !== null) { + onError = onSuccess; + onSuccess = value; + value = key; + } + onError || (onError = defaultErrorHandler); + onSuccess || (onSuccess = defaultSuccessHandler); -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; + var hasSuccess = false, + result = null, + putRequest; -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - processNextTick(cb, er); -} + var putTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE); + putTransaction.oncomplete = function () { + var callback = hasSuccess ? onSuccess : onError; + callback(result); + }; + putTransaction.onabort = onError; + putTransaction.onerror = onError; -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; + if (this.keyPath !== null) { // in-line keys + this._addIdPropertyIfNeeded(value); + putRequest = putTransaction.objectStore(this.storeName).put(value); + } else { // out-of-line keys + putRequest = putTransaction.objectStore(this.storeName).put(value, key); + } + putRequest.onsuccess = function (event) { + hasSuccess = true; + result = event.target.result; + }; + putRequest.onerror = onError; - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - processNextTick(cb, er); - valid = false; - } - return valid; -} + return putTransaction; + }, -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = Buffer.isBuffer(chunk); + /** + * Retrieves an object from the store. If no entry exists with the given id, + * the success handler will be called with null as first and only argument. + * + * @param {*} key The id of the object to fetch. + * @param {Function} [onSuccess] A callback that is called if fetching + * was successful. Will receive the object as only argument. + * @param {Function} [onError] A callback that will be called if an error + * occurred during the operation. + * @returns {IDBTransaction} The transaction used for this operation. + */ + get: function (key, onSuccess, onError) { + onError || (onError = defaultErrorHandler); + onSuccess || (onSuccess = defaultSuccessHandler); - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + var hasSuccess = false, + result = null; - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + var 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); + getRequest.onsuccess = function (event) { + hasSuccess = true; + result = event.target.result; + }; + getRequest.onerror = onError; - if (typeof cb !== 'function') cb = nop; + return getTransaction; + }, - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } + /** + * Removes an object from the store. + * + * @param {*} key The id of the object to remove. + * @param {Function} [onSuccess] A callback that is called if the removal + * was successful. + * @param {Function} [onError] A callback that will be called if an error + * occurred during the operation. + * @returns {IDBTransaction} The transaction used for this operation. + */ + remove: function (key, onSuccess, onError) { + onError || (onError = defaultErrorHandler); + onSuccess || (onSuccess = defaultSuccessHandler); - return ret; -}; + var hasSuccess = false, + result = null; -Writable.prototype.cork = function () { - var state = this._writableState; + var 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; - state.corked++; -}; + var deleteRequest = removeTransaction.objectStore(this.storeName)['delete'](key); + deleteRequest.onsuccess = function (event) { + hasSuccess = true; + result = event.target.result; + }; + deleteRequest.onerror = onError; -Writable.prototype.uncork = function () { - var state = this._writableState; + return removeTransaction; + }, - if (state.corked) { - state.corked--; + /** + * Runs a batch of put and/or remove operations on the store. + * + * @param {Array} dataArray An array of objects containing the operation to run + * and the data object (for put operations). + * @param {Function} [onSuccess] A callback that is called if all operations + * were successful. + * @param {Function} [onError] A callback that is called if an error + * occurred during one of the operations. + * @returns {IDBTransaction} The transaction used for this operation. + */ + batch: function (dataArray, onSuccess, onError) { + onError || (onError = defaultErrorHandler); + onSuccess || (onSuccess = defaultSuccessHandler); - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; + if (Object.prototype.toString.call(dataArray) != '[object Array]') { + onError(new Error('dataArray argument must be of type Array.')); + } else if (dataArray.length === 0) { + return onSuccess(true); + } -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; + var count = dataArray.length; + var called = false; + var hasSuccess = false; -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} + var 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; -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// 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 len = state.objectMode ? 1 : chunk.length; - state.length += len; + var onItemSuccess = function () { + count--; + if (count === 0 && !called) { + called = true; + hasSuccess = true; + } + }; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + dataArray.forEach(function (operation) { + var type = operation.type; + var key = operation.key; + var value = operation.value; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } + var onItemError = function (err) { + batchTransaction.abort(); + if (!called) { + called = true; + onError(err, type, key); + } + }; - return ret; -} + if (type == 'remove') { + var deleteRequest = batchTransaction.objectStore(this.storeName)['delete'](key); + deleteRequest.onsuccess = onItemSuccess; + deleteRequest.onerror = onItemError; + } else if (type == 'put') { + var putRequest; + if (this.keyPath !== null) { // in-line keys + this._addIdPropertyIfNeeded(value); + putRequest = batchTransaction.objectStore(this.storeName).put(value); + } else { // out-of-line keys + putRequest = batchTransaction.objectStore(this.storeName).put(value, key); + } + putRequest.onsuccess = onItemSuccess; + putRequest.onerror = onItemError; + } + }, this); -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} + return batchTransaction; + }, -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) processNextTick(cb, er);else cb(er); + /** + * Takes an array of objects and stores them in a single transaction. + * + * @param {Array} dataArray An array of objects to store + * @param {Function} [onSuccess] A callback that is called if all operations + * were successful. + * @param {Function} [onError] A callback that is called if an error + * occurred during one of the operations. + * @returns {IDBTransaction} The transaction used for this operation. + */ + putBatch: function (dataArray, onSuccess, onError) { + var batchData = dataArray.map(function (item) { + return {type: 'put', value: item}; + }); - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} + return this.batch(batchData, onSuccess, onError); + }, -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} + /** + * Like putBatch, takes an array of objects and stores them in a single + * transaction, but allows processing of the result values. Returns the + * processed records containing the key for newly created records to the + * onSuccess calllback instead of only returning true or false for success. + * In addition, added the option for the caller to specify a key field that + * should be set to the newly created key. + * + * @param {Array} dataArray An array of objects to store + * @param {Object} [options] An object containing optional options + * @param {String} [options.keyField=this.keyPath] Specifies a field in the record to update + * with the auto-incrementing key. Defaults to the store's keyPath. + * @param {Function} [onSuccess] A callback that is called if all operations + * were successful. + * @param {Function} [onError] A callback that is called if an error + * occurred during one of the operations. + * @returns {IDBTransaction} The transaction used for this operation. + * + */ + upsertBatch: function (dataArray, options, onSuccess, onError) { + // handle `dataArray, onSuccess, onError` signature + if (typeof options == 'function') { + onSuccess = options; + onError = onSuccess; + options = {}; + } -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + onError || (onError = defaultErrorHandler); + onSuccess || (onSuccess = defaultSuccessHandler); + options || (options = {}); - onwriteStateUpdate(state); + if (Object.prototype.toString.call(dataArray) != '[object Array]') { + onError(new Error('dataArray argument must be of type Array.')); + } - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + var keyField = options.keyField || this.keyPath; + var count = dataArray.length; + var called = false; + var hasSuccess = false; + var index = 0; // assume success callbacks are executed in order - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + var batchTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE); + batchTransaction.oncomplete = function () { + if (hasSuccess) { + onSuccess(dataArray); + } else { + onError(false); + } + }; + batchTransaction.onabort = onError; + batchTransaction.onerror = onError; - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} + var onItemSuccess = function (event) { + var record = dataArray[index++]; + record[keyField] = event.target.result; -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} + count--; + if (count === 0 && !called) { + called = true; + hasSuccess = true; + } + }; -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} + dataArray.forEach(function (record) { + var key = record.key; -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + var onItemError = function (err) { + batchTransaction.abort(); + if (!called) { + called = true; + onError(err); + } + }; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + var putRequest; + if (this.keyPath !== null) { // in-line keys + this._addIdPropertyIfNeeded(record); + putRequest = batchTransaction.objectStore(this.storeName).put(record); + } else { // out-of-line keys + putRequest = batchTransaction.objectStore(this.storeName).put(record, key); + } + putRequest.onsuccess = onItemSuccess; + putRequest.onerror = onItemError; + }, this); - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } + return batchTransaction; + }, - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + /** + * Takes an array of keys and removes matching objects in a single + * transaction. + * + * @param {Array} keyArray An array of keys to remove + * @param {Function} [onSuccess] A callback that is called if all operations + * were successful. + * @param {Function} [onError] A callback that is called if an error + * occurred during one of the operations. + * @returns {IDBTransaction} The transaction used for this operation. + */ + removeBatch: function (keyArray, onSuccess, onError) { + var batchData = keyArray.map(function (key) { + return {type: 'remove', key: key}; + }); - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + return this.batch(batchData, onSuccess, onError); + }, - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } + /** + * Takes an array of keys and fetches matching objects + * + * @param {Array} keyArray An array of keys identifying the objects to fetch + * @param {Function} [onSuccess] A callback that is called if all operations + * were successful. + * @param {Function} [onError] A callback that is called if an error + * occurred during one of the operations. + * @param {String} [arrayType='sparse'] The type of array to pass to the + * success handler. May be one of 'sparse', 'dense' or 'skip'. Defaults to + * 'sparse'. This parameter specifies how to handle the situation if a get + * operation did not throw an error, but there was no matching object in + * the database. In most cases, 'sparse' provides the most desired + * behavior. See the examples for details. + * @returns {IDBTransaction} The transaction used for this operation. + * @example + // given that there are two objects in the database with the keypath + // values 1 and 2, and the call looks like this: + myStore.getBatch([1, 5, 2], onError, function (data) { … }, arrayType); - if (entry === null) state.lastBufferedRequest = null; - } + // this is what the `data` array will be like: - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + // arrayType == 'sparse': + // data is a sparse array containing two entries and having a length of 3: + [Object, 2: Object] + 0: Object + 2: Object + length: 3 + // calling forEach on data will result in the callback being called two + // times, with the index parameter matching the index of the key in the + // keyArray. -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; + // arrayType == 'dense': + // data is a dense array containing three entries and having a length of 3, + // where data[1] is of type undefined: + [Object, undefined, Object] + 0: Object + 1: undefined + 2: Object + length: 3 + // calling forEach on data will result in the callback being called three + // times, with the index parameter matching the index of the key in the + // keyArray, but the second call will have undefined as first argument. -Writable.prototype._writev = null; + // arrayType == 'skip': + // data is a dense array containing two entries and having a length of 2: + [Object, Object] + 0: Object + 1: Object + length: 2 + // calling forEach on data will result in the callback being called two + // times, with the index parameter not matching the index of the key in the + // keyArray. + */ + getBatch: function (keyArray, onSuccess, onError, arrayType) { + onError || (onError = defaultErrorHandler); + onSuccess || (onSuccess = defaultSuccessHandler); + arrayType || (arrayType = 'sparse'); -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + if (Object.prototype.toString.call(keyArray) != '[object Array]') { + onError(new Error('keyArray argument must be of type Array.')); + } else if (keyArray.length === 0) { + return onSuccess([]); + } - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + var data = []; + var count = keyArray.length; + var called = false; + var hasSuccess = false; + var result = null; - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + var 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; - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + var onItemSuccess = function (event) { + if (event.target.result || arrayType == 'dense') { + data.push(event.target.result); + } else if (arrayType == 'sparse') { + data.length++; + } + count--; + if (count === 0) { + called = true; + hasSuccess = true; + result = data; + } + }; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); -}; + keyArray.forEach(function (key) { -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} + var onItemError = function (err) { + called = true; + result = err; + onError(err); + batchTransaction.abort(); + }; -function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } -} + var getRequest = batchTransaction.objectStore(this.storeName).get(key); + getRequest.onsuccess = onItemSuccess; + getRequest.onerror = onItemError; -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } - } - return need; -} + }, this); -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) processNextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} + return batchTransaction; + }, -// 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; + /** + * Fetches all entries in the store. + * + * @param {Function} [onSuccess] A callback that is called if the operation + * was successful. Will receive an array of objects. + * @param {Function} [onError] A callback that will be called if an error + * occurred during the operation. + * @returns {IDBTransaction} The transaction used for this operation. + */ + getAll: function (onSuccess, onError) { + onError || (onError = defaultErrorHandler); + onSuccess || (onSuccess = defaultSuccessHandler); + var getAllTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); + var store = getAllTransaction.objectStore(this.storeName); + if (store.getAll) { + this._getAllNative(getAllTransaction, store, onSuccess, onError); + } else { + this._getAllCursor(getAllTransaction, store, onSuccess, onError); + } - 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; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; -} -}).call(this,require('_process')) -},{"./_stream_duplex":74,"./internal/streams/stream":80,"_process":206,"core-util-is":8,"inherits":35,"process-nextick-args":69,"safe-buffer":82,"util-deprecate":90}],79:[function(require,module,exports){ -'use strict'; + return getAllTransaction; + }, -/**/ + /** + * Implements getAll for IDB implementations that have a non-standard + * getAll() method. + * + * @param {IDBTransaction} getAllTransaction An open READ transaction. + * @param {IDBObjectStore} store A reference to the store. + * @param {Function} onSuccess A callback that will be called if the + * operation was successful. + * @param {Function} onError A callback that will be called if an + * error occurred during the operation. + * @private + */ + _getAllNative: function (getAllTransaction, store, onSuccess, onError) { + var hasSuccess = false, + result = null; -var Buffer = require('safe-buffer').Buffer; -/**/ + getAllTransaction.oncomplete = function () { + var callback = hasSuccess ? onSuccess : onError; + callback(result); + }; + getAllTransaction.onabort = onError; + getAllTransaction.onerror = onError; -module.exports = BufferList; + var getAllRequest = store.getAll(); + getAllRequest.onsuccess = function (event) { + hasSuccess = true; + result = event.target.result; + }; + getAllRequest.onerror = onError; + }, -function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; -} + /** + * Implements getAll for IDB implementations that do not have a getAll() + * method. + * + * @param {IDBTransaction} getAllTransaction An open READ transaction. + * @param {IDBObjectStore} store A reference to the store. + * @param {Function} onSuccess A callback that will be called if the + * operation was successful. + * @param {Function} onError A callback that will be called if an + * error occurred during the operation. + * @private + */ + _getAllCursor: function (getAllTransaction, store, onSuccess, onError) { + var all = [], + hasSuccess = false, + result = null; -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; -}; + getAllTransaction.oncomplete = function () { + var callback = hasSuccess ? onSuccess : onError; + callback(result); + }; + getAllTransaction.onabort = onError; + getAllTransaction.onerror = onError; -BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; -}; + var cursorRequest = store.openCursor(); + cursorRequest.onsuccess = function (event) { + var cursor = event.target.result; + if (cursor) { + all.push(cursor.value); + cursor['continue'](); + } + else { + hasSuccess = true; + result = all; + } + }; + cursorRequest.onError = onError; + }, -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; -}; + /** + * Clears the store, i.e. deletes all entries in the store. + * + * @param {Function} [onSuccess] A callback that will be called if the + * operation was successful. + * @param {Function} [onError] A callback that will be called if an + * error occurred during the operation. + * @returns {IDBTransaction} The transaction used for this operation. + */ + clear: function (onSuccess, onError) { + onError || (onError = defaultErrorHandler); + onSuccess || (onSuccess = defaultSuccessHandler); -BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; -}; + var hasSuccess = false, + result = null; -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; -}; + var 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; -BufferList.prototype.concat = function (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) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; -}; -},{"safe-buffer":82}],80:[function(require,module,exports){ -module.exports = require('events').EventEmitter; + var clearRequest = clearTransaction.objectStore(this.storeName).clear(); + clearRequest.onsuccess = function (event) { + hasSuccess = true; + result = event.target.result; + }; + clearRequest.onerror = onError; -},{"events":169}],81:[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'); + return clearTransaction; + }, -},{"./lib/_stream_duplex.js":74,"./lib/_stream_passthrough.js":75,"./lib/_stream_readable.js":76,"./lib/_stream_transform.js":77,"./lib/_stream_writable.js":78}],82:[function(require,module,exports){ -module.exports = require('buffer') + /** + * Checks if an id property needs to present on a object and adds one if + * necessary. + * + * @param {Object} dataObj The data object that is about to be stored + * @private + */ + _addIdPropertyIfNeeded: function (dataObj) { + if (typeof dataObj[this.keyPath] == 'undefined') { + dataObj[this.keyPath] = this._insertIdCount++ + Date.now(); + } + }, -},{"buffer":156}],83:[function(require,module,exports){ -var hasProp = Object.prototype.hasOwnProperty; + /************ + * indexing * + ************/ -function throwsMessage(err) { - return '[Throws: ' + (err ? err.message : '?') + ']'; -} + /** + * Returns a DOMStringList of index names of the store. + * + * @return {DOMStringList} The list of index names + */ + getIndexList: function () { + return this.store.indexNames; + }, -function safeGetValueFromPropertyOnObject(obj, property) { - if (hasProp.call(obj, property)) { - try { - return obj[property]; - } - catch (err) { - return throwsMessage(err); - } - } + /** + * Checks if an index with the given name exists in the store. + * + * @param {String} indexName The name of the index to look for + * @return {Boolean} Whether the store contains an index with the given name + */ + hasIndex: function (indexName) { + return this.store.indexNames.contains(indexName); + }, - return obj[property]; -} + /** + * Normalizes an object containing index data and assures that all + * properties are set. + * + * @param {Object} indexData The index data object to normalize + * @param {String} indexData.name The name of the index + * @param {String} [indexData.keyPath] The key path of the index + * @param {Boolean} [indexData.unique] Whether the index is unique + * @param {Boolean} [indexData.multiEntry] Whether the index is multi entry + */ + normalizeIndexData: function (indexData) { + indexData.keyPath = indexData.keyPath || indexData.name; + indexData.unique = !!indexData.unique; + indexData.multiEntry = !!indexData.multiEntry; + }, -function ensureProperties(obj) { - var seen = [ ]; // store references to objects we have seen before + /** + * Checks if an actual index complies with an expected index. + * + * @param {IDBIndex} actual The actual index found in the store + * @param {Object} expected An Object describing an expected index + * @return {Boolean} Whether both index definitions are identical + */ + indexComplies: function (actual, expected) { + var complies = ['keyPath', 'unique', 'multiEntry'].every(function (key) { + // IE10 returns undefined for no multiEntry + if (key == 'multiEntry' && actual[key] === undefined && expected[key] === false) { + return true; + } + // Compound keys + if (key == 'keyPath' && Object.prototype.toString.call(expected[key]) == '[object Array]') { + var exp = expected.keyPath; + var act = actual.keyPath; - function visit(obj) { - if (obj === null || typeof obj !== 'object') { - return obj; - } + // IE10 can't handle keyPath sequences and stores them as a string. + // The index will be unusable there, but let's still return true if + // the keyPath sequence matches. + if (typeof act == 'string') { + return exp.toString() == act; + } - if (seen.indexOf(obj) !== -1) { - return '[Circular]'; - } - seen.push(obj); + // Chrome/Opera stores keyPath squences as DOMStringList, Firefox + // as Array + if (!(typeof act.contains == 'function' || typeof act.indexOf == 'function')) { + return false; + } - if (typeof obj.toJSON === 'function') { - try { - return visit(obj.toJSON()); - } catch(err) { - return throwsMessage(err); - } - } + if (act.length !== exp.length) { + return false; + } - if (Array.isArray(obj)) { - return obj.map(visit); - } + for (var i = 0, m = exp.length; i < m; i++) { + if (!( (act.contains && act.contains(exp[i])) || act.indexOf(exp[i] !== -1) )) { + return false; + } + } + return true; + } + return expected[key] == actual[key]; + }); + return complies; + }, - return Object.keys(obj).reduce(function(result, prop) { - // prevent faulty defined getter properties - result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop)); - return result; - }, {}); - }; + /********** + * cursor * + **********/ - return visit(obj); -} + /** + * Iterates over the store using the given options and calling onItem + * for each entry matching the options. + * + * @param {Function} onItem A callback to be called for each match + * @param {Object} [options] An object defining specific options + * @param {String} [options.index=null] A name of an IDBIndex to operate on + * @param {String} [options.order=ASC] The order in which to provide the + * results, can be 'DESC' or 'ASC' + * @param {Boolean} [options.autoContinue=true] Whether to automatically + * iterate the cursor to the next result + * @param {Boolean} [options.filterDuplicates=false] Whether to exclude + * duplicate matches + * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use + * @param {Boolean} [options.writeAccess=false] Whether grant write access + * to the store in the onItem callback + * @param {Function} [options.onEnd=null] A callback to be called after + * iteration has ended + * @param {Function} [options.onError=throw] A callback to be called + * if an error occurred during the operation. + * @param {Number} [options.limit=Infinity] Limit the number of returned + * results to this number + * @param {Number} [options.offset=0] Skip the provided number of results + * in the resultset + * @param {Boolean} [options.allowItemRejection=false] Allows the onItem + * function to return a Boolean to accept or reject the current item + * @returns {IDBTransaction} The transaction used for this operation. + */ + iterate: function (onItem, options) { + options = mixin({ + index: null, + order: 'ASC', + autoContinue: true, + filterDuplicates: false, + keyRange: null, + writeAccess: false, + onEnd: null, + onError: defaultErrorHandler, + limit: Infinity, + offset: 0, + allowItemRejection: false + }, options || {}); -module.exports = function(data) { - return JSON.stringify(ensureProperties(data)); -} + var directionType = options.order.toLowerCase() == 'desc' ? 'PREV' : 'NEXT'; + if (options.filterDuplicates) { + directionType += '_NO_DUPLICATE'; + } -module.exports.ensureProperties = ensureProperties; + var hasSuccess = false; + var cursorTransaction = this.db.transaction([this.storeName], this.consts[options.writeAccess ? 'READ_WRITE' : 'READ_ONLY']); + var cursorTarget = cursorTransaction.objectStore(this.storeName); + if (options.index) { + cursorTarget = cursorTarget.index(options.index); + } + var recordCount = 0; -},{}],84:[function(require,module,exports){ -module.exports = shift + cursorTransaction.oncomplete = function () { + if (!hasSuccess) { + options.onError(null); + return; + } + if (options.onEnd) { + options.onEnd(); + } else { + onItem(null); + } + }; + cursorTransaction.onabort = options.onError; + cursorTransaction.onerror = options.onError; -function shift (stream) { - var rs = stream._readableState - if (!rs) return null - return rs.objectMode ? stream.read() : stream.read(getStateLength(rs)) -} + var cursorRequest = cursorTarget.openCursor(options.keyRange, this.consts[directionType]); + 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); + if (!options.allowItemRejection || onItemReturn !== false) { + recordCount++; + } + if (options.autoContinue) { + if (recordCount + options.offset < options.limit) { + cursor['continue'](); + } else { + hasSuccess = true; + } + } + } + } else { + hasSuccess = true; + } + }; -function getStateLength (state) { - if (state.buffer.length) { - // Since node 6.3.0 state.buffer is a BufferList not an array - if (state.buffer.head) { - return state.buffer.head.data.length - } + return cursorTransaction; + }, + + /** + * Runs a query against the store and passes an array containing matched + * objects to the success handler. + * + * @param {Function} onSuccess A callback to be called when the operation + * was successful. + * @param {Object} [options] An object defining specific options + * @param {String} [options.index=null] A name of an IDBIndex to operate on + * @param {String} [options.order=ASC] The order in which to provide the + * results, can be 'DESC' or 'ASC' + * @param {Boolean} [options.filterDuplicates=false] Whether to exclude + * duplicate matches + * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use + * @param {Function} [options.onError=throw] A callback to be called + * if an error occurred during the operation. + * @param {Number} [options.limit=Infinity] Limit the number of returned + * results to this number + * @param {Number} [options.offset=0] Skip the provided number of results + * in the resultset + * @param {Function} [options.filter=null] A custom filter function to + * apply to query resuts before returning. Must return `false` to reject + * an item. Can be combined with keyRanges. + * @returns {IDBTransaction} The transaction used for this operation. + */ + query: function (onSuccess, options) { + var result = [], + processedItems = 0; + options = options || {}; + options.autoContinue = true; + options.writeAccess = false; + options.allowItemRejection = !!options.filter; + options.onEnd = function () { + onSuccess(result, processedItems); + }; + return this.iterate(function (item) { + processedItems++; + var accept = options.filter ? options.filter(item) : true; + if (accept !== false) { + result.push(item); + } + return accept; + }, options); + }, - return state.buffer[0].length - } + /** + * + * Runs a query against the store, but only returns the number of matches + * instead of the matches itself. + * + * @param {Function} onSuccess A callback to be called if the opration + * was successful. + * @param {Object} [options] An object defining specific options + * @param {String} [options.index=null] A name of an IDBIndex to operate on + * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use + * @param {Function} [options.onError=throw] A callback to be called if an error + * occurred during the operation. + * @returns {IDBTransaction} The transaction used for this operation. + */ + count: function (onSuccess, options) { - return state.length -} + options = mixin({ + index: null, + keyRange: null + }, options || {}); -},{}],85:[function(require,module,exports){ -'use strict'; + var onError = options.onError || defaultErrorHandler; -var Buffer = require('safe-buffer').Buffer; + var hasSuccess = false, + result = null; -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (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 true; - default: - return false; - } -}; + var cursorTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); + cursorTransaction.oncomplete = function () { + var callback = hasSuccess ? onSuccess : onError; + callback(result); + }; + cursorTransaction.onabort = onError; + cursorTransaction.onerror = onError; -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; + var cursorTarget = cursorTransaction.objectStore(this.storeName); + if (options.index) { + cursorTarget = cursorTarget.index(options.index); + } + var countRequest = cursorTarget.count(options.keyRange); + countRequest.onsuccess = function (evt) { + hasSuccess = true; + result = evt.target.result; + }; + countRequest.onError = onError; -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} + return cursorTransaction; + }, -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} + /**************/ + /* key ranges */ + /**************/ -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; + /** + * Creates a key range using specified options. This key range can be + * handed over to the count() and iterate() methods. + * + * Note: You must provide at least one or both of "lower" or "upper" value. + * + * @param {Object} options The options for the key range to create + * @param {*} [options.lower] The lower bound + * @param {Boolean} [options.excludeLower] Whether to exclude the lower + * bound passed in options.lower from the key range + * @param {*} [options.upper] The upper bound + * @param {Boolean} [options.excludeUpper] Whether to exclude the upper + * bound passed in options.upper from the key range + * @param {*} [options.only] A single key value. Use this if you need a key + * range that only includes one value for a key. Providing this + * property invalidates all other properties. + * @return {IDBKeyRange} The IDBKeyRange representing the specified options + */ + makeKeyRange: function (options) { + /*jshint onecase:true */ + var keyRange, + hasLower = typeof options.lower != 'undefined', + hasUpper = typeof options.upper != 'undefined', + isOnly = typeof options.only != 'undefined'; -StringDecoder.prototype.end = utf8End; + switch (true) { + case isOnly: + keyRange = this.keyRange.only(options.only); + break; + case hasLower && hasUpper: + keyRange = this.keyRange.bound(options.lower, options.upper, options.excludeLower, options.excludeUpper); + break; + case hasLower: + keyRange = this.keyRange.lowerBound(options.lower, options.excludeLower); + break; + case hasUpper: + keyRange = this.keyRange.upperBound(options.upper, options.excludeUpper); + break; + default: + throw new Error('Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.'); + } -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; + return keyRange; -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; + } -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return -1; -} + }; -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} + /** helpers **/ + var empty = {}; -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'.repeat(p); - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'.repeat(p + 1); + function mixin (target, source) { + var name, s; + for (name in source) { + s = source[name]; + if (s !== empty[name] && s !== target[name]) { + target[name] = s; + } + } + return target; } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'.repeat(p + 2); - } + + function hasVersionError(errorEvent) { + if ('error' in errorEvent.target) { + return errorEvent.target.error.name == 'VersionError'; + } else if ('errorCode' in errorEvent.target) { + return errorEvent.target.errorCode == 12; + } + return false; } - } -} -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} + IDBStore.prototype = proto; + IDBStore.version = proto.version; -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -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); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} + return IDBStore; -// For UTF-8, a replacement character for each buffered byte of a (partial) -// character needs to be added to the output. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); - return r; -} +}, this); -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -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 >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} +},{}],39:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -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; -} + i += d -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; + m = m + Math.pow(2, mLen) + e = e - eBias } - return buf.toString('base64', i, buf.length - n); + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} + value = Math.abs(value) -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":82}],86:[function(require,module,exports){ -exports.doubleNormalization0point5 = 'doubleNormalization0point5' -exports.logNormalization = 'logNormalization' -exports.raw = 'raw' -exports.selfString = 'selfString' -exports.selfNumeric = 'selfNumeric' + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } -exports.getTermFrequency = function (docVector, options) { - options = Object.assign({}, { - scheme: 'raw', - weight: 0 - }, options) - // handle empty docVector - if (!docVector) { - return [] - } - if (docVector.length === 0) { - return [] - } - if (options.scheme === 'logNormalization') { - return docVector.map(function (item) { - return [item[0], +options.weight + Math.log(1 + (+item[1]))] - }) - } else if (options.scheme === 'doubleNormalization0point5') { - var maxFreq = docVector.sort(function (a, b) { - return b[1] - a[1] - })[0][1] - return docVector.map(function (item) { - return [item[0], +options.weight + 0.5 + ((0.5 * +item[1]) / (maxFreq))] - }) - } else if (options.scheme === 'raw') { - return docVector.map(function (item) { - return [item[0], +options.weight + item[1]] - }) - } else if (options.scheme === 'selfString') { - return docVector.map(function (item) { - return [item[0], item[0][0] + ''] - }) - } else if (options.scheme === 'selfNumeric') { - return docVector.map(function (item) { - var value = item[0][0] - // try to cast to number - if (!isNaN(parseFloat(value)) && isFinite(value)) { - value = +options.weight + +item[0][0] - } - return [item[0], value] - }) + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } } -} -},{}],87:[function(require,module,exports){ -/** - * search-index module. - * @module term-vector - */ + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} -const _isEqual = require('lodash.isequal') + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} -exports.getVector = function (tokens, nGramLength) { - nGramLength = nGramLength || 1 - if (Object.prototype.toString.call(tokens) !== '[object Array]') { - throw new Error('error: input must be an Array') - } - if (nGramLength === 0) { - throw new Error('error: nGramLength must be greater than 0') + buffer[offset + i - d] |= s * 128 +} + +},{}],40:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor } - var vec = [] - if (!isNaN(nGramLength)) { - return getTermVectorForNgramLength(tokens, nGramLength) - } else if (Object.prototype.toString.call(nGramLength) === '[object Array]') { - for (var i = 0; i < nGramLength.length; i++) { - vec = vec.concat(getTermVectorForNgramLength(tokens, nGramLength[i])) - } - return vec - } else if (typeof (nGramLength) && - ((parseInt(nGramLength.gte) <= - parseInt(nGramLength.lte)))) { - var j = parseInt(nGramLength.gte) - while (j <= nGramLength.lte && tokens[j - 1]) { - vec = vec.concat(getTermVectorForNgramLength(tokens, j++)) - } - return vec - } else throw new Error('nGramLength seems to be maformed- see docs') } -// create ngrams of desired length -var getTermVectorForNgramLength = function (tokens, nGramLength) { - // cant make ngram if specified length is longer than token array - if (nGramLength > tokens.length) { - return [] +},{}],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 +// this to work, but no error will be thrown if they are not sorted + + +var Readable = require('stream').Readable + +exports.getIntersectionStream = function(sortedSets) { + var s = new Readable + var i = 0 // identifies array + var ii = [] // identifies index in each array + for (var k = 0; k < sortedSets.length; k++) { + ii[k] = 0 } - var ngrams = [] - for (var i = 0; i <= (tokens.length - nGramLength); i++) { - ngrams.push(tokens.slice(i, i + nGramLength)) + //special case: sortedSets is empty + if (sortedSets.length === 0) { + // do nothing } - // count ngrams - ngrams = ngrams.sort() - // special case- doc of array length 1 - if (ngrams.length === 1) return [[ngrams[0], 1]] - var counter = 1 - var lastToken = ngrams[0] - var vector = [] - for (var j = 1; j < ngrams.length; j++) { - if (_isEqual(ngrams[j], lastToken)) { - counter++ - } else { - vector.push([lastToken, counter]) - counter = 1 - lastToken = ngrams[j] + //special case: sortedSets contains only one set + else if (sortedSets.length === 1) { + sortedSets[0].forEach(function (item) { + s.push(item + '') + }) + } + //do a normal intersect + else { + var finished = false + // walk along the set of given arrays + while (!finished) { + if (sortedSets[i][ii[i]] < sortedSets[i + 1][ii[i + 1]]) { + ii[i]++ + } + else if (sortedSets[i][ii[i]] > sortedSets[i + 1][ii[i + 1]]) { + ii[i + 1]++ + } + // there is an intersection between two arrays- now see if the + // next array also contains this item + else if ((i + 2) < sortedSets.length) { + ii[i]++ + i++ + } + // All arrays have been traversed and the item was present in each + // array. Therefore this item is in the intersection set. Emit the + // item in the stream + else { + s.push(sortedSets[i][ii[i]] + '') + ii[i]++ + ii[i + 1]++ + + for (var k = 0; k < sortedSets.length; k++) { + if (ii[k] >= sortedSets[k].length) finished = true + } + i = 0 + } } } - vector.push([ngrams[i - 1], counter]) - return vector + + // indicates the end of the stream + s.push(null) + + return s } -},{"lodash.isequal":62}],88:[function(require,module,exports){ -(function (process){ -var Stream = require('stream') +},{"stream":147}],42:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ -// through -// -// a stream that does nothing but re-emit the input. -// useful for aggregating a series of changing but not ending streams into one stream) +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} -exports = module.exports = through -through.through = through +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} -//create a readable writable stream. +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} -function through (write, end, opts) { - write = write || function (data) { this.queue(data) } - end = end || function () { this.queue(null) } +},{}],43:[function(require,module,exports){ +var toString = {}.toString; - var ended = false, destroyed = false, buffer = [], _ended = false - var stream = new Stream() - stream.readable = stream.writable = true - stream.paused = false +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; -// stream.autoPause = !(opts && opts.autoPause === false) - stream.autoDestroy = !(opts && opts.autoDestroy === false) +},{}],44:[function(require,module,exports){ +var Buffer = require('buffer').Buffer; - stream.write = function (data) { - write.call(this, data) - return !stream.paused - } +module.exports = isBuffer; - function drain() { - while(buffer.length && !stream.paused) { - var data = buffer.shift() - if(null === data) - return stream.emit('end') - else - stream.emit('data', data) - } - } +function isBuffer (o) { + return Buffer.isBuffer(o) + || /\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o)); +} - stream.queue = stream.push = function (data) { -// console.error(ended) - if(_ended) return stream - if(data === null) _ended = true - buffer.push(data) - drain() - return stream - } +},{"buffer":9}],45:[function(require,module,exports){ +(function (Buffer){ +/*global Buffer*/ +// Named constants with unique integer values +var C = {}; +// Tokens +var LEFT_BRACE = C.LEFT_BRACE = 0x1; +var RIGHT_BRACE = C.RIGHT_BRACE = 0x2; +var LEFT_BRACKET = C.LEFT_BRACKET = 0x3; +var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4; +var COLON = C.COLON = 0x5; +var COMMA = C.COMMA = 0x6; +var TRUE = C.TRUE = 0x7; +var FALSE = C.FALSE = 0x8; +var NULL = C.NULL = 0x9; +var STRING = C.STRING = 0xa; +var NUMBER = C.NUMBER = 0xb; +// Tokenizer States +var START = C.START = 0x11; +var STOP = C.STOP = 0x12; +var TRUE1 = C.TRUE1 = 0x21; +var TRUE2 = C.TRUE2 = 0x22; +var TRUE3 = C.TRUE3 = 0x23; +var FALSE1 = C.FALSE1 = 0x31; +var FALSE2 = C.FALSE2 = 0x32; +var FALSE3 = C.FALSE3 = 0x33; +var FALSE4 = C.FALSE4 = 0x34; +var NULL1 = C.NULL1 = 0x41; +var NULL2 = C.NULL2 = 0x42; +var NULL3 = C.NULL3 = 0x43; +var NUMBER1 = C.NUMBER1 = 0x51; +var NUMBER3 = C.NUMBER3 = 0x53; +var STRING1 = C.STRING1 = 0x61; +var STRING2 = C.STRING2 = 0x62; +var STRING3 = C.STRING3 = 0x63; +var STRING4 = C.STRING4 = 0x64; +var STRING5 = C.STRING5 = 0x65; +var STRING6 = C.STRING6 = 0x66; +// Parser States +var VALUE = C.VALUE = 0x71; +var KEY = C.KEY = 0x72; +// Parser Modes +var OBJECT = C.OBJECT = 0x81; +var ARRAY = C.ARRAY = 0x82; +// Character constants +var BACK_SLASH = "\\".charCodeAt(0); +var FORWARD_SLASH = "\/".charCodeAt(0); +var BACKSPACE = "\b".charCodeAt(0); +var FORM_FEED = "\f".charCodeAt(0); +var NEWLINE = "\n".charCodeAt(0); +var CARRIAGE_RETURN = "\r".charCodeAt(0); +var TAB = "\t".charCodeAt(0); - //this will be registered as the first 'end' listener - //must call destroy next tick, to make sure we're after any - //stream piped from here. - //this is only a problem if end is not emitted synchronously. - //a nicer way to do this is to make sure this is the last listener for 'end' +var STRING_BUFFER_SIZE = 64 * 1024; - stream.on('end', function () { - stream.readable = false - if(!stream.writable && stream.autoDestroy) - process.nextTick(function () { - stream.destroy() - }) - }) +function Parser() { + this.tState = START; + this.value = undefined; - function _end () { - stream.writable = false - end.call(stream) - if(!stream.readable && stream.autoDestroy) - stream.destroy() - } + this.string = undefined; // string data + this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE); + this.stringBufferOffset = 0; + this.unicode = undefined; // unicode escapes + this.highSurrogate = undefined; + + this.key = undefined; + this.mode = undefined; + this.stack = []; + this.state = VALUE; + this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary + this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read + this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached - stream.end = function (data) { - if(ended) return - ended = true - if(arguments.length) stream.write(data) - _end() // will emit or queue - return stream - } + // Stream offset + this.offset = -1; +} - stream.destroy = function () { - if(destroyed) return - destroyed = true - ended = true - buffer.length = 0 - stream.writable = stream.readable = false - stream.emit('close') - return stream +// Slow code to string converter (only used when throwing syntax errors) +Parser.toknam = function (code) { + var keys = Object.keys(C); + for (var i = 0, l = keys.length; i < l; i++) { + var key = keys[i]; + if (C[key] === code) { return key; } } + return code && ("0x" + code.toString(16)); +}; - stream.pause = function () { - if(stream.paused) return - stream.paused = true - return stream +var proto = Parser.prototype; +proto.onError = function (err) { throw err; }; +proto.charError = function (buffer, i) { + this.tState = STOP; + this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState))); +}; +proto.appendStringChar = function (char) { + if (this.stringBufferOffset >= STRING_BUFFER_SIZE) { + this.string += this.stringBuffer.toString('utf8'); + this.stringBufferOffset = 0; } - stream.resume = function () { - if(stream.paused) { - stream.paused = false - stream.emit('resume') + this.stringBuffer[this.stringBufferOffset++] = char; +}; +proto.appendStringBuf = function (buf, start, end) { + var size = buf.length; + if (typeof start === 'number') { + if (typeof end === 'number') { + if (end < 0) { + // adding a negative end decreeses the size + size = buf.length - start + end; + } else { + size = end - start; + } + } else { + size = buf.length - start; } - drain() - //may have become paused again, - //as drain emits 'data'. - if(!stream.paused) - stream.emit('drain') - return stream } - return stream -} + if (size < 0) { + size = 0; + } -}).call(this,require('_process')) -},{"_process":206,"stream":223}],89:[function(require,module,exports){ -(function (Buffer){ -/** - * Convert a typed array to a Buffer without a copy - * - * Author: Feross Aboukhadijeh - * License: MIT - * - * `npm install typedarray-to-buffer` - */ - -module.exports = function (arr) { - if (typeof Buffer._augment === 'function' && Buffer.TYPED_ARRAY_SUPPORT) { - // If `Buffer` is from the `buffer` module and this browser supports typed arrays, - // then augment it with all the `Buffer` methods. - return Buffer._augment(arr) - } else { - // Otherwise, fallback to creating a `Buffer` with a copy. - return new Buffer(arr) + if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) { + this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); + this.stringBufferOffset = 0; } -} -}).call(this,require("buffer").Buffer) -},{"buffer":156}],90:[function(require,module,exports){ -(function (global){ + buf.copy(this.stringBuffer, this.stringBufferOffset, start, end); + this.stringBufferOffset += size; +}; +proto.write = function (buffer) { + if (typeof buffer === "string") buffer = new Buffer(buffer); + var n; + for (var i = 0, l = buffer.length; i < l; i++) { + if (this.tState === START){ + n = buffer[i]; + this.offset++; + if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // { + }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // } + }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [ + }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ] + }else if(n === 0x3a){ this.onToken(COLON, ":"); // : + }else if(n === 0x2c){ this.onToken(COMMA, ","); // , + }else if(n === 0x74){ this.tState = TRUE1; // t + }else if(n === 0x66){ this.tState = FALSE1; // f + }else if(n === 0x6e){ this.tState = NULL1; // n + }else if(n === 0x22){ // " + this.string = ""; + this.stringBufferOffset = 0; + this.tState = STRING1; + }else if(n === 0x2d){ this.string = "-"; this.tState = NUMBER1; // - + }else{ + if (n >= 0x30 && n < 0x40) { // 1-9 + this.string = String.fromCharCode(n); this.tState = NUMBER3; + } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) { + // whitespace + } else { + return this.charError(buffer, i); + } + } + }else if (this.tState === STRING1){ // After open quote + n = buffer[i]; // get current byte from buffer + // check for carry over of a multi byte char split between data chunks + // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration + if (this.bytes_remaining > 0) { + for (var j = 0; j < this.bytes_remaining; j++) { + this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j]; + } -/** - * Module exports. - */ + this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]); + this.bytes_in_sequence = this.bytes_remaining = 0; + i = i + j - 1; + } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time + if (n <= 193 || n > 244) { + return this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + Parser.toknam(this.tState))); + } + if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; + if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; + if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; + if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split + for (var k = 0; k <= (buffer.length - 1 - i); k++) { + this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk + } + this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length; + i = buffer.length - 1; + } else { + this.appendStringBuf(buffer, i, i + this.bytes_in_sequence); + i = i + this.bytes_in_sequence - 1; + } + } else if (n === 0x22) { + this.tState = START; + this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); + this.stringBufferOffset = 0; + this.onToken(STRING, this.string); + this.offset += Buffer.byteLength(this.string, 'utf8') + 1; + this.string = undefined; + } + else if (n === 0x5c) { + this.tState = STRING2; + } + else if (n >= 0x20) { this.appendStringChar(n); } + else { + return this.charError(buffer, i); + } + }else if (this.tState === STRING2){ // After backslash + n = buffer[i]; + if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1; + }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1; + }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1; + }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1; + }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1; + }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1; + }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1; + }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1; + }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3; + }else{ + return this.charError(buffer, i); + } + }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes + n = buffer[i]; + // 0-9 A-F a-f + if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) { + this.unicode += String.fromCharCode(n); + if (this.tState++ === STRING6) { + var intVal = parseInt(this.unicode, 16); + this.unicode = undefined; + if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate + this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal))); + this.highSurrogate = undefined; + } else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate + this.highSurrogate = intVal; + } else { + if (this.highSurrogate !== undefined) { + this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))); + this.highSurrogate = undefined; + } + this.appendStringBuf(new Buffer(String.fromCharCode(intVal))); + } + this.tState = STRING1; + } + } else { + return this.charError(buffer, i); + } + } else if (this.tState === NUMBER1 || this.tState === NUMBER3) { + n = buffer[i]; -module.exports = deprecate; + switch (n) { + case 0x30: // 0 + case 0x31: // 1 + case 0x32: // 2 + case 0x33: // 3 + case 0x34: // 4 + case 0x35: // 5 + case 0x36: // 6 + case 0x37: // 7 + case 0x38: // 8 + case 0x39: // 9 + case 0x2e: // . + case 0x65: // e + case 0x45: // E + case 0x2b: // + + case 0x2d: // - + this.string += String.fromCharCode(n); + this.tState = NUMBER3; + break; + default: + this.tState = START; + var result = Number(this.string); -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ + if (isNaN(result)){ + return this.charError(buffer, i); + } -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; + if ((this.string.match(/[0-9]+/) == this.string) && (result.toString() != this.string)) { + // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number + this.onToken(STRING, this.string); + } else { + this.onToken(NUMBER, result); + } + + this.offset += this.string.length - 1; + this.string = undefined; + i--; + break; + } + }else if (this.tState === TRUE1){ // r + if (buffer[i] === 0x72) { this.tState = TRUE2; } + else { return this.charError(buffer, i); } + }else if (this.tState === TRUE2){ // u + if (buffer[i] === 0x75) { this.tState = TRUE3; } + else { return this.charError(buffer, i); } + }else if (this.tState === TRUE3){ // e + if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE1){ // a + if (buffer[i] === 0x61) { this.tState = FALSE2; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE2){ // l + if (buffer[i] === 0x6c) { this.tState = FALSE3; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE3){ // s + if (buffer[i] === 0x73) { this.tState = FALSE4; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE4){ // e + if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; } + else { return this.charError(buffer, i); } + }else if (this.tState === NULL1){ // u + if (buffer[i] === 0x75) { this.tState = NULL2; } + else { return this.charError(buffer, i); } + }else if (this.tState === NULL2){ // l + if (buffer[i] === 0x6c) { this.tState = NULL3; } + else { return this.charError(buffer, i); } + }else if (this.tState === NULL3){ // l + if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; } + else { return this.charError(buffer, i); } + } } +}; +proto.onToken = function (token, value) { + // Override this to get events +}; - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); +proto.parseError = function (token, value) { + this.tState = STOP; + this.onError(new Error("Unexpected " + Parser.toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + Parser.toknam(this.state))); +}; +proto.push = function () { + this.stack.push({value: this.value, key: this.key, mode: this.mode}); +}; +proto.pop = function () { + var value = this.value; + var parent = this.stack.pop(); + this.value = parent.value; + this.key = parent.key; + this.mode = parent.mode; + this.emit(value); + if (!this.mode) { this.state = VALUE; } +}; +proto.emit = function (value) { + if (this.mode) { this.state = COMMA; } + this.onValue(value); +}; +proto.onValue = function (value) { + // Override me +}; +proto.onToken = function (token, value) { + if(this.state === VALUE){ + if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){ + if (this.value) { + this.value[this.key] = value; + } + this.emit(value); + }else if(token === LEFT_BRACE){ + this.push(); + if (this.value) { + this.value = this.value[this.key] = {}; } else { - console.warn(msg); + this.value = {}; } - warned = true; + this.key = undefined; + this.state = KEY; + this.mode = OBJECT; + }else if(token === LEFT_BRACKET){ + this.push(); + if (this.value) { + this.value = this.value[this.key] = []; + } else { + this.value = []; + } + this.key = 0; + this.mode = ARRAY; + this.state = VALUE; + }else if(token === RIGHT_BRACE){ + if (this.mode === OBJECT) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else if(token === RIGHT_BRACKET){ + if (this.mode === ARRAY) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else{ + return this.parseError(token, value); } - return fn.apply(this, arguments); + }else if(this.state === KEY){ + if (token === STRING) { + this.key = value; + this.state = COLON; + } else if (token === RIGHT_BRACE) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else if(this.state === COLON){ + if (token === COLON) { this.state = VALUE; } + else { return this.parseError(token, value); } + }else if(this.state === COMMA){ + if (token === COMMA) { + if (this.mode === ARRAY) { this.key++; this.state = VALUE; } + else if (this.mode === OBJECT) { this.state = KEY; } + + } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else{ + return this.parseError(token, value); } +}; - return deprecated; -} +Parser.C = C; -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ +module.exports = Parser; -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} +}).call(this,require("buffer").Buffer) +},{"buffer":9}],46:[function(require,module,exports){ +var encodings = require('./lib/encodings'); -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],91:[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. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) +module.exports = Codec; - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') +function Codec(opts){ + this.opts = opts || {}; + this.encodings = encodings; +} - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) +Codec.prototype._encoding = function(encoding){ + if (typeof encoding == 'string') encoding = encodings[encoding]; + if (!encoding) encoding = encodings.id; + return encoding; +}; - return wrapper +Codec.prototype._keyEncoding = function(opts, batchOpts){ + return this._encoding(batchOpts && batchOpts.keyEncoding + || opts && opts.keyEncoding + || this.opts.keyEncoding); +}; - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) - } - return ret - } -} +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)); +}; -},{}],92:[function(require,module,exports){ -module.exports = extend +Codec.prototype.encodeKey = function(key, opts, batchOpts){ + return this._keyEncoding(opts, batchOpts).encode(key); +}; -var hasOwnProperty = Object.prototype.hasOwnProperty; +Codec.prototype.encodeValue = function(value, opts, batchOpts){ + return this._valueEncoding(opts, batchOpts).encode(value); +}; -function extend() { - var target = {} +Codec.prototype.decodeKey = function(key, opts){ + return this._keyEncoding(opts).decode(key); +}; - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] +Codec.prototype.decodeValue = function(value, opts){ + return this._valueEncoding(opts).decode(value); +}; - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } +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) + }; + if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'; + if (_op.prefix) op.prefix = _op.prefix; + if ('value' in _op) { + op.value = self.encodeValue(_op.value, opts, _op); + if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'; } + return op; + }); +}; - return target -} - -},{}],93:[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 -const CalculateEntireResultSet = require('./lib/CalculateEntireResultSet.js').CalculateEntireResultSet -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 -const MergeOrConditions = require('./lib/MergeOrConditions.js').MergeOrConditions -const Readable = require('stream').Readable -const ScoreDocsOnField = require('./lib/ScoreDocsOnField.js').ScoreDocsOnField -const ScoreTopScoringDocsTFIDF = require('./lib/ScoreTopScoringDocsTFIDF.js').ScoreTopScoringDocsTFIDF -const SortTopScoringDocs = require('./lib/SortTopScoringDocs.js').SortTopScoringDocs -const bunyan = require('bunyan') -const levelup = require('levelup') -const matcher = require('./lib/matcher.js') -const siUtil = require('./lib/siUtil.js') - -const initModule = function (err, Searcher, moduleReady) { - Searcher.bucketStream = function (q) { - q = siUtil.getQueryDefaults(q) - const s = new Readable({ objectMode: true }) - q.query.forEach(function (clause) { - s.push(clause) - }) - s.push(null) - return s - .pipe(new CalculateResultSetPerClause(Searcher.options, q.filter || {})) - .pipe(new CalculateEntireResultSet(Searcher.options)) - .pipe(new CalculateBuckets(Searcher.options, q.filter || {}, q.buckets)) - } +var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']; - Searcher.categoryStream = function (q) { - q = siUtil.getQueryDefaults(q) - const s = new Readable({ objectMode: true }) - q.query.forEach(function (clause) { - s.push(clause) - }) - s.push(null) - return s - .pipe(new CalculateResultSetPerClause(Searcher.options, q.filter || {})) - .pipe(new CalculateEntireResultSet(Searcher.options)) - .pipe(new CalculateCategories(Searcher.options, q)) - } +Codec.prototype.encodeLtgt = function(ltgt){ + var self = this; + var ret = {}; + Object.keys(ltgt).forEach(function(key){ + ret[key] = ltgtKeys.indexOf(key) > -1 + ? self.encodeKey(ltgt[key], ltgt) + : ltgt[key] + }); + return ret; +}; - Searcher.classify = function (ops) { - return new Classify(Searcher, ops) - } +Codec.prototype.createStreamDecoder = function(opts){ + var self = this; - Searcher.close = function (callback) { - Searcher.options.indexes.close(function (err) { - while (!Searcher.options.indexes.isClosed()) { - Searcher.options.log.debug('closing...') - } - if (Searcher.options.indexes.isClosed()) { - Searcher.options.log.debug('closed...') - callback(err) - } - }) + if (opts.keys && opts.values) { + return function(key, value){ + return { + key: self.decodeKey(key, opts), + value: self.decodeValue(value, opts) + }; + }; + } else if (opts.keys) { + return function(key) { + return self.decodeKey(key, opts); + }; + } else if (opts.values) { + return function(_, value){ + return self.decodeValue(value, opts); + } + } else { + return function(){}; } +}; - 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)) - } +Codec.prototype.keyAsBuffer = function(opts){ + return this._keyEncoding(opts).buffer; +}; - Searcher.get = function (docIDs) { - var s = new Readable({ objectMode: true }) - docIDs.forEach(function (id) { - s.push(id) - }) - s.push(null) - return s.pipe(new FetchDocsFromDB(Searcher.options)) - } +Codec.prototype.valueAsBuffer = function(opts){ + return this._valueEncoding(opts).buffer; +}; - Searcher.fieldNames = function () { - return Searcher.options.indexes.createReadStream({ - gte: 'FIELD', - lte: 'FIELD' - }) - } - Searcher.match = function (q) { - return matcher.match(q, Searcher.options) - } +},{"./lib/encodings":47}],47:[function(require,module,exports){ +(function (Buffer){ +exports.utf8 = exports['utf-8'] = { + encode: function(data){ + return isBinary(data) + ? data + : String(data); + }, + decode: function(data){ + return typeof data === 'string' + ? data + : String(data) + }, + buffer: false, + type: 'utf8' +}; - Searcher.dbReadStream = function () { - return Searcher.options.indexes.createReadStream() - } +exports.json = { + encode: JSON.stringify, + decode: JSON.parse, + buffer: false, + type: 'json' +}; - Searcher.search = function (q) { - q = siUtil.getQueryDefaults(q) - const s = new Readable({ objectMode: true }) - q.query.forEach(function (clause) { - s.push(clause) - }) - s.push(null) - if (q.sort) { - return 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)) - } else { - return 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)) - } - } +exports.binary = { + encode: function(data){ + return isBinary(data) + ? data + : new Buffer(data); + }, + decode: identity, + buffer: true, + type: 'binary' +}; - // TODO: seriously needs a rewrite - Searcher.scan = function (q) { - q = siUtil.getQueryDefaults(q) - // just make this work for a simple one clause AND - // TODO: add filtering, NOTting, multi-clause AND - var s = new Readable({ objectMode: true }) - s.push('init') - s.push(null) - return s - .pipe(new GetIntersectionStream(Searcher.options, - siUtil.getKeySet( - q.query[0].AND, - Searcher.options.keySeparator - ))) - .pipe(new FetchDocsFromDB(Searcher.options)) - } +exports.none = { + encode: identity, + decode: identity, + buffer: false, + type: 'id' +}; - Searcher.totalHits = function (q, callback) { - q = siUtil.getQueryDefaults(q) - const s = new Readable({ objectMode: true }) - 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) - }) - } +exports.id = exports.none; - return moduleReady(err, Searcher) -} +var bufferEncodings = [ + 'hex', + 'ascii', + 'base64', + 'ucs2', + 'ucs-2', + 'utf16le', + 'utf-16le' +]; -const getOptions = function (options, done) { - var Searcher = {} - Searcher.options = Object.assign({}, { - deletable: true, - fieldedSearch: true, - store: true, - indexPath: 'si', - keySeparator: '○', - logLevel: 'error', - nGramLength: 1, - nGramSeparator: ' ', - separator: /[|' .,\-|(\n)]+/, - stopwords: [] - }, options) - Searcher.options.log = bunyan.createLogger({ - name: 'search-index', - level: options.logLevel - }) - if (!options.indexes) { - levelup(Searcher.options.indexPath || 'si', { - valueEncoding: 'json' - }, function (err, db) { - Searcher.options.indexes = db - return done(err, Searcher) - }) - } else { - return done(null, Searcher) - } +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: true, + type: type + }; +}); + +function identity(value){ + return value; } -module.exports = function (givenOptions, moduleReady) { - getOptions(givenOptions, function (err, Searcher) { - initModule(err, Searcher, moduleReady) - }) +function isBinary(data){ + return data === undefined + || data === null + || Buffer.isBuffer(data); } -},{"./lib/AvailableFields.js":94,"./lib/CalculateBuckets.js":95,"./lib/CalculateCategories.js":96,"./lib/CalculateEntireResultSet.js":97,"./lib/CalculateResultSetPerClause.js":98,"./lib/CalculateTopScoringDocs.js":99,"./lib/CalculateTotalHits.js":100,"./lib/Classify.js":101,"./lib/FetchDocsFromDB.js":102,"./lib/FetchStoredDoc.js":103,"./lib/GetIntersectionStream.js":104,"./lib/MergeOrConditions.js":105,"./lib/ScoreDocsOnField.js":106,"./lib/ScoreTopScoringDocsTFIDF.js":107,"./lib/SortTopScoringDocs.js":108,"./lib/matcher.js":109,"./lib/siUtil.js":110,"bunyan":111,"levelup":138,"stream":223}],94:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') +}).call(this,require("buffer").Buffer) +},{"buffer":9}],48:[function(require,module,exports){ +/* Copyright (c) 2012-2017 LevelUP contributors + * See list at + * MIT License + * + */ -const AvailableFields = function (options) { - this.options = options - Transform.call(this, { objectMode: true }) -} -exports.AvailableFields = AvailableFields -util.inherits(AvailableFields, Transform) -AvailableFields.prototype._transform = function (field, encoding, end) { - this.push(field.key.split(this.options.keySeparator)[1]) - return end() -} +var createError = require('errno').create + , LevelUPError = createError('LevelUPError') + , NotFoundError = createError('NotFoundError', LevelUPError) -},{"stream":223,"util":229}],95:[function(require,module,exports){ -const _intersection = require('lodash.intersection') -const _uniq = require('lodash.uniq') -const Transform = require('stream').Transform -const util = require('util') +NotFoundError.prototype.notFound = true +NotFoundError.prototype.status = 404 -const CalculateBuckets = function (options, filter, requestedBuckets) { - this.buckets = requestedBuckets || [] - this.filter = filter - this.options = options - Transform.call(this, { objectMode: true }) -} -exports.CalculateBuckets = CalculateBuckets -util.inherits(CalculateBuckets, Transform) -CalculateBuckets.prototype._transform = function (mergedQueryClauses, encoding, end) { - const that = this - const sep = this.options.keySeparator - var bucketsProcessed = 0 - that.buckets.forEach(function (bucket) { - const gte = 'DF' + sep + bucket.field + sep + bucket.gte - const 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) - if (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) - if (++bucketsProcessed === that.buckets.length) { - return end() - } - }) - }) +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) } -},{"lodash.intersection":141,"lodash.uniq":145,"stream":223,"util":229}],96:[function(require,module,exports){ -const _intersection = require('lodash.intersection') -const Transform = require('stream').Transform -const util = require('util') +},{"errno":35}],49:[function(require,module,exports){ +var inherits = require('inherits'); +var Readable = require('readable-stream').Readable; +var extend = require('xtend'); +var EncodingError = require('level-errors').EncodingError; -const CalculateCategories = function (options, q) { - var category = q.category || [] - category.values = [] // breaky line - this.offset = +q.offset - this.pageSize = +q.pageSize - this.category = category - this.options = options - this.query = q.query - Transform.call(this, { objectMode: true }) +module.exports = ReadStream; +inherits(ReadStream, Readable); + +function ReadStream(iterator, options){ + if (!(this instanceof ReadStream)) return new ReadStream(iterator, options); + Readable.call(this, extend(options, { + objectMode: true + })); + this._iterator = iterator; + this._destroyed = false; + this._decoder = null; + if (options && options.decoder) this._decoder = options.decoder; + this.on('end', this._cleanup.bind(this)); } -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 - const that = this - const gte = 'DF' + sep + this.category.field + sep - const lte = 'DF' + sep + this.category.field + sep + sep - this.category.values = this.category.values || [] - var i = this.offset + this.pageSize - var j = 0 - const rs = that.options.indexes.createReadStream({gte: gte, lte: lte}) - rs.on('data', function (data) { - // page not yet reached - if (that.offset > j++) return - var IDSet = _intersection(data.value, mergedQueryClauses.set) - if (IDSet.length > 0) { // make this optional - var key = data.key.split(sep)[2] - var value = IDSet.length - if (that.category.set) { - value = IDSet - } - var result = { - key: key, - value: value - } - // set filter: true on queries with a single OR clause - if (that.query.length === 1) { - try { - if (that.query[0].AND[that.category.field].indexOf(key) > -1) { - result.filter = true - } - } catch (e) {} - } - // page size exceeded - if (i-- > that.offset) { - that.push(result) - } else { - rs.destroy() + +ReadStream.prototype._read = function(){ + var self = this; + if (this._destroyed) return; + + this._iterator.next(function(err, key, value){ + if (self._destroyed) return; + if (err) return self.emit('error', err); + if (key === undefined && value === undefined) { + self.push(null); + } else { + if (!self._decoder) return self.push({ key: key, value: value }); + + try { + var value = self._decoder(key, value); + } catch (err) { + self.emit('error', new EncodingError(err)); + self.push(null); + return; } + self.push(value); } - }).on('close', function () { - return end() - }) + }); +}; + +ReadStream.prototype.destroy = +ReadStream.prototype._cleanup = function(){ + var self = this; + if (this._destroyed) return; + this._destroyed = true; + + this._iterator.end(function(err){ + if (err) return self.emit('error', err); + self.emit('close'); + }); +}; + + +},{"inherits":40,"level-errors":48,"readable-stream":56,"xtend":159}],50:[function(require,module,exports){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +},{}],51:[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 duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +module.exports = Duplex; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; } +/**/ + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; +}); + +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); -},{"lodash.intersection":141,"stream":223,"util":229}],97:[function(require,module,exports){ -const Transform = require('stream').Transform -const _union = require('lodash.union') -const util = require('util') + Readable.call(this, options); + Writable.call(this, options); -const CalculateEntireResultSet = function (options) { - this.options = options - this.setSoFar = [] - Transform.call(this, { objectMode: true }) -} -exports.CalculateEntireResultSet = CalculateEntireResultSet -util.inherits(CalculateEntireResultSet, Transform) -CalculateEntireResultSet.prototype._transform = function (queryClause, encoding, end) { - this.setSoFar = _union(queryClause.set, this.setSoFar) - return end() -} -CalculateEntireResultSet.prototype._flush = function (end) { - this.push({ - set: this.setSoFar - }) - return end() + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); } -},{"lodash.union":144,"stream":223,"util":229}],98:[function(require,module,exports){ -const Transform = require('stream').Transform -const _difference = require('lodash.difference') -const _intersection = require('lodash.intersection') -const _spread = require('lodash.spread') -const siUtil = require('./siUtil.js') -const util = require('util') +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; -const CalculateResultSetPerClause = function (options) { - this.options = options - Transform.call(this, { objectMode: true }) + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); } -exports.CalculateResultSetPerClause = CalculateResultSetPerClause -util.inherits(CalculateResultSetPerClause, Transform) -CalculateResultSetPerClause.prototype._transform = function (queryClause, encoding, end) { - const sep = this.options.keySeparator - const that = this - const frequencies = [] - var NOT = function (includeResults) { - const bigIntersect = _spread(_intersection) - var include = bigIntersect(includeResults) - // if there are no NOT conditions, simply end() - if (siUtil.getKeySet(queryClause.NOT, sep).length === 0) { - that.push({ - queryClause: queryClause, - set: include, - termFrequencies: frequencies, - BOOST: queryClause.BOOST || 0 - }) - return end() - } else { - // if there ARE "NOT"-conditions, remove all IDs specified by NOT - var i = 0 - var 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; i < data.value.length; i++) { - excludeSet[data.value[i]] = 1 - } - }) - .on('error', function (err) { - that.options.log.debug(err) - }) - .on('end', function () { - var exclude = Object.keys(excludeSet) - excludeResults.push(exclude.sort()) - if (++i === siUtil.getKeySet(queryClause.NOT, sep).length) { - excludeResults.forEach(function (excludeSet) { - include = _difference(include, excludeSet) - }) - that.push({ - queryClause: queryClause, - set: include, - termFrequencies: frequencies, - BOOST: queryClause.BOOST || 0 - }) - return end() - } - }) - }) - } + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); } - // Get all of the IDs in the AND conditions - var IDSets = [] - siUtil.getKeySet(queryClause.AND, sep).forEach(function (item) { - var includeSet = {} - var setLength = 0 - that.options.indexes.createReadStream({gte: item[0], lte: item[1]}) - .on('data', function (data) { - setLength += data.value.length - for (var i = 0; i < data.value.length; i++) { - includeSet[data.value[i]] = 1 - } - }) - .on('error', function (err) { - that.options.log.debug(err) - }) - .on('end', function () { - var include = Object.keys(includeSet) - frequencies.push({ - gte: item[0].split(sep)[1] + sep + item[0].split(sep)[2], - lte: item[1].split(sep)[1] + sep + item[1].split(sep)[2], - tf: include.length, // actual term frequency across docs - setLength: setLength // number of array elements that need to be traversed - }) - IDSets.push(include.sort()) - if (IDSets.length === siUtil.getKeySet(queryClause.AND, sep).length) { - NOT(IDSets) - } - }) - }) } -},{"./siUtil.js":110,"lodash.difference":140,"lodash.intersection":141,"lodash.spread":143,"stream":223,"util":229}],99:[function(require,module,exports){ -const Transform = require('stream').Transform -const _sortedIndexOf = require('lodash.sortedindexof') -const util = require('util') +}).call(this,require('_process')) +},{"./_stream_readable":53,"./_stream_writable":55,"_process":85,"core-util-is":11,"inherits":40}],52:[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. -const CalculateTopScoringDocs = function (options, seekLimit) { - this.options = options - this.seekLimit = seekLimit - Transform.call(this, { objectMode: true }) -} -exports.CalculateTopScoringDocs = CalculateTopScoringDocs -util.inherits(CalculateTopScoringDocs, Transform) -CalculateTopScoringDocs.prototype._transform = function (clauseSet, encoding, end) { - const sep = this.options.keySeparator - // clauseSet = JSON.parse(clauseSet) - const that = this +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. - const lowestFrequency = clauseSet.termFrequencies.sort(function (a, b) { - return a.setLength - b.setLength - })[0] +module.exports = PassThrough; - const gte = 'TF' + sep + lowestFrequency.gte - const lte = 'TF' + sep + lowestFrequency.lte + sep +var Transform = require('./_stream_transform'); - // walk down the DF array of lowest frequency hit until (offset + - // pagesize) hits have been found +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - var topScoringDocs = [] - that.options.indexes.createReadStream({gte: gte, lte: lte}) - .on('data', function (data) { - var intersections = [] - // Do intersection and pagination cutoffs here- only push - // results that are in the resultset - for (var i = 0 - ; ((i < data.value.length) && (intersections.length < that.seekLimit)); i++) { - if (_sortedIndexOf(clauseSet.set, data.value[i][1]) !== -1) { - intersections.push(data.value[i]) - } - } - topScoringDocs = topScoringDocs.concat(intersections) - }) - .on('error', function (err) { - that.options.log.debug(err) - }) - .on('end', function () { - // fetch document vectors for the highest scores and work out - // complete score for each selected doc. - clauseSet['topScoringDocs'] = topScoringDocs - that.push(clauseSet) - return end() - }) +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); } -},{"lodash.sortedindexof":142,"stream":223,"util":229}],100:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; + +},{"./_stream_transform":54,"core-util-is":11,"inherits":40}],53:[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. + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events').EventEmitter; + +/**/ +if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +var Stream = require('stream'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ -const CalculateTotalHits = function (options, filter, requestedBuckets) { - this.buckets = requestedBuckets || [] - this.filter = filter - this.options = options - Transform.call(this, { objectMode: true }) -} -exports.CalculateTotalHits = CalculateTotalHits -util.inherits(CalculateTotalHits, Transform) -CalculateTotalHits.prototype._transform = function (mergedQueryClauses, encoding, end) { - this.push(mergedQueryClauses.set.length) - end() -} +var StringDecoder; -},{"stream":223,"util":229}],101:[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) +/**/ +var debug = require('util'); +if (debug && debug.debuglog) { + debug = debug.debuglog('stream'); +} else { + debug = function () {}; } +/**/ -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(Readable, Stream); -util.inherits(Classify, Transform) +function ReadableState(options, stream) { + var Duplex = require('./_stream_duplex'); -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() - }) -} + options = options || {}; -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() - }) -} + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; -},{"ngraminator":146,"stream":223,"util":229}],102:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; -const FetchDocsFromDB = function (options) { - this.options = options - Transform.call(this, { objectMode: true }) -} -exports.FetchDocsFromDB = FetchDocsFromDB -util.inherits(FetchDocsFromDB, Transform) -FetchDocsFromDB.prototype._transform = function (line, encoding, end) { - const sep = this.options.keySeparator - const that = this - this.options.indexes.get('DOCUMENT' + sep + line.toString() + sep, function (err, doc) { - if (!err) { - that.push(doc) - } - end() - }) -} + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; -},{"stream":223,"util":229}],103:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') + // 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. + this.sync = true; -const FetchStoredDoc = function (options) { - this.options = options - Transform.call(this, { objectMode: true }) -} -exports.FetchStoredDoc = FetchStoredDoc -util.inherits(FetchStoredDoc, Transform) -FetchStoredDoc.prototype._transform = function (doc, encoding, end) { - const sep = this.options.keySeparator - var that = this - // doc = JSON.parse(doc) - that.options.indexes.get('DOCUMENT' + sep + doc.id + sep, function (err, stored) { - if (err) { - that.options.log.debug(err) - } - doc.document = stored - that.push(doc) - return end() - }) -} + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; -},{"stream":223,"util":229}],104:[function(require,module,exports){ -const Transform = require('stream').Transform -const iats = require('intersect-arrays-to-stream') -const util = require('util') -// Make a Transform stream stage to get an intersection stream -const GetIntersectionStream = function (options, ANDKeys) { - this.ANDKeys = ANDKeys - this.options = options - Transform.call(this, { objectMode: true }) -} -exports.GetIntersectionStream = GetIntersectionStream -util.inherits(GetIntersectionStream, Transform) -GetIntersectionStream.prototype._transform = function (line, encoding, end) { - const that = this - var IDSets = [] - this.ANDKeys.forEach(function (item) { - var ANDSetIDs = [] - that.options.indexes.createReadStream({gte: item[0], lte: item[1]}) - .on('data', function (data) { - ANDSetIDs = ANDSetIDs.concat(data.value).sort() - }) - .on('end', function () { - IDSets.push(ANDSetIDs) - if (IDSets.length === that.ANDKeys.length) { - iats.getIntersectionStream(IDSets).on('data', function (data) { - that.push(data) - }).on('end', function () { - end() - }) - } - }) - }) -} + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; -},{"intersect-arrays-to-stream":124,"stream":223,"util":229}],105:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.readableObjectMode; -const MergeOrConditions = function (q) { - this.resultSet = [] - this.q = q - Transform.call(this, { objectMode: true }) -} -exports.MergeOrConditions = MergeOrConditions -util.inherits(MergeOrConditions, Transform) -MergeOrConditions.prototype._transform = function (doc, encoding, end) { - // console.log(JSON.stringify(doc, null, 2)) - this.resultSet.push(doc) - return end() -} -MergeOrConditions.prototype._flush = function (end) { - var that = this - // get rid of OR conditions- merge on doc id - var mergedResultSet = this.resultSet.sort(function (a, b) { - if (a.id < b.id) return 1 - if (a.id > b.id) return -1 - return 0 - }).reduce(function (merged, cur) { - // merge scoring criteria (OR conditions) - var lastDoc = merged[merged.length - 1] - if (merged.length === 0 || (cur.id !== lastDoc.id)) { - merged.push(cur) - } else if (cur.id === lastDoc.id) { - // in case a document is duplicated with different score, save the higher score - lastDoc.scoringCriteria = lastDoc.scoringCriteria.concat(cur.scoringCriteria) - } - return merged - }, []) + // 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'; - // console.log(JSON.stringify(mergedResultSet, null, 2)) + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - // work out the score as an average of all OR conditions. - mergedResultSet.map(function (item) { - // sum up score + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - if (item.scoringCriteria) { - item.score = item.scoringCriteria.reduce(function (acc, val) { - return { score: +acc.score + +val.score } - }, { score: 0 }).score + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - // TODO: possible to score multiple OR conditions by an AVERAGE, or a SUM + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} - // work out average score (score divided by total OR conditions) - item.score = (item.score / item.scoringCriteria.length) - } +function Readable(options) { + var Duplex = require('./_stream_duplex'); - return item - }) + if (!(this instanceof Readable)) + return new Readable(options); - // console.log(JSON.stringify(mergedResultSet, null, 2)) + this._readableState = new ReadableState(options, this); - mergedResultSet.forEach(function (item) { - that.push(item) - }) - return end() + // legacy + this.readable = true; + + Stream.call(this); } -},{"stream":223,"util":229}],106:[function(require,module,exports){ -const Transform = require('stream').Transform -const _sortedIndexOf = require('lodash.sortedindexof') -const util = require('util') +// 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 (util.isString(chunk) && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +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 = false; + if (!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 { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); -const ScoreDocsOnField = function (options, seekLimit, sort) { - this.options = options - this.seekLimit = seekLimit - this.sort = sort - Transform.call(this, { objectMode: true }) -} -exports.ScoreDocsOnField = ScoreDocsOnField -util.inherits(ScoreDocsOnField, Transform) -ScoreDocsOnField.prototype._transform = function (clauseSet, encoding, end) { - const sep = this.options.keySeparator - // clauseSet = JSON.parse(clauseSet) - const that = this + if (!addToFront) + state.reading = false; - const gte = 'TF' + sep + this.sort.field + sep - const lte = 'TF' + sep + this.sort.field + sep + sep + // if we want the data now, just emit it. + 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); - // walk down the DF array of lowest frequency hit until (offset + - // pagesize) hits have been found - that.options.indexes.createReadStream({gte: gte, lte: lte}) - .on('data', function (data) { - for (var i = 0; ((i < data.value.length) && (i < that.seekLimit)); i++) { - if (_sortedIndexOf(clauseSet.set, data.value[i][1]) !== -1) { - that.push({ - id: data.value[i][1], - score: data.value[i][0] - }) - } + if (state.needReadable) + emitReadable(stream); } - }) - .on('end', function () { - return end() - }) -} -},{"lodash.sortedindexof":142,"stream":223,"util":229}],107:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } -const ScoreTopScoringDocsTFIDF = function (options) { - this.options = options - Transform.call(this, { objectMode: true }) + return needMoreData(state); } -exports.ScoreTopScoringDocsTFIDF = ScoreTopScoringDocsTFIDF -util.inherits(ScoreTopScoringDocsTFIDF, Transform) -ScoreTopScoringDocsTFIDF.prototype._transform = function (clause, encoding, end) { - const sep = this.options.keySeparator - const that = this - clause.queryClause.BOOST = clause.queryClause.BOOST || 0 // put this somewhere better - const fields = Object.keys(clause.queryClause.AND) - var i = 0 - // async.each(clause.topScoringDocs, function (docID, nextDocCallback) { - - // if there are no docs, just return - if (clause.topScoringDocs.length === 0) return end() - - clause.topScoringDocs.forEach(function (docID) { - docID = docID[1] - // var vectors = [] - var tfVectors = {} - // for each field in query: - var fieldFetchCounter = 0 - fields.forEach(function (field) { - // get vector for whole document field - that.options.indexes.get( - 'DOCUMENT-VECTOR' + sep + field + sep + docID + sep, function (err, docVector) { - if (err) console.log(err) // TODO something clever with err - // const vector = {} - clause.queryClause.AND[field].forEach(function (token) { - tfVectors[field + sep + token] = docVector[token] - }) - // How to recognise last field? - if (++fieldFetchCounter === fields.length) { - var documentFrequencies = clause.termFrequencies - // All vectors loaded from index: work out score - // At this stage documents are scores per clause- the clauses are merged later - // Work out tfidf per field/token - const tfidf = {} - for (var j = 0; j <= documentFrequencies.length; j++) { - var item = documentFrequencies[j] - if (!item) continue - var tf = +item.tf - var df = +tfVectors[item.gte] // should this be gte? - var idf = Math.log10(1 + (1 / df)) - tfidf[item.gte] = (tf * idf) - } - // Work out tfidf per clause - var score = (Object.keys(tfidf).reduce(function (prev, cur) { - return (tfidf[prev] || 0) + tfidf[cur] - }, 0) / Object.keys(tfidf).length) - - that.push({ - id: docID, - scoringCriteria: [{ - tf: tfVectors, - df: documentFrequencies, - tfidf: tfidf, - boost: +clause.queryClause.BOOST, - score: score - +clause.queryClause.BOOST - }], - score: score - +clause.queryClause.BOOST - }) - if (++i === clause.topScoringDocs.length) { - return end() - } - } - }) - }) - }) + +// 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, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); } -},{"stream":223,"util":229}],108:[function(require,module,exports){ -const Transform = require('stream').Transform -const util = require('util') +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; -const SortTopScoringDocs = function (q) { - this.resultSet = [] - this.q = q - if (q.sort) { - if (q.sort.direction) { - this.sortDirection = q.sort.direction - } - } - Transform.call(this, { objectMode: true }) -} -exports.SortTopScoringDocs = SortTopScoringDocs -util.inherits(SortTopScoringDocs, Transform) -SortTopScoringDocs.prototype._transform = function (doc, encoding, end) { - this.resultSet.push(doc) - return end() -} -SortTopScoringDocs.prototype._flush = function (end) { - const that = this - if (this.sortDirection === 'desc') { - this.resultSet = this.resultSet.sort(function (a, b) { - if (a.score < b.score) return 2 - if (a.score > b.score) return -2 - if (a.id < b.id) return 1 - if (a.id > b.id) return -1 - return 0 - }) +// Don't raise the hwm > 128MB +var MAX_HWM = 0x800000; +function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; } else { - this.resultSet = this.resultSet.sort(function (a, b) { - if (a.score > b.score) return 2 - if (a.score < b.score) return -2 - if (a.id < b.id) return 1 - if (a.id > b.id) return -1 - return 0 - }) + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; } - this.resultSet = this.resultSet.slice(this.q.offset, this.q.offset + this.q.pageSize) - this.resultSet.forEach(function (hit) { - that.push(hit) - }) - return end() + return n; } -},{"stream":223,"util":229}],109:[function(require,module,exports){ -const Readable = require('stream').Readable -const Transform = require('stream').Transform -const util = require('util') +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; -const MatcherStream = function (q, options) { - this.options = options - Transform.call(this, { objectMode: true }) -} -util.inherits(MatcherStream, Transform) -MatcherStream.prototype._transform = function (q, encoding, end) { - const sep = this.options.keySeparator - const 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', 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() - }) -} + if (state.objectMode) + return n === 0 ? 0 : 1; -exports.match = function (q, options) { - var s = new Readable({ objectMode: true }) - q = Object.assign({}, { - beginsWith: '', - field: '*', - threshold: 3, - limit: 10, - type: 'simple' - }, q) - if (q.beginsWith.length < q.threshold) { - s.push(null) - return s + if (isNaN(n) || util.isNull(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; } - s.push(q) - s.push(null) - return s.pipe(new MatcherStream(q, options)) -} + if (n <= 0) + return 0; -},{"stream":223,"util":229}],110:[function(require,module,exports){ -exports.getKeySet = function (clause, sep) { - var keySet = [] - for (var fieldName in clause) { - clause[fieldName].forEach(function (token) { - var gte = token.gte || token - var lte = token.lte || token - keySet.push([ - 'DF' + sep + fieldName + sep + gte, - 'DF' + sep + fieldName + sep + lte - ]) - }) - } - return keySet -} + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); -exports.getQueryDefaults = function (q) { - // if a string is given- turn it into a query - if (typeof q === 'string') { - q = { - query: [{ - AND: {'*': q.split(' ')} - }] - } - } - // Make sure that user query is arrayified - if (q) { - if (q.query) { - if (Object.prototype.toString.call(q.query) !== '[object Array]') { - q.query = [q.query] - } - } - } - // cast strings to int, where possible ("2" = 2) - try { - if (q.offset) q.offset = parseInt(q.offset) - } catch (e) {} - try { - if (q.pageSize) q.pageSize = parseInt(q.pageSize) - } catch (e) {} - return Object.assign({}, { - query: [{ - AND: {'*': ['*']} - }], - offset: 0, - pageSize: 20 - }, q) + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } + + return n; } -},{}],111:[function(require,module,exports){ -arguments[4][7][0].apply(exports,arguments) -},{"../../../../search-index/node_modules/is-buffer/index.js":173,"_process":206,"assert":152,"dup":7,"events":169,"fs":155,"os":204,"safe-json-stringify":148,"stream":223,"util":229}],112:[function(require,module,exports){ -arguments[4][8][0].apply(exports,arguments) -},{"../../../../search-index/node_modules/is-buffer/index.js":173,"dup":8}],113:[function(require,module,exports){ -arguments[4][9][0].apply(exports,arguments) -},{"abstract-leveldown":118,"dup":9,"util":229}],114:[function(require,module,exports){ -arguments[4][10][0].apply(exports,arguments) -},{"../../../search-index/node_modules/is-buffer/index.js":173,"./deferred-iterator":113,"_process":206,"abstract-leveldown":118,"dup":10,"util":229}],115:[function(require,module,exports){ -arguments[4][11][0].apply(exports,arguments) -},{"_process":206,"dup":11}],116:[function(require,module,exports){ -arguments[4][12][0].apply(exports,arguments) -},{"_process":206,"dup":12}],117:[function(require,module,exports){ -arguments[4][13][0].apply(exports,arguments) -},{"../../../../../search-index/node_modules/is-buffer/index.js":173,"./abstract-chained-batch":115,"./abstract-iterator":116,"_process":206,"dup":13,"xtend":149}],118:[function(require,module,exports){ -arguments[4][14][0].apply(exports,arguments) -},{"./abstract-chained-batch":115,"./abstract-iterator":116,"./abstract-leveldown":117,"./is-leveldown":119,"dup":14}],119:[function(require,module,exports){ -arguments[4][15][0].apply(exports,arguments) -},{"./abstract-leveldown":117,"dup":15}],120:[function(require,module,exports){ -arguments[4][31][0].apply(exports,arguments) -},{"dup":31,"prr":122}],121:[function(require,module,exports){ -arguments[4][32][0].apply(exports,arguments) -},{"./custom":120,"dup":32}],122:[function(require,module,exports){ -arguments[4][33][0].apply(exports,arguments) -},{"dup":33}],123:[function(require,module,exports){ -arguments[4][35][0].apply(exports,arguments) -},{"dup":35}],124:[function(require,module,exports){ +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function(n) { + debug('read', n); + var state = this._readableState; + var nOrig = n; -// This module takes an arbitrary number of sorted arrays, and returns -// the intersection as a stream. Arrays need to be sorted in order for -// this to work, but no error will be thrown if they are not sorted + if (!util.isNumber(n) || n > 0) + state.emittedReadable = false; + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) + endReadable(this); + else + emitReadable(this); + return null; + } -var Readable = require('stream').Readable + n = howMuchToRead(n, state); -exports.getIntersectionStream = function(sortedSets) { - var s = new Readable - var i = 0 // identifies array - var ii = [] // identifies index in each array - for (var k = 0; k < sortedSets.length; k++) { - ii[k] = 0 + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) + endReadable(this); + return null; } - //special case: sortedSets is empty - if (sortedSets.length === 0) { - // do nothing - } - //special case: sortedSets contains only one set - else if (sortedSets.length === 1) { - sortedSets[0].forEach(function (item) { - s.push(item + '') - }) - } - //do a normal intersect - else { - var finished = false - // walk along the set of given arrays - while (!finished) { - if (sortedSets[i][ii[i]] < sortedSets[i + 1][ii[i + 1]]) { - ii[i]++ - } - else if (sortedSets[i][ii[i]] > sortedSets[i + 1][ii[i + 1]]) { - ii[i + 1]++ - } - // there is an intersection between two arrays- now see if the - // next array also contains this item - else if ((i + 2) < sortedSets.length) { - ii[i]++ - i++ - } - // All arrays have been traversed and the item was present in each - // array. Therefore this item is in the intersection set. Emit the - // item in the stream - else { - s.push(sortedSets[i][ii[i]] + '') - ii[i]++ - ii[i + 1]++ + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - for (var k = 0; k < sortedSets.length; k++) { - if (ii[k] >= sortedSets[k].length) finished = true - } - i = 0 - } - } + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); } - // indicates the end of the stream - s.push(null) + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } - return s -} + if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } -},{"stream":223}],125:[function(require,module,exports){ -arguments[4][39][0].apply(exports,arguments) -},{"./lib/encodings":126,"dup":39}],126:[function(require,module,exports){ -arguments[4][40][0].apply(exports,arguments) -},{"buffer":156,"dup":40}],127:[function(require,module,exports){ -arguments[4][41][0].apply(exports,arguments) -},{"dup":41,"errno":121}],128:[function(require,module,exports){ -arguments[4][42][0].apply(exports,arguments) -},{"dup":42,"inherits":123,"level-errors":127,"readable-stream":135,"xtend":149}],129:[function(require,module,exports){ -arguments[4][43][0].apply(exports,arguments) -},{"dup":43}],130:[function(require,module,exports){ -arguments[4][44][0].apply(exports,arguments) -},{"./_stream_readable":132,"./_stream_writable":134,"_process":206,"core-util-is":112,"dup":44,"inherits":123}],131:[function(require,module,exports){ -arguments[4][45][0].apply(exports,arguments) -},{"./_stream_transform":133,"core-util-is":112,"dup":45,"inherits":123}],132:[function(require,module,exports){ -arguments[4][46][0].apply(exports,arguments) -},{"./_stream_duplex":130,"_process":206,"buffer":156,"core-util-is":112,"dup":46,"events":169,"inherits":123,"isarray":129,"stream":223,"string_decoder/":136,"util":154}],133:[function(require,module,exports){ -arguments[4][47][0].apply(exports,arguments) -},{"./_stream_duplex":130,"core-util-is":112,"dup":47,"inherits":123}],134:[function(require,module,exports){ -arguments[4][48][0].apply(exports,arguments) -},{"./_stream_duplex":130,"_process":206,"buffer":156,"core-util-is":112,"dup":48,"inherits":123,"stream":223}],135:[function(require,module,exports){ -arguments[4][49][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":130,"./lib/_stream_passthrough.js":131,"./lib/_stream_readable.js":132,"./lib/_stream_transform.js":133,"./lib/_stream_writable.js":134,"_process":206,"dup":49,"stream":223}],136:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"buffer":156,"dup":50}],137:[function(require,module,exports){ -arguments[4][59][0].apply(exports,arguments) -},{"./util":139,"dup":59,"level-errors":127}],138:[function(require,module,exports){ -arguments[4][60][0].apply(exports,arguments) -},{"./batch":137,"./leveldown":154,"./util":139,"_process":206,"deferred-leveldown":114,"dup":60,"events":169,"level-codec":125,"level-errors":127,"level-iterator-stream":128,"prr":147,"util":229,"xtend":149}],139:[function(require,module,exports){ -arguments[4][61][0].apply(exports,arguments) -},{"dup":61,"xtend":149}],140:[function(require,module,exports){ -(function (global){ -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; + var ret; + if (n > 0) + ret = fromList(n, state); + else + ret = null; -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; + if (util.isNull(ret)) { + state.needReadable = true; + n = 0; + } -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + state.length -= n; -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended && state.length === 0) + endReadable(this); -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; + if (!util.isNull(ret)) + this.emit('data', ret); -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + return ret; +}; -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +function chunkInvalid(state, chunk) { + var er = null; + if (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); +function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } } - return func.apply(thisArg, args); + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); } -/** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludes(array, value) { - var length = array ? array.length : 0; - return !!length && baseIndexOf(array, value, 0) > -1; +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); + } } -/** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array ? array.length : 0; +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(function() { + maybeReadMore_(stream, state); + }); } - return false; } -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array ? array.length : 0, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; } - return result; + state.readingMore = false; } -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); +}; - while (++index < length) { - array[offset + index] = values[index]; +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var 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); + break; } - return array; -} + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); } } - return -1; -} -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); + function onend() { + debug('onend'); + dest.end(); } - var index = fromIndex - 1, - length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + 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); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && + (!dest._writableState || dest._writableState.needDrain)) + ondrain(); + } + + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + if (false === ret) { + debug('false write response, pause', + src._readableState.awaitDrain); + src._readableState.awaitDrain++; + src.pause(); } } - return -1; -} -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} -/** - * Checks if a cache value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); -} -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; -} + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); } - return result; + + return dest; +}; + +function pipeOnDrain(src) { + return function() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) + state.awaitDrain--; + if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; } -/** Used for built-in method references. */ -var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + if (!dest) + dest = state.pipes; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); + // slow case. multiple pipe destinations. -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } -/* Built-in method references that are verified to be native. */ -var Map = getNative(root, 'Map'), - nativeCreate = getNative(Object, 'create'); + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + dest.emit('unpipe', this); -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; -} + return this; +}; -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; -} +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; + // If listening to data, and it has not explicitly been paused, + // then call resume to start the flow of data on the next tick. + if (ev === 'data' && false !== this._readableState.flowing) { + this.resume(); } - return hasOwnProperty.call(data, key) ? data[key] : undefined; -} -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); -} + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + var self = this; + process.nextTick(function() { + debug('readable nexttick read 0'); + self.read(0); + }); + } else if (state.length) { + emitReadable(this, state); + } + } + } -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + if (!state.reading) { + debug('resume read 0'); + this.read(0); + } + resume(this, state); + } return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(function() { + resume_(stream, state); + }); + } } -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; +function resume_(stream, state) { + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) + stream.read(0); +} -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; +Readable.prototype.pause = function() { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + if (state.flowing) { + do { + var chunk = stream.read(); + } while (null !== chunk && state.flowing); } } -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; -} +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); + var self = this; + stream.on('end', function() { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); + self.push(null); + }); + + stream.on('data', function(chunk) { + debug('wrapped data'); + if (state.decoder) + chunk = state.decoder.write(chunk); + if (!chunk || !state.objectMode && !chunk.length) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } } - return true; -} -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - return index < 0 ? undefined : data[index][1]; -} + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; -} + return self; +}; -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - if (index < 0) { - data.push([key, value]); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; } else { - data[index][1] = value; - } - return this; -} + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } } -} -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; + return ret; } -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); -} +function endReadable(stream) { + var state = stream._readableState; -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } } -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } } -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; } -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; +}).call(this,require('_process')) +},{"./_stream_duplex":51,"_process":85,"buffer":9,"core-util-is":11,"events":37,"inherits":40,"isarray":50,"stream":147,"string_decoder/":57,"util":7}],54:[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. -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache(values) { - var index = -1, - length = values ? values.length : 0; - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } -} +// 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 +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; -} +module.exports = Transform; -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); -} +var Duplex = require('./_stream_duplex'); -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; -} +util.inherits(Transform, Duplex); -/** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ -function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; } -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - predicate || (predicate = isFlattenable); - result || (result = []); + var cb = ts.writecb; - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; -} + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; + ts.writechunk = null; + ts.writecb = null; + + if (!util.isNullOrUndefined(data)) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); } -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} + Duplex.call(this, options); -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; -} + this._transformState = new TransformState(options, this); -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); -} + // when the writable side finishes, then flush out anything remaining. + var stream = this; -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('prefinish', function() { + if (util.isFunction(this._flush)) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); } -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); -} +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + + +function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; -} + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); -/** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order of result values is determined by the - * order they occur in the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ -var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; -}); + if (ts.transforming) + throw new Error('calling transform done when still transforming'); -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); + return stream.push(null); } -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} +},{"./_stream_duplex":51,"core-util-is":11,"inherits":40}],55:[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. -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} +module.exports = Writable; -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} +/**/ +var Buffer = require('buffer').Buffer; +/**/ -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} +Writable.WritableState = WritableState; + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} +var Stream = require('stream'); -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} +util.inherits(Writable, Stream); -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; } -module.exports = difference; +function WritableState(options, stream) { + var Duplex = require('./_stream_duplex'); -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],141:[function(require,module,exports){ -(function (global){ -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + options = options || {}; -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; -/** `Object#toString` result references. */ -var funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.writableObjectMode; -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + // 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. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + // 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'; -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} + // a flag to see when we're in the middle of a write. + this.writing = false; -/** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludes(array, value) { - var length = array ? array.length : 0; - return !!length && baseIndexOf(array, value, 0) > -1; + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // 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. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.buffer = []; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; } -/** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array ? array.length : 0; +function Writable(options) { + var Duplex = require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; + Stream.call(this); } -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array ? array.length : 0, - result = Array(length); +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); +function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); +} - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; } - return -1; + return valid; } -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (util.isFunction(encoding)) { + cb = encoding; + encoding = null; } - var index = fromIndex - 1, - length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; - } + if (util.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (!util.isFunction(cb)) + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); } - return -1; -} -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} + return ret; +}; -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} +Writable.prototype.cork = function() { + var state = this._writableState; -/** - * Checks if a cache value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); -} + state.corked++; +}; -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; -} +Writable.prototype.uncork = function() { + var state = this._writableState; -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} + if (state.corked) { + state.corked--; + + if (!state.writing && + !state.corked && + !state.finished && + !state.bufferProcessing && + state.buffer.length) + clearBuffer(this, state); } - return result; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + util.isString(chunk)) { + chunk = new Buffer(chunk, encoding); + } + return chunk; } -/** Used for built-in method references. */ -var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (util.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; + state.length += len; -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; + if (state.writing || state.corked) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, false, len, chunk, encoding, cb); -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) + stream._writev(chunk, state.onwrite); + else + stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + state.pendingcb--; + cb(er); + }); + else { + state.pendingcb--; + cb(er); + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} -/** Built-in value references. */ -var splice = arrayProto.splice; +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max, - nativeMin = Math.min; + onwriteStateUpdate(state); -/* Built-in method references that are verified to be native. */ -var Map = getNative(root, 'Map'), - nativeCreate = getNative(Object, 'create'); + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; + if (!finished && + !state.corked && + !state.bufferProcessing && + state.buffer.length) { + clearBuffer(stream, state); + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } } } -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; -} - -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); } -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } - return hasOwnProperty.call(data, key) ? data[key] : undefined; } -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); -} -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; -} +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; + if (stream._writev && state.buffer.length > 1) { + // Fast case, write everything using _writev() + var cbs = []; + for (var c = 0; c < state.buffer.length; c++) + cbs.push(state.buffer[c].callback); -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; + // count the one we are adding, as well. + // TODO(isaacs) clean this up + state.pendingcb++; + doWrite(stream, state, true, state.length, state.buffer, '', function(err) { + for (var i = 0; i < cbs.length; i++) { + state.pendingcb--; + cbs[i](err); + } + }); - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + // Clear buffer + state.buffer = []; + } else { + // Slow case, write chunks one-by-one + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; -} + doWrite(stream, state, false, len, chunk, encoding, cb); -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } + } - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; } - return true; + + state.bufferProcessing = false; } -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); - return index < 0 ? undefined : data[index][1]; -} +}; -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; -} +Writable.prototype._writev = null; -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; + if (util.isFunction(chunk)) { + cb = chunk; + chunk = null; + encoding = null; + } else if (util.isFunction(encoding)) { + cb = encoding; + encoding = null; } - return this; -} - -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; + if (!util.isNullOrUndefined(chunk)) + this.write(chunk, encoding); - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); +}; + + +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); } -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } } -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else + prefinish(stream, state); + } + return need; } -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; } -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); +}).call(this,require('_process')) +},{"./_stream_duplex":51,"_process":85,"buffer":9,"core-util-is":11,"inherits":40,"stream":147}],56:[function(require,module,exports){ +(function (process){ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = require('stream'); +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'); +if (!process.browser && process.env.READABLE_STREAM === 'disable') { + module.exports = require('stream'); } -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; +}).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":147}],57:[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. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (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 true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } } -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache(values) { - var index = -1, - length = values ? values.length : 0; +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } -} + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; -} + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); -} + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; } - } - return -1; -} - -/** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ -function baseIntersection(arrays, iteratee, comparator) { - var includes = comparator ? arrayIncludesWith : arrayIncludes, - length = arrays[0].length, - othLength = arrays.length, - othIndex = othLength, - caches = Array(othLength), - maxLength = Infinity, - result = []; + this.charReceived = this.charLength = 0; - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) - ? new SetCache(othIndex && array) - : undefined; + break; } - array = arrays[0]; - - var index = -1, - seen = caches[0]; - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); - value = (comparator || value !== 0) ? value : 0; - if (!(seen - ? cacheHas(seen, computed) - : includes(result, computed, comparator) - )) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache - ? cacheHas(cache, computed) - : includes(arrays[othIndex], computed, comparator)) - ) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; } - return result; -} -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); -} -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); + // or just emit the charStr + return charStr; +}; - while (++index < length) { - array[index] = args[start + index]; +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} -/** - * Casts `value` to an empty array if it's not an array like object. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ -function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; -} + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; -} + return res; +}; -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); } -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; } -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; } -/** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order of result values is determined by the - * order they occur in the first array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersection([2, 1], [2, 3]); - * // => [2] - */ -var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; -}); +},{"buffer":9}],58:[function(require,module,exports){ +(function (Buffer){ +module.exports = Level -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); +var IDB = require('idb-wrapper') +var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN +var util = require('util') +var Iterator = require('./iterator') +var isBuffer = require('isbuffer') +var xtend = require('xtend') +var toBuffer = require('typedarray-to-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 } -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); +util.inherits(Level, AbstractLevelDOWN) + +Level.prototype._open = function(options, callback) { + var self = this + + var idbOpts = { + storeName: this.location, + autoIncrement: false, + 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) } -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); +Level.prototype._get = function (key, options, callback) { + this.idb.get(key, function (value) { + if (value === undefined) { + // 'NotFound' error, consistent with LevelDOWN API + return callback(new Error('NotFound')) + } + // by default return buffers, unless explicitly told not to + var asBuffer = true + if (options.asBuffer === false) asBuffer = false + if (options.raw) asBuffer = false + if (asBuffer) { + if (value instanceof Uint8Array) value = toBuffer(value) + else value = new Buffer(String(value)) + } + return callback(null, value, key) + }, callback) } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; +Level.prototype._del = function(id, options, callback) { + this.idb.remove(id, callback, callback) } -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +Level.prototype._put = function (key, value, options, callback) { + if (value instanceof ArrayBuffer) { + value = toBuffer(new Uint8Array(value)) + } + var obj = this.convertEncoding(key, value, options) + if (Buffer.isBuffer(obj.value)) { + if (typeof value.toArrayBuffer === 'function') { + obj.value = new Uint8Array(value.toArrayBuffer()) + } else { + obj.value = new Uint8Array(value) + } + } + this.idb.put(obj.key, obj.value, function() { callback() }, callback) } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +Level.prototype.convertEncoding = function(key, value, options) { + if (options.raw) return {key: key, value: value} + if (value) { + var stringed = value.toString() + if (stringed === 'NaN') value = 'NaN' + } + var valEnc = options.valueEncoding + var obj = {key: key, value: value} + if (value && (!valEnc || valEnc !== 'binary')) { + if (typeof obj.value !== 'object') { + obj.value = stringed + } + } + return obj } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +Level.prototype.iterator = function (options) { + if (typeof options !== 'object') options = {} + return new Iterator(this.idb, options) } -module.exports = intersection; +Level.prototype._batch = function (array, options, callback) { + var op + var i + var k + var copiedOp + var currentOp + var modified = [] + + if (array.length === 0) return setTimeout(callback, 0) + + for (i = 0; i < array.length; i++) { + copiedOp = {} + currentOp = array[i] + modified[i] = copiedOp + + var converted = this.convertEncoding(currentOp.key, currentOp.value, options) + currentOp.key = converted.key + currentOp.value = converted.value -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],142:[function(require,module,exports){ -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + for (k in currentOp) { + if (k === 'type' && currentOp[k] == 'del') { + copiedOp[k] = 'remove' + } else { + copiedOp[k] = currentOp[k] + } + } + } -/** Used as references for the maximum length and index of an array. */ -var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + return this.idb.batch(modified, function(){ callback() }, callback) +} -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; +Level.prototype._close = function (callback) { + this.idb.db.close() + callback() +} -/** Used for built-in method references. */ -var objectProto = Object.prototype; +Level.prototype._approximateSize = function (start, end, callback) { + var err = new Error('Not implemented') + if (callback) + return callback(err) -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + throw err +} -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeFloor = Math.floor, - nativeMin = Math.min; +Level.prototype._isBuffer = function (obj) { + return Buffer.isBuffer(obj) +} -/** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ -function baseSortedIndex(array, value, retHighest) { - var low = 0, - high = array ? array.length : low; +Level.destroy = function (db, callback) { + if (typeof db === 'object') { + var prefix = db.IDBOptions.storePrefix || 'IDBWrapper-' + var dbname = db.location + } else { + var prefix = 'IDBWrapper-' + var dbname = db + } + var request = indexedDB.deleteDatabase(prefix + dbname) + request.onsuccess = function() { + callback() + } + request.onerror = function(err) { + callback(err) + } +} + +var checkKeyValue = Level.prototype._checkKeyValue = function (obj, type) { + if (obj === null || obj === undefined) + return new Error(type + ' cannot be `null` or `undefined`') + if (obj === null || obj === undefined) + return new Error(type + ' cannot be `null` or `undefined`') + if (isBuffer(obj) && obj.byteLength === 0) + return new Error(type + ' cannot be an empty ArrayBuffer') + if (String(obj) === '') + return new Error(type + ' cannot be an empty String') + if (obj.length === 0) + return new Error(type + ' cannot be an empty Array') +} + +}).call(this,require("buffer").Buffer) +},{"./iterator":59,"abstract-leveldown":62,"buffer":9,"idb-wrapper":38,"isbuffer":44,"typedarray-to-buffer":153,"util":157,"xtend":69}],59:[function(require,module,exports){ +var util = require('util') +var AbstractIterator = require('abstract-leveldown').AbstractIterator +var ltgt = require('ltgt') - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; +module.exports = Iterator - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; +function Iterator (db, options) { + if (!options) options = {} + this.options = options + AbstractIterator.call(this, db) + this._order = options.reverse ? 'DESC': 'ASC' + this._limit = options.limit + this._count = 0 + this._done = false + var lower = ltgt.lowerBound(options) + var upper = ltgt.upperBound(options) + try { + this._keyRange = lower || upper ? this.db.makeKeyRange({ + lower: lower, + upper: upper, + excludeLower: ltgt.lowerBoundExclusive(options), + excludeUpper: ltgt.upperBoundExclusive(options) + }) : null + } catch (e) { + // The lower key is greater than the upper key. + // IndexedDB throws an error, but we'll just return 0 results. + this._keyRangeError = true } - return baseSortedIndexBy(array, value, identity, retHighest); + this.callback = null } -/** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which invokes `iteratee` for `value` and each element of `array` to compute - * their sort ranking. The iteratee is invoked with one argument; (value). - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ -function baseSortedIndexBy(array, value, iteratee, retHighest) { - value = iteratee(value); +util.inherits(Iterator, AbstractIterator) - var low = 0, - high = array ? array.length : 0, - valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; +Iterator.prototype.createIterator = function() { + var self = this - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - othIsDefined = computed !== undefined, - othIsNull = computed === null, - othIsReflexive = computed === computed, - othIsSymbol = isSymbol(computed); + self.iterator = self.db.iterate(function () { + self.onItem.apply(self, arguments) + }, { + keyRange: self._keyRange, + autoContinue: false, + order: self._order, + onError: function(err) { console.log('horrible error', err) }, + }) +} - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } +// TODO the limit implementation here just ignores all reads after limit has been reached +// it should cancel the iterator instead but I don't know how +Iterator.prototype.onItem = function (value, cursor, cursorTransaction) { + if (!cursor && this.callback) { + this.callback() + this.callback = false + return } - return nativeMin(high, MAX_ARRAY_INDEX); + var shouldCall = true + + if (!!this._limit && this._limit > 0 && this._count++ >= this._limit) + shouldCall = false + + if (shouldCall) this.callback(false, cursor.key, cursor.value) + if (cursor) cursor['continue']() } -/** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 - */ -function sortedIndexOf(array, value) { - var length = array ? array.length : 0; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; - } +Iterator.prototype._next = function (callback) { + if (!callback) return new Error('next() requires a callback argument') + if (this._keyRangeError) return callback() + if (!this._started) { + this.createIterator() + this._started = true } - return -1; + this.callback = callback } -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} +},{"abstract-leveldown":62,"ltgt":80,"util":157}],60:[function(require,module,exports){ +(function (process){ +/* Copyright (c) 2013 Rod Vagg, MIT License */ -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +function AbstractChainedBatch (db) { + this._db = db + this._operations = [] + this._written = false } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); +AbstractChainedBatch.prototype._checkWritten = function () { + if (this._written) + throw new Error('write() already called on this batch') } -/** - * 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; -} +AbstractChainedBatch.prototype.put = function (key, value) { + this._checkWritten() + + var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer) + if (err) throw err + err = this._db._checkKeyValue(value, 'value', this._db._isBuffer) + if (err) throw err -module.exports = sortedIndexOf; + if (!this._db._isBuffer(key)) key = String(key) + if (!this._db._isBuffer(value)) value = String(value) -},{}],143:[function(require,module,exports){ -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + if (typeof this._put == 'function' ) + this._put(key, value) + else + this._operations.push({ type: 'put', key: key, value: value }) -/** Used as the `TypeError` message for "Functions" methods. */ -var FUNC_ERROR_TEXT = 'Expected a function'; + return this +} -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; +AbstractChainedBatch.prototype.del = function (key) { + this._checkWritten() -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; + var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer) + if (err) throw err -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; + if (!this._db._isBuffer(key)) key = String(key) -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + if (typeof this._del == 'function' ) + this._del(key) + else + this._operations.push({ type: 'del', key: key }) -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + return this +} -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; +AbstractChainedBatch.prototype.clear = function () { + this._checkWritten() -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; + this._operations = [] -/** - * 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); + if (typeof this._clear == 'function' ) + this._clear() + + return this } -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; +AbstractChainedBatch.prototype.write = function (options, callback) { + this._checkWritten() - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} + if (typeof options == 'function') + callback = options + if (typeof callback != 'function') + throw new Error('write() requires a callback argument') + if (typeof options != 'object') + options = {} -/** Used for built-in method references. */ -var objectProto = Object.prototype; + this._written = true -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + if (typeof this._write == 'function' ) + return this._write(callback) -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; + if (typeof this._db._batch == 'function') + return this._db._batch(this._operations, options, callback) -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); + process.nextTick(callback) +} - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; +module.exports = AbstractChainedBatch +}).call(this,require('_process')) +},{"_process":85}],61:[function(require,module,exports){ +(function (process){ +/* Copyright (c) 2013 Rod Vagg, MIT License */ + +function AbstractIterator (db) { + this.db = db + this._ended = false + this._nexting = false } -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; +AbstractIterator.prototype.next = function (callback) { + var self = this - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; + if (typeof callback != 'function') + throw new Error('next() requires a callback argument') - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; + if (self._ended) + return callback(new Error('cannot call next() after end()')) + if (self._nexting) + return callback(new Error('cannot call next() before previous next() has completed')) + + self._nexting = true + if (typeof self._next == 'function') { + return self._next(function () { + self._nexting = false + callback.apply(null, arguments) + }) } - return result; -} -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); + process.nextTick(function () { + self._nexting = false + callback() + }) } -/** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). - * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' - * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); - * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 - */ -function spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start === undefined ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); +AbstractIterator.prototype.end = function (callback) { + if (typeof callback != 'function') + throw new Error('end() requires a callback argument') + + if (this._ended) + return callback(new Error('end() already called on iterator')) - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); -} + this._ended = true -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} + if (typeof this._end == 'function') + return this._end(callback) -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; + process.nextTick(callback) } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); +module.exports = AbstractIterator + +}).call(this,require('_process')) +},{"_process":85}],62:[function(require,module,exports){ +(function (Buffer,process){ +/* Copyright (c) 2013 Rod Vagg, MIT License */ + +var xtend = require('xtend') + , AbstractIterator = require('./abstract-iterator') + , AbstractChainedBatch = require('./abstract-chained-batch') + +function AbstractLevelDOWN (location) { + if (!arguments.length || location === undefined) + throw new Error('constructor requires at least a location argument') + + if (typeof location != 'string') + throw new Error('constructor requires a location string argument') + + this.location = location } -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; +AbstractLevelDOWN.prototype.open = function (options, callback) { + if (typeof options == 'function') + callback = options + + if (typeof callback != 'function') + throw new Error('open() requires a callback argument') + + if (typeof options != 'object') + options = {} + + if (typeof this._open == 'function') + return this._open(options, callback) + + process.nextTick(callback) } -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; +AbstractLevelDOWN.prototype.close = function (callback) { + if (typeof callback != 'function') + throw new Error('close() requires a callback argument') - return result === result ? (remainder ? result - remainder : result) : 0; + if (typeof this._close == 'function') + return this._close(callback) + + process.nextTick(callback) } -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); +AbstractLevelDOWN.prototype.get = function (key, options, callback) { + var err + + if (typeof options == 'function') + callback = options + + if (typeof callback != 'function') + throw new Error('get() requires a callback argument') + + if (err = this._checkKeyValue(key, 'key', this._isBuffer)) + return callback(err) + + if (!this._isBuffer(key)) + key = String(key) + + if (typeof options != 'object') + options = {} + + if (typeof this._get == 'function') + return this._get(key, options, callback) + + process.nextTick(function () { callback(new Error('NotFound')) }) } -module.exports = spread; +AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { + var err + + if (typeof options == 'function') + callback = options + + if (typeof callback != 'function') + throw new Error('put() requires a callback argument') -},{}],144:[function(require,module,exports){ -(function (global){ -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + if (err = this._checkKeyValue(key, 'key', this._isBuffer)) + return callback(err) -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; + if (err = this._checkKeyValue(value, 'value', this._isBuffer)) + return callback(err) -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; + if (!this._isBuffer(key)) + key = String(key) -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991; + // coerce value to string in node, don't touch it in browser + // (indexeddb can store any JS type) + if (!this._isBuffer(value) && !process.browser) + value = String(value) -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + if (typeof options != 'object') + options = {} -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + if (typeof this._put == 'function') + return this._put(key, value, options, callback) -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; + process.nextTick(callback) +} -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +AbstractLevelDOWN.prototype.del = function (key, options, callback) { + var err -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + if (typeof options == 'function') + callback = options -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); + if (typeof callback != 'function') + throw new Error('del() requires a callback argument') -/** - * 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); -} + if (err = this._checkKeyValue(key, 'key', this._isBuffer)) + return callback(err) -/** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludes(array, value) { - var length = array ? array.length : 0; - return !!length && baseIndexOf(array, value, 0) > -1; -} + if (!this._isBuffer(key)) + key = String(key) -/** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array ? array.length : 0; + if (typeof options != 'object') + options = {} - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; + if (typeof this._del == 'function') + return this._del(key, options, callback) + + process.nextTick(callback) } -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; +AbstractLevelDOWN.prototype.batch = function (array, options, callback) { + if (!arguments.length) + return this._chainedBatch() - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} + if (typeof options == 'function') + callback = options -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); + if (typeof callback != 'function') + throw new Error('batch(array) requires a callback argument') - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; + if (!Array.isArray(array)) + return callback(new Error('batch(array) requires an array argument')) + + if (typeof options != 'object') + options = {} + + var i = 0 + , l = array.length + , e + , err + + for (; i < l; i++) { + e = array[i] + if (typeof e != 'object') + continue + + 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 (e.type == 'put') { + if (err = this._checkKeyValue(e.value, 'value', this._isBuffer)) + return callback(err) } } - return -1; + + if (typeof this._batch == 'function') + return this._batch(array, options, callback) + + process.nextTick(callback) } -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); +//TODO: remove from here, not a necessary primitive +AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) { + if ( start == null + || end == null + || typeof start == 'function' + || typeof end == 'function') { + throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') } - var index = fromIndex - 1, - length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; + if (typeof callback != 'function') + throw new Error('approximateSize() requires a callback argument') + + if (!this._isBuffer(start)) + start = String(start) + + if (!this._isBuffer(end)) + end = String(end) + + if (typeof this._approximateSize == 'function') + return this._approximateSize(start, end, callback) + + process.nextTick(function () { + callback(null, 0) + }) +} + +AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { + var self = this + + options = xtend(options) + + ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) { + if (options[o] && self._isBuffer(options[o]) && options[o].length === 0) + delete options[o] + }) + + options.reverse = !!options.reverse + + // fix `start` so it takes into account gt, gte, lt, lte as appropriate + if (options.reverse && options.lt) + options.start = options.lt + if (options.reverse && options.lte) + options.start = options.lte + if (!options.reverse && options.gt) + options.start = options.gt + if (!options.reverse && options.gte) + options.start = options.gte + + if ((options.reverse && options.lt && !options.lte) + || (!options.reverse && options.gt && !options.gte)) + options.exclusiveStart = true // start should *not* include matching key + + return options } -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; +AbstractLevelDOWN.prototype.iterator = function (options) { + if (typeof options != 'object') + options = {} + + options = this._setupIteratorOptions(options) + + if (typeof this._iterator == 'function') + return this._iterator(options) + + return new AbstractIterator(this) } -/** - * Checks if a cache value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); +AbstractLevelDOWN.prototype._chainedBatch = function () { + return new AbstractChainedBatch(this) } -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; +AbstractLevelDOWN.prototype._isBuffer = function (obj) { + return Buffer.isBuffer(obj) } -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; +AbstractLevelDOWN.prototype._checkKeyValue = function (obj, type) { + + if (obj === null || obj === undefined) + return new Error(type + ' cannot be `null` or `undefined`') + + if (this._isBuffer(obj)) { + if (obj.length === 0) + return new Error(type + ' cannot be an empty Buffer') + } else if (String(obj) === '') + return new Error(type + ' cannot be an empty String') } -/** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ -function setToArray(set) { - var index = -1, - result = Array(set.size); +module.exports.AbstractLevelDOWN = AbstractLevelDOWN +module.exports.AbstractIterator = AbstractIterator +module.exports.AbstractChainedBatch = AbstractChainedBatch - set.forEach(function(value) { - result[++index] = value; - }); - return result; +}).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) +},{"../../../is-buffer/index.js":42,"./abstract-chained-batch":60,"./abstract-iterator":61,"_process":85,"xtend":63}],63:[function(require,module,exports){ +module.exports = extend + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (source.hasOwnProperty(key)) { + target[key] = source[key] + } + } + } + + return target } -/** Used for built-in method references. */ -var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +},{}],64:[function(require,module,exports){ +var hasOwn = Object.prototype.hasOwnProperty; +var toString = Object.prototype.toString; -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; +var isFunction = function (fn) { + var isFunc = (typeof fn === 'function' && !(fn instanceof RegExp)) || toString.call(fn) === '[object Function]'; + if (!isFunc && typeof window !== 'undefined') { + isFunc = fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt; + } + return isFunc; +}; -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; +module.exports = function forEach(obj, fn) { + if (!isFunction(fn)) { + throw new TypeError('iterator must be a function'); + } + var i, k, + isString = typeof obj === 'string', + l = obj.length, + context = arguments.length > 2 ? arguments[2] : null; + if (l === +l) { + for (i = 0; i < l; i++) { + if (context === null) { + fn(isString ? obj.charAt(i) : obj[i], i, obj); + } else { + fn.call(context, isString ? obj.charAt(i) : obj[i], i, obj); + } + } + } else { + for (k in obj) { + if (hasOwn.call(obj, k)) { + if (context === null) { + fn(obj[k], k, obj); + } else { + fn.call(context, obj[k], k, obj); + } + } + } + } +}; + + +},{}],65:[function(require,module,exports){ +module.exports = Object.keys || require('./shim'); + + +},{"./shim":67}],66:[function(require,module,exports){ +var toString = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toString.call(value); + var isArguments = str === '[object Arguments]'; + if (!isArguments) { + isArguments = str !== '[object Array]' + && value !== null + && typeof value === 'object' + && typeof value.length === 'number' + && value.length >= 0 + && toString.call(value.callee) === '[object Function]'; + } + return isArguments; +}; + + +},{}],67:[function(require,module,exports){ +(function () { + "use strict"; + + // modified from https://github.com/kriskowal/es5-shim + var 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; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object', + isFunction = toString.call(object) === '[object Function]', + 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) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(name); + } + } + } + + if (hasDontEnumBug) { + var ctor = object.constructor, + skipConstructor = ctor && ctor.prototype === object; + + forEach(dontEnums, function (dontEnum) { + if (!(skipConstructor && dontEnum === 'constructor') && has.call(object, dontEnum)) { + theKeys.push(dontEnum); + } + }); + } + return theKeys; + }; + + module.exports = keysShim; }()); -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +},{"./foreach":64,"./isArguments":66}],68:[function(require,module,exports){ +module.exports = hasKeys -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +function hasKeys(source) { + return source !== null && + (typeof source === "object" || + typeof source === "function") +} -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); +},{}],69:[function(require,module,exports){ +var Keys = require("object-keys") +var hasKeys = require("./has-keys") -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; +module.exports = extend -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; +function extend() { + var target = {} -/* Built-in method references that are verified to be native. */ -var Map = getNative(root, 'Map'), - Set = getNative(root, 'Set'), - nativeCreate = getNative(Object, 'create'); + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; + if (!hasKeys(source)) { + continue + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + var keys = Keys(source) -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; -} + for (var j = 0; j < keys.length; j++) { + var name = keys[j] + target[name] = source[name] + } + } -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; + return target } -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. +},{"./has-keys":68,"object-keys":65}],70:[function(require,module,exports){ +/* Copyright (c) 2012-2016 LevelUP contributors + * See list at + * MIT License + * */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; -} -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); -} +var util = require('./util') +var WriteError = require('level-errors').WriteError +var getOptions = util.getOptions +var dispatchError = util.dispatchError -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; +function Batch (levelup, codec) { + this._levelup = levelup + this._codec = codec + this.batch = levelup.db.batch() + this.ops = [] + this.length = 0 } -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; +Batch.prototype.put = function (key_, value_, options) { + options = getOptions(options) -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; + var key = this._codec.encodeKey(key_, options) + var value = this._codec.encodeValue(value_, options) - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + try { + this.batch.put(key, value) + } catch (e) { + throw new WriteError(e) } -} -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; + this.ops.push({ type: 'put', key: key, value: value }) + this.length++ + + return this } -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); +Batch.prototype.del = function (key_, options) { + options = getOptions(options) - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); + var key = this._codec.encodeKey(key_, options) + + try { + this.batch.del(key) + } catch (err) { + throw new WriteError(err) } - return true; -} -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); + this.ops.push({ type: 'del', key: key }) + this.length++ - return index < 0 ? undefined : data[index][1]; + return this } -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; +Batch.prototype.clear = function () { + try { + this.batch.clear() + } catch (err) { + throw new WriteError(err) + } + + this.ops = [] + this.length = 0 + + return this } -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); +Batch.prototype.write = function (callback) { + var levelup = this._levelup + var ops = this.ops - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; + try { + this.batch.write(function (err) { + if (err) { return dispatchError(levelup, new WriteError(err), callback) } + levelup.emit('batch', ops) + if (callback) { callback() } + }) + } catch (err) { + throw new WriteError(err) } - return this; } -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; +module.exports = Batch -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. +},{"./util":72,"level-errors":48}],71:[function(require,module,exports){ +(function (process){ +/* Copyright (c) 2012-2016 LevelUP contributors + * See list at + * MIT License + * */ -function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} +var EventEmitter = require('events').EventEmitter +var inherits = require('util').inherits +var deprecate = require('util').deprecate +var extend = require('xtend') +var prr = require('prr') +var DeferredLevelDOWN = require('deferred-leveldown') +var IteratorStream = require('level-iterator-stream') +var Batch = require('./batch') +var Codec = require('level-codec') +var getLevelDOWN = require('./leveldown') +var errors = require('level-errors') +var util = require('./util') + +var WriteError = errors.WriteError +var ReadError = errors.ReadError +var NotFoundError = errors.NotFoundError +var OpenError = errors.OpenError +var EncodingError = errors.EncodingError +var InitializationError = errors.InitializationError +var LevelUPError = errors.LevelUPError + +var getOptions = util.getOptions +var defaultOptions = util.defaultOptions +var dispatchError = util.dispatchError -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; +function getCallback (options, callback) { + return typeof options === 'function' ? options : callback } -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); -} +// Possible LevelUP#_status values: +// - 'new' - newly created, not opened or closed +// - 'opening' - waiting for the database to be opened, post open() +// - 'open' - successfully opened the database, available for use +// - 'closing' - waiting for the database to be closed, post close() +// - 'closed' - database has been successfully closed, should not be +// used except for another open() operation -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); -} +function LevelUP (location, options, callback) { + if (!(this instanceof LevelUP)) { return new LevelUP(location, options, callback) } -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); -} + var error -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; -} + EventEmitter.call(this) + this.setMaxListeners(Infinity) -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; + if (typeof location === 'function') { + options = typeof options === 'object' ? options : {} + options.db = location + location = null + } else if (typeof location === 'object' && typeof location.db === 'function') { + options = location + location = null + } -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache(values) { - var index = -1, - length = values ? values.length : 0; + if (typeof options === 'function') { + callback = options + options = {} + } - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); + if ((!options || typeof options.db !== 'function') && typeof location !== 'string') { + error = new InitializationError( + 'Must provide a location for the database') + if (callback) { + return process.nextTick(function () { + callback(error) + }) + } + throw error } -} -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; -} + options = getOptions(options) + this.options = extend(defaultOptions, options) + this._codec = new Codec(this.options) + this._status = 'new' + // set this.location as enumerable but not configurable or writable + prr(this, 'location', location, 'e') -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); + this.open(callback) } -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; +inherits(LevelUP, EventEmitter) -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } +LevelUP.prototype.open = function (callback) { + var self = this + var dbFactory + var db + + if (this.isOpen()) { + if (callback) { process.nextTick(function () { callback(null, self) }) } + return this } - return -1; -} -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; + if (this._isOpening()) { + return callback && this.once('open', function () { callback(null, self) }) + } - predicate || (predicate = isFlattenable); - result || (result = []); + this.emit('opening') + this._status = 'opening' + this.db = new DeferredLevelDOWN(this.location) - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; + 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) { + return dispatchError(self, new OpenError(err), callback) } + self.db.setDb(db) + self.db = db + self._status = 'open' + if (callback) { callback(null, self) } + self.emit('open') + self.emit('ready') + }) +} + +LevelUP.prototype.close = function (callback) { + var self = this + + if (this.isOpen()) { + this._status = 'closing' + this.db.close(function () { + self._status = 'closed' + self.emit('closed') + if (callback) { callback.apply(null, arguments) } + }) + this.emit('closing') + this.db = new DeferredLevelDOWN(this.location) + } else if (this._status === 'closed' && callback) { + return process.nextTick(callback) + } else if (this._status === 'closing' && callback) { + this.once('closed', callback) + } else if (this._isOpening()) { + this.once('open', function () { + self.close(callback) + }) } - return result; } -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; +LevelUP.prototype.isOpen = function () { + return this._status === 'open' +} + +LevelUP.prototype._isOpening = function () { + return this._status === 'opening' +} + +LevelUP.prototype.isClosed = function () { + return (/^clos/).test(this._status) +} + +function maybeError (db, options, callback) { + if (!db._isOpening() && !db.isOpen()) { + dispatchError(db, new ReadError('Database is not open'), callback) + return true } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); } -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); +function writeError (db, message, callback) { + dispatchError(db, new WriteError(message), callback) +} - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; +function readError (db, message, callback) { + dispatchError(db, new ReadError(message), callback) } -/** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ -function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; +LevelUP.prototype.get = function (key_, options, callback) { + var self = this + var key - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; + callback = getCallback(options, callback) + + if (maybeError(this, options, callback)) { return } + + if (key_ === null || key_ === undefined || typeof callback !== 'function') { + return readError(this, 'get() requires key and callback arguments', callback) } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); + options = util.getOptions(options) + key = this._codec.encodeKey(key_, options) + + options.asBuffer = this._codec.valueAsBuffer(options) + + this.db.get(key, options, function (err, value) { + if (err) { + if ((/notfound/i).test(err) || err.notFound) { + err = new NotFoundError( + 'Key not found in database [' + key_ + ']', err) + } else { + err = new ReadError(err) } - result.push(value); + return dispatchError(self, err, callback) } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); + if (callback) { + try { + value = self._codec.decodeValue(value, options) + } catch (e) { + return callback(new EncodingError(e)) } - result.push(value); + callback(null, value) } - } - return result; + }) } -/** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ -var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); -}; +LevelUP.prototype.put = function (key_, value_, options, callback) { + var self = this + var key + var value -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} + callback = getCallback(options, callback) -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; -} + if (key_ === null || key_ === undefined) { return writeError(this, 'put() requires a key argument', callback) } -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); + if (maybeError(this, options, callback)) { return } + + options = getOptions(options) + key = this._codec.encodeKey(key_, options) + value = this._codec.encodeValue(value_, options) + + this.db.put(key, value, options, function (err) { + if (err) { + return dispatchError(self, new WriteError(err), callback) + } + self.emit('put', key_, value_) + if (callback) { callback() } + }) } -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); +LevelUP.prototype.del = function (key_, options, callback) { + var self = this + var key + + callback = getCallback(options, callback) + + if (key_ === null || key_ === undefined) { return writeError(this, 'del() requires a key argument', callback) } + + if (maybeError(this, options, callback)) { return } + + options = getOptions(options) + key = this._codec.encodeKey(key_, options) + + this.db.del(key, options, function (err) { + if (err) { + return dispatchError(self, new WriteError(err), callback) + } + self.emit('del', key_) + if (callback) { callback() } + }) } -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); +LevelUP.prototype.batch = function (arr_, options, callback) { + var self = this + var arr + + if (!arguments.length) { return new Batch(this, this._codec) } + + callback = getCallback(options, callback) + + if (!Array.isArray(arr_)) { return writeError(this, 'batch() requires an array argument', callback) } + + if (maybeError(this, options, callback)) { return } + + options = getOptions(options) + arr = self._codec.encodeBatch(arr_, options) + arr = arr.map(function (op) { + if (!op.type && op.key !== undefined && op.value !== undefined) { op.type = 'put' } + return op + }) + + this.db.batch(arr, options, function (err) { + if (err) { + return dispatchError(self, new WriteError(err), callback) + } + self.emit('batch', arr_) + if (callback) { callback() } + }) } -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} +LevelUP.prototype.approximateSize = deprecate(function (start_, end_, options, callback) { + var self = this + var start + var end + + callback = getCallback(options, callback) + + options = getOptions(options) + + if (start_ === null || start_ === undefined || end_ === null || + end_ === undefined || typeof callback !== 'function') { + return readError(this, 'approximateSize() requires start, end and callback arguments', callback) } - return ''; -} -/** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.union([2], [1, 2]); - * // => [2, 1] - */ -var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); -}); + start = this._codec.encodeKey(start_, options) + end = this._codec.encodeKey(end_, options) -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} + this.db.approximateSize(start, end, function (err, size) { + if (err) { + return dispatchError(self, new OpenError(err), callback) + } else if (callback) { + callback(null, size) + } + }) +}, 'db.approximateSize() is deprecated. Use db.db.approximateSize() instead') -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +LevelUP.prototype.readStream = +LevelUP.prototype.createReadStream = function (options) { + options = extend({keys: true, values: true}, this.options, options) + + options.keyEncoding = options.keyEncoding + options.valueEncoding = options.valueEncoding + + options = this._codec.encodeLtgt(options) + options.keyAsBuffer = this._codec.keyAsBuffer(options) + options.valueAsBuffer = this._codec.valueAsBuffer(options) + + if (typeof options.limit !== 'number') { options.limit = -1 } + + return new IteratorStream(this.db.iterator(options), extend(options, { + decoder: this._codec.createStreamDecoder(options) + })) } -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +LevelUP.prototype.keyStream = +LevelUP.prototype.createKeyStream = function (options) { + return this.createReadStream(extend(options, { keys: true, values: false })) +} -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); +LevelUP.prototype.valueStream = +LevelUP.prototype.createValueStream = function (options) { + return this.createReadStream(extend(options, { keys: false, values: true })) } -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); +LevelUP.prototype.toString = function () { + return 'LevelUP' } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; +function utilStatic (name) { + return function (location, callback) { + getLevelDOWN()[name](location, callback || function () {}) + } } -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false +module.exports = LevelUP +module.exports.errors = require('level-errors') +module.exports.destroy = deprecate( + utilStatic('destroy'), + 'levelup.destroy() is deprecated. Use leveldown.destroy() instead' +) +module.exports.repair = deprecate( + utilStatic('repair'), + 'levelup.repair() is deprecated. Use leveldown.repair() instead' +) + +}).call(this,require('_process')) +},{"./batch":70,"./leveldown":7,"./util":72,"_process":85,"deferred-leveldown":13,"events":37,"level-codec":46,"level-errors":48,"level-iterator-stream":49,"prr":86,"util":157,"xtend":159}],72:[function(require,module,exports){ +/* Copyright (c) 2012-2016 LevelUP contributors + * See list at + * MIT License + * */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + +var defaultOptions = { + createIfMissing: true, + errorIfExists: false, + keyEncoding: 'utf8', + valueEncoding: 'utf8', + compression: true } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +function getOptions (options) { + if (typeof options === 'string') { options = { valueEncoding: options } } + if (typeof options !== 'object') { options = {} } + return options } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +function dispatchError (db, error, callback) { + typeof callback === 'function' ? callback(error) : db.emit('error', error) } -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. +function isDefined (v) { + return typeof v !== 'undefined' } -module.exports = union; +module.exports = { + defaultOptions: defaultOptions, + getOptions: getOptions, + dispatchError: dispatchError, + isDefined: isDefined +} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],145:[function(require,module,exports){ +},{}],73:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -25378,10 +17847,11 @@ var LARGE_ARRAY_SIZE = 200; var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; +var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ -var funcTag = '[object Function]', +var argsTag = '[object Arguments]', + funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** @@ -25402,6 +17872,26 @@ var freeSelf = typeof self == 'object' && self && self.Object === Object && self /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. @@ -25437,6 +17927,45 @@ function arrayIncludesWith(array, value, comparator) { return false; } +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. @@ -25495,6 +18024,19 @@ function baseIsNaN(value) { return value !== value; } +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + /** * Checks if a cache value for `key` exists. * @@ -25538,23 +18080,6 @@ function isHostObject(value) { return result; } -/** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ -function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; -} - /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, @@ -25589,11 +18114,16 @@ var reIsNative = RegExp('^' + ); /** Built-in value references. */ -var splice = arrayProto.splice; +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'), - Set = getNative(root, 'Set'), nativeCreate = getNative(Object, 'create'); /** @@ -25965,7 +18495,97 @@ function assocIndexOf(array, key) { return length; } } - return -1; + return -1; +} + +/** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ +function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; +} + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; } /** @@ -25985,77 +18605,34 @@ function baseIsNative(value) { } /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. */ -function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; - - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); + while (++index < length) { + array[index] = args[start + index]; } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; } - } - return result; + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; } -/** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ -var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); -}; - /** * Gets the data for `map`. * @@ -26084,6 +18661,18 @@ function getNative(object, key) { return baseIsNative(value) ? value : undefined; } +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} + /** * Checks if `value` is suitable for use as unique object key. * @@ -26129,27 +18718,31 @@ function toSource(func) { } /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each - * element is kept. + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order of result values is determined by the + * order they occur in the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor * @example * - * _.uniq([2, 1, 2]); - * // => [2, 1] + * _.difference([2, 1], [2, 3]); + * // => [1] */ -function uniq(array) { - return (array && array.length) - ? baseUniq(array) +var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; -} +}); /** * Performs a @@ -26160,31 +18753,138 @@ function uniq(array) { * @memberOf _ * @since 4.0.0 * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. * @example * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); + * _.isArrayLikeObject([1, 2, 3]); * // => true * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); + * _.isArrayLikeObject(document.body.children); * // => true * - * _.eq('a', Object('a')); + * _.isArrayLikeObject('abc'); * // => false * - * _.eq(NaN, NaN); - * // => true + * _.isArrayLikeObject(_.noop); + * // => false */ -function eq(value, other) { - return value === other || (value !== value && other !== other); +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); } /** @@ -26211,6 +18911,37 @@ function isFunction(value) { return tag == funcTag || tag == genTag; } +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) @@ -26242,4689 +18973,6503 @@ function isObject(value) { } /** - * This method returns `undefined`. + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". * * @static * @memberOf _ - * @since 2.3.0 - * @category Util + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * - * _.times(2, _.noop); - * // => [undefined, undefined] + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false */ -function noop() { - // No operation performed. +function isObjectLike(value) { + return !!value && typeof value == 'object'; } -module.exports = uniq; +module.exports = difference; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],146:[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 -} - -// 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) - } -} - -},{}],147:[function(require,module,exports){ -arguments[4][33][0].apply(exports,arguments) -},{"dup":33}],148:[function(require,module,exports){ -arguments[4][83][0].apply(exports,arguments) -},{"dup":83}],149:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"dup":92}],150:[function(require,module,exports){ -const bunyan = require('bunyan') -const level = require('levelup') -const down = require('leveldown') -const SearchIndexAdder = require('search-index-adder') -const SearchIndexSearcher = require('search-index-searcher') - -module.exports = function (givenOptions, moduleReady) { - const optionsLoaded = function (err, SearchIndex) { - const siUtil = require('./siUtil.js')(SearchIndex.options) - if (err) return moduleReady(err) - SearchIndex.close = siUtil.close - SearchIndex.countDocs = siUtil.countDocs - getAdder(SearchIndex, adderLoaded) - } +},{}],74:[function(require,module,exports){ +(function (global){ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - const adderLoaded = function (err, SearchIndex) { - if (err) return moduleReady(err) - getSearcher(SearchIndex, searcherLoaded) - } +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; - const searcherLoaded = function (err, SearchIndex) { - if (err) return moduleReady(err) - return moduleReady(err, SearchIndex) - } +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - getOptions(givenOptions, optionsLoaded) -} +/** `Object#toString` result references. */ +var funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; -const getAdder = function (SearchIndex, done) { - SearchIndexAdder(SearchIndex.options, function (err, searchIndexAdder) { - 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 - SearchIndex.del = searchIndexAdder.deleter - SearchIndex.deleteStream = searchIndexAdder.deleteStream - SearchIndex.feed = searchIndexAdder.feed - SearchIndex.flush = searchIndexAdder.flush - done(err, SearchIndex) - }) -} +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; -const getSearcher = function (SearchIndex, done) { - SearchIndexSearcher(SearchIndex.options, function (err, searchIndexSearcher) { - 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 - SearchIndex.scan = searchIndexSearcher.scan - SearchIndex.search = searchIndexSearcher.search - SearchIndex.totalHits = searchIndexSearcher.totalHits - done(err, SearchIndex) - }) -} +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; -const getOptions = function (options, done) { - var SearchIndex = {} - SearchIndex.options = Object.assign({}, { - indexPath: 'si', - keySeparator: '○', - logLevel: 'error' - }, options) - options.log = bunyan.createLogger({ - name: 'search-index', - level: options.logLevel - }) - if (!options.indexes) { - level(SearchIndex.options.indexPath || 'si', { - valueEncoding: 'json', - db: down - }, function (err, db) { - SearchIndex.options.indexes = db - return done(err, SearchIndex) - }) - } else { - return done(null, SearchIndex) - } -} +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; -},{"./siUtil.js":151,"bunyan":157,"leveldown":188,"levelup":201,"search-index-adder":1,"search-index-searcher":93}],151:[function(require,module,exports){ -module.exports = function(siOptions) { - var siUtil = {} +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - siUtil.countDocs = function (callback) { - var count = 0 - const gte = 'DOCUMENT' + siOptions.keySeparator - const lte = 'DOCUMENT' + siOptions.keySeparator + siOptions.keySeparator - siOptions.indexes.createReadStream({gte: gte, lte: lte}) - .on('data', function (data) { - count++ - }) - .on('error', function (err) { - return callback(err, null) - }) - .on('end', function () { - return callback(null, count) - }) - } +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); - siUtil.close = function (callback) { - siOptions.indexes.close(function (err) { - while (!siOptions.indexes.isClosed()) { - //log not always working here- investigate - if (siOptions.log) siOptions.log.info('closing...') - } - if (siOptions.indexes.isClosed()) { - if (siOptions.log) siOptions.log.info('closed...') - callback(err) - } - }) +/** + * 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); +} - return siUtil +/** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludes(array, value) { + var length = array ? array.length : 0; + return !!length && baseIndexOf(array, value, 0) > -1; } -},{}],152:[function(require,module,exports){ -(function (global){ -'use strict'; +/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array ? array.length : 0; -// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; +} -/*! - * The buffer module from node.js, for the browser. +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. * - * @author Feross Aboukhadijeh - * @license MIT + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. */ -function compare(a, b) { - if (a === b) { - return 0; +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); } + return result; +} - var x = a.length; - var y = b.length; +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } } + return -1; +} - if (x < y) { - return -1; +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); } - if (y < x) { - return 1; + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } } - return 0; + return -1; } -function isBuffer(b) { - if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { - return global.Buffer.isBuffer(b); - } - return !!(b != null && b._isBuffer); + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; } -// based on node assert, original notice: +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +/** + * Checks if a cache value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} -var util = require('util/'); -var hasOwn = Object.prototype.hasOwnProperty; -var pSlice = Array.prototype.slice; -var functionsHaveNames = (function () { - return function foo() {}.name === 'foo'; -}()); -function pToString (obj) { - return Object.prototype.toString.call(obj); +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; } -function isView(arrbuf) { - if (isBuffer(arrbuf)) { - return false; - } - if (typeof global.ArrayBuffer !== 'function') { - return false; - } - if (typeof ArrayBuffer.isView === 'function') { - return ArrayBuffer.isView(arrbuf); - } - if (!arrbuf) { - return false; - } - if (arrbuf instanceof DataView) { - return true; - } - if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { - return true; + +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} } - return false; + return result; } -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. -var assert = module.exports = ok; +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; -var regex = /\s*function\s+([^\(\s]*)\s*/; -// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js -function getName(func) { - if (!util.isFunction(func)) { - return; - } - if (functionsHaveNames) { - return func.name; - } - var str = func.toString(); - var match = str.match(regex); - return match && match[1]; -} -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - // try to strip useless frames - var fn_name = getName(stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); - this.stack = out; - } - } -}; +/** Built-in value references. */ +var splice = arrayProto.splice; -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; -function truncate(s, n) { - if (typeof s === 'string') { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} -function inspect(something) { - if (functionsHaveNames || !util.isFunction(something)) { - return util.inspect(something); - } - var rawname = getName(something); - var name = rawname ? ': ' + rawname : ''; - return '[Function' + name + ']'; -} -function getMessage(self) { - return truncate(inspect(self.actual), 128) + ' ' + - self.operator + ' ' + - truncate(inspect(self.expected), 128); -} +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'), + nativeCreate = getNative(Object, 'create'); -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; } -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + return this.has(key) && delete this.__data__[key]; +} -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } -assert.ok = ok; -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } -}; +} -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; +} -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + if (index < 0) { + return false; } -}; - -function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if (isBuffer(actual) && isBuffer(expected)) { - return compare(actual, expected) === 0; + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + return true; +} - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; + return index < 0 ? undefined : data[index][1]; +} - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if ((actual === null || typeof actual !== 'object') && - (expected === null || typeof expected !== 'object')) { - return strict ? actual === expected : actual == expected; +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} - // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance - // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. - } else if (isView(actual) && isView(expected) && - pToString(actual) === pToString(expected) && - !(actual instanceof Float32Array || - actual instanceof Float64Array)) { - return compare(new Uint8Array(actual.buffer), - new Uint8Array(expected.buffer)) === 0; +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else if (isBuffer(actual) !== isBuffer(expected)) { - return false; + if (index < 0) { + data.push([key, value]); } else { - memos = memos || {actual: [], expected: []}; + data[index][1] = value; + } + return this; +} - var actualIndex = memos.actual.indexOf(actual); - if (actualIndex !== -1) { - if (actualIndex === memos.expected.indexOf(expected)) { - return true; - } - } +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; - memos.actual.push(actual); - memos.expected.push(expected); +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; - return objEquiv(actual, expected, strict, memos); + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } } -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; } -function objEquiv(a, b, strict, actualVisitedObjects) { - if (a === null || a === undefined || b === null || b === undefined) - return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) - return a === b; - if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) - return false; - var aIsArgs = isArguments(a); - var bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b, strict); - } - var ka = objectKeys(a); - var kb = objectKeys(b); - var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) - return false; - } - return true; +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + return getMapData(this, key)['delete'](key); +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + getMapData(this, key).set(key, value); + return this; } -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values ? values.length : 0; -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); } } +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } } + return -1; +} - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } +/** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ +function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; - try { - if (actual instanceof expected) { - return true; + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); } - } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; } + array = arrays[0]; - if (Error.isPrototypeOf(expected)) { - return false; - } + var index = -1, + seen = caches[0]; - return expected.call({}, actual) === true; -} + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; -function _tryBlock(block) { - var error; - try { - block(); - } catch (e) { - error = e; + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } } - return error; + return result; } -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (typeof block !== 'function') { - throw new TypeError('"block" argument must be a function'); - } - - if (typeof expected === 'string') { - message = expected; - expected = null; +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; } + var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} - actual = _tryBlock(block); - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); - var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && util.isError(actual); - var isUnexpectedException = !shouldThrow && actual && !expected; + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} - if ((isUnwantedException && - userProvidedMessage && - expectedException(actual, expected)) || - isUnexpectedException) { - fail(actual, expected, 'Got unwanted exception' + message); - } +/** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ +function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; +} - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws(true, block, error, message); -}; +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws(false, block, error, message); -}; +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} -assert.ifError = function(err) { if (err) throw err; }; +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} } - return keys; -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"util/":229}],153:[function(require,module,exports){ -'use strict' + return ''; +} -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray +/** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order of result values is determined by the + * order they occur in the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ +var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; +}); -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); } -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return (b64.length * 3 / 4) - placeHoldersCount(b64) +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); } -function toByteArray (b64) { - var i, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) - - 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; 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 - arr[L++] = tmp & 0xFF - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } - - return arr +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; } -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} +module.exports = intersection; -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],75:[function(require,module,exports){ +(function (global){ +/** + * Lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright JS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; - parts.push(output) +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - return parts.join('') -} +/** `Object#toString` result references. */ +var 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]'; -},{}],154:[function(require,module,exports){ +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; -},{}],155:[function(require,module,exports){ -arguments[4][154][0].apply(exports,arguments) -},{"dup":154}],156:[function(require,module,exports){ -(function (global){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ -/* eslint-disable no-proto */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; -'use strict' +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; -var base64 = require('base64-js') -var ieee754 = require('ieee754') -var isArray = require('isarray') +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; -function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } -} +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); - return that -} +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. * - * The `Uint8Array` prototype remains unmodified. + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; } - return allocUnsafe(this, arg) } - return from(this, arg, encodingOrOffset, length) + return result; } -Buffer.poolSize = 8192 // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr -} +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') + while (++index < length) { + array[offset + index] = values[index]; } + return array; +} - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } } - - return fromObject(that, value) + return false; } /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) + while (++index < n) { + result[index] = iteratee(index); } + return result; } -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; } -function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); } /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; } -function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; } /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; } + /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; } -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; - var actual = that.write(string, encoding) +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); - return that -} +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeKeys = overArg(Object.keys, Object); - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - return that } -function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} - if (that.length === 0) { - return that - } +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} - obj.copy(that, 0, 0, len) - return that +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); +} + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } +} - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; } -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; } - return length | 0 + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; } -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; } -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; } -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; } + return this; +} - if (a === b) return 0 +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; - var x = a.length - var y = b.length +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - - if (x < y) return -1 - if (y < x) return 1 - return 0 } -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; } -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); } -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} - var len = string.length - if (len === 0) return 0 +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; } -Buffer.byteLength = byteLength -function slowToString (encoding, start, end) { - var loweredCase = false +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); } +} - if (end === undefined || end > this.length) { - end = this.length - } +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} - if (end <= 0) { - return '' - } +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; - if (end <= start) { - return '' - } +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} - if (!encoding) encoding = 'utf8' +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) + this.size = data.size; + return result; +} - case 'ascii': - return asciiSlice(this, start, end) +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} - case 'base64': - return base64Slice(this, start, end) +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); } } + return result; } -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; } - return this + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); } -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; } -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' -} + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; } - if (thisEnd === undefined) { - thisEnd = this.length + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } } - if (start >= end) { - return 1 + if (!isSameTag) { + return false; } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); } } - - if (x < y) return -1 - if (y < x) return 1 - return 0 + return result; } -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } + stack.set(array, other); + stack.set(other, array); - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + if (compared !== undefined) { + if (compared) { + continue; } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } - - throw new TypeError('val must be string, number or Buffer') + stack['delete'](array); + stack['delete'](other); + return result; } -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } + return true; - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; } - if (found) return i - } - } - - return -1 -} + bitmask |= COMPARE_UNORDERED_FLAG; -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; } -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; } } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; - if (length > strLen / 2) { - length = strLen / 2 + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } } - return i + stack['delete'](object); + stack['delete'](other); + return result; } -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); } -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; } -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; } else { - encoding = length - length = undefined + delete value[symToStringTag]; } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) } + return result; +} - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); +}; - if (!encoding) encoding = 'utf8' +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + 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; + }; +} - case 'ascii': - return asciiWrite(this, string, offset, length) +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } + return value === proto; } -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); } -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} } + return ''; } -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } +/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ +function isEqual(value, other) { + return baseIsEqual(value, other); +} - res.push(codePoint) - i += bytesPerSequence +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; } - - return decodeCodePointsArray(res) + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; } -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; } -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; } -function hexSlice (buf, start, end) { - var len = buf.length +module.exports = isEqual; - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],76:[function(require,module,exports){ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res -} +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end +/** Used for built-in method references. */ +var objectProto = Object.prototype; - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor = Math.floor, + nativeMin = Math.min; - if (end < start) end = start +/** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ +function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array ? array.length : low; - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } } + return high; } - - return newBuf + return baseSortedIndexBy(array, value, identity, retHighest); } -/* - * Need to make sure that buffer isn't trying to write out of bounds. +/** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } +function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); - return val -} + var low = 0, + high = array ? array.length : 0, + valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } } - - return val + return nativeMin(high, MAX_ARRAY_INDEX); } -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] +/** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ +function sortedIndexOf(array, value) { + var length = array ? array.length : 0; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; } -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); } -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; } -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); } -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) +/** + * 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; } -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) +module.exports = sortedIndexOf; - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 +},{}],77:[function(require,module,exports){ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - if (val >= mul) val -= Math.pow(2, 8 * byteLength) +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; - return val -} +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - if (val >= mul) val -= Math.pow(2, 8 * byteLength) +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - return val -} +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val +/** + * 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); } -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) + while (++index < length) { + array[offset + index] = values[index]; + } + return array; } -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} +/** Used for built-in method references. */ +var objectProto = Object.prototype; -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; } -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) + if (start < 0) { + start = -start > length ? 0 : (length + start); } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF + end = end > length ? length : end; + if (end < 0) { + end += length; } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; - return offset + byteLength + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; } -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); +} - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF +/** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ +function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); } + start = start === undefined ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); - return offset + byteLength + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); } -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); } -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; } -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); } -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; } - return offset + 2 -} - -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; } + return value === value ? value : 0; } -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; } -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; } - return offset + 4 + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); } -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } +module.exports = spread; - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } +},{}],78:[function(require,module,exports){ +(function (global){ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - return offset + byteLength -} +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991; - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - return offset + byteLength -} +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) +/** + * 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 offset + 4 + return func.apply(thisArg, args); } -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') +/** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludes(array, value) { + var length = array ? array.length : 0; + return !!length && baseIndexOf(array, value, 0) > -1; } -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) +/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 + return false; } -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) + while (++index < length) { + array[offset + index] = values[index]; + } + return array; } -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 + return -1; } -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); + } + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; } -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; } -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start +/** + * Checks if a cache value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') + return result; +} - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); - var len = end - start - var i + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; - return len -} +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; - if (end <= start) { - return this - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - if (!val) val = 0 +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } +/** Built-in value references. */ +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; - return this -} +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; -// HELPER FUNCTIONS -// ================ +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'), + Set = getNative(root, 'Set'), + nativeCreate = getNative(Object, 'create'); -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - return str } -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; } -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + return this.has(key) && delete this.__data__[key]; } -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); +} - // valid lead - leadSurrogate = codePoint +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} - continue - } +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} - leadSurrogate = null +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; +} - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); } + return true; +} - return bytes +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; } -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; } -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) + if (index < 0) { + data.push([key, value]); + } else { + data[index][1] = value; } - - return byteArray + return this; } -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - return i } -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":153,"ieee754":171,"isarray":174}],157:[function(require,module,exports){ -(function (Buffer,process){ /** - * Copyright (c) 2017 Trent Mick. - * Copyright (c) 2017 Joyent Inc. - * - * The bunyan logging library for node.js. + * Removes `key` and its value from the map. * - * -*- mode: js -*- - * vim: expandtab:ts=4:sw=4 + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ +function mapCacheDelete(key) { + return getMapData(this, key)['delete'](key); +} -var VERSION = '1.8.10'; - -/* - * Bunyan log format version. This becomes the 'v' field on all log records. - * This will be incremented if there is any backward incompatible change to - * the log record format. Details will be in 'CHANGES.md' (the change log). +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ -var LOG_VERSION = 0; +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} -var xxx = function xxx(s) { // internal dev/debug logging - var args = ['XX' + 'X: '+s].concat( - Array.prototype.slice.call(arguments, 1)); - console.error.apply(this, args); -}; -var xxx = function xxx() {}; // comment out to turn on debug logging +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + getMapData(this, key).set(key, value); + return this; +} +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; -/* - * Runtime environment notes: +/** * - * Bunyan is intended to run in a number of runtime environments. Here are - * some notes on differences for those envs and how the code copes. + * Creates an array cache object to store unique values. * - * - node.js: The primary target environment. - * - NW.js: http://nwjs.io/ An *app* environment that feels like both a - * node env -- it has node-like globals (`process`, `global`) and - * browser-like globals (`window`, `navigator`). My *understanding* is that - * bunyan can operate as if this is vanilla node.js. - * - browser: Failing the above, we sniff using the `window` global - * . - * - browserify: http://browserify.org/ A browser-targetting bundler of - * node.js deps. The runtime is a browser env, so can't use fs access, - * etc. Browserify's build looks for `require()` imports - * to bundle. For some imports it won't be able to handle, we "hide" - * from browserify with `require('frobshizzle' + '')`. - * - Other? Please open issues if things are broken. + * @private + * @constructor + * @param {Array} [values] The values to cache. */ -var runtimeEnv; -if (typeof (process) !== 'undefined' && process.versions) { - if (process.versions.nw) { - runtimeEnv = 'nw'; - } else if (process.versions.node) { - runtimeEnv = 'node'; - } -} -if (!runtimeEnv && typeof (window) !== 'undefined' && - window.window === window) { - runtimeEnv = 'browser'; +function SetCache(values) { + var index = -1, + length = values ? values.length : 0; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } } -if (!runtimeEnv) { - throw new Error('unknown runtime environment'); + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; } +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} -var os, fs, dtrace; -if (runtimeEnv === 'browser') { - os = { - hostname: function () { - return window.location.host; - } - }; - fs = {}; - dtrace = null; -} else { - os = require('os'); - fs = require('fs'); - try { - dtrace = require('dtrace-provider' + ''); - } catch (e) { - dtrace = null; +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; } + } + return -1; } -var util = require('util'); -var assert = require('assert'); -var EventEmitter = require('events').EventEmitter; -var stream = require('stream'); -try { - var safeJsonStringify = require('safe-json-stringify'); -} catch (e) { - safeJsonStringify = null; -} -if (process.env.BUNYAN_TEST_NO_SAFE_JSON_STRINGIFY) { - safeJsonStringify = null; -} +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; -// The 'mv' module is required for rotating-file stream support. -try { - var mv = require('mv' + ''); -} catch (e) { - mv = null; -} + predicate || (predicate = isFlattenable); + result || (result = []); -try { - var sourceMapSupport = require('source-map-support' + ''); -} catch (_) { - sourceMapSupport = null; + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; } - -//---- Internal support stuff +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} /** - * A shallow copy of an object. Bunyan logging attempts to never cause - * exceptions, so this function attempts to handle non-objects gracefully. + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. */ -function objCopy(obj) { - if (obj == null) { // null or undefined - return obj; - } else if (Array.isArray(obj)) { - return obj.slice(); - } else if (typeof (obj) === 'object') { - var copy = {}; - Object.keys(obj).forEach(function (k) { - copy[k] = obj[k]; - }); - return copy; - } else { - return obj; +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; } -var format = util.format; -if (!format) { - // If node < 0.6, then use its `util.format`: - // : - var inspect = util.inspect; - var formatRegExp = /%[sdj%]/g; - format = function format(f) { - if (typeof (f) !== 'string') { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } +/** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function (x) { - if (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; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (x === null || typeof (x) !== 'object') { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; } - return str; - }; + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; } +/** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ +var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); +}; /** - * Gather some caller info 3 stack levels up. - * See . + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. */ -function getCaller3Info() { - if (this === undefined) { - // Cannot access caller info in 'strict' mode. - return; - } - var obj = {}; - var saveLimit = Error.stackTraceLimit; - var savePrepare = Error.prepareStackTrace; - Error.stackTraceLimit = 3; - - Error.prepareStackTrace = function (_, stack) { - var caller = stack[2]; - if (sourceMapSupport) { - caller = sourceMapSupport.wrapCallSite(caller); - } - obj.file = caller.getFileName(); - obj.line = caller.getLineNumber(); - var func = caller.getFunctionName(); - if (func) - obj.func = func; - }; - Error.captureStackTrace(this, getCaller3Info); - this.stack; - - Error.stackTraceLimit = saveLimit; - Error.prepareStackTrace = savePrepare; - return obj; +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } - -function _indent(s, indent) { - if (!indent) indent = ' '; - var lines = s.split(/\r?\n/g); - return indent + lines.join('\n' + indent); +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; } - /** - * Warn about an bunyan processing error. + * Checks if `value` is a flattenable `arguments` object or array. * - * @param msg {String} Message with which to warn. - * @param dedupKey {String} Optional. A short string key for this warning to - * have its warning only printed once. + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ -function _warn(msg, dedupKey) { - assert.ok(msg); - if (dedupKey) { - if (_warned[dedupKey]) { - return; - } - _warned[dedupKey] = true; - } - process.stderr.write(msg + '\n'); -} -function _haveWarned(dedupKey) { - return _warned[dedupKey]; +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); } -var _warned = {}; - - -function ConsoleRawStream() {} -ConsoleRawStream.prototype.write = function (rec) { - if (rec.level < INFO) { - console.log(rec); - } else if (rec.level < WARN) { - console.info(rec); - } else if (rec.level < ERROR) { - console.warn(rec); - } else { - console.error(rec); - } -}; +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} -//---- Levels +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} -var TRACE = 10; -var DEBUG = 20; -var INFO = 30; -var WARN = 40; -var ERROR = 50; -var FATAL = 60; +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} -var levelFromName = { - 'trace': TRACE, - 'debug': DEBUG, - 'info': INFO, - 'warn': WARN, - 'error': ERROR, - 'fatal': FATAL -}; -var nameFromLevel = {}; -Object.keys(levelFromName).forEach(function (name) { - nameFromLevel[levelFromName[name]] = name; +/** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ +var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); -// Dtrace probes. -var dtp = undefined; -var probes = dtrace && {}; - /** - * Resolve a level number, name (upper or lowercase) to a level number value. + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. * - * @param nameOrNum {String|Number} A level name (case-insensitive) or positive - * integer level. - * @api public + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true */ -function resolveLevel(nameOrNum) { - var level; - var type = typeof (nameOrNum); - if (type === 'string') { - level = levelFromName[nameOrNum.toLowerCase()]; - if (!level) { - throw new Error(format('unknown level name: "%s"', nameOrNum)); - } - } else if (type !== 'number') { - throw new TypeError(format('cannot resolve level: invalid arg (%s):', - type, nameOrNum)); - } else if (nameOrNum < 0 || Math.floor(nameOrNum) !== nameOrNum) { - throw new TypeError(format('level is not a positive integer: %s', - nameOrNum)); - } else { - level = nameOrNum; - } - return level; +function eq(value, other) { + return value === other || (value !== value && other !== other); } - -function isWritable(obj) { - if (obj instanceof stream.Writable) { - return true; - } - return typeof (obj.write) === 'function'; +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } - -//---- Logger class - /** - * Create a Logger instance. + * Checks if `value` is classified as an `Array` object. * - * @param options {Object} See documentation for full details. At minimum - * this must include a 'name' string key. Configuration keys: - * - `streams`: specify the logger output streams. This is an array of - * objects with these fields: - * - `type`: The stream type. See README.md for full details. - * Often this is implied by the other fields. Examples are - * 'file', 'stream' and "raw". - * - `level`: Defaults to 'info'. - * - `path` or `stream`: The specify the file path or writeable - * stream to which log records are written. E.g. - * `stream: process.stdout`. - * - `closeOnExit` (boolean): Optional. Default is true for a - * 'file' stream when `path` is given, false otherwise. - * See README.md for full details. - * - `level`: set the level for a single output stream (cannot be used - * with `streams`) - * - `stream`: the output stream for a logger with just one, e.g. - * `process.stdout` (cannot be used with `streams`) - * - `serializers`: object mapping log record field names to - * serializing functions. See README.md for details. - * - `src`: Boolean (default false). Set true to enable 'src' automatic - * field with log call source info. - * All other keys are log record fields. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example * - * An alternative *internal* call signature is used for creating a child: - * new Logger(, [, ]); + * _.isArray([1, 2, 3]); + * // => true * - * @param _childSimple (Boolean) An assertion that the given `_childOptions` - * (a) only add fields (no config) and (b) no serialization handling is - * required for them. IOW, this is a fast path for frequent child - * creation. + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false */ -function Logger(options, _childOptions, _childSimple) { - xxx('Logger start:', options) - if (!(this instanceof Logger)) { - return new Logger(options, _childOptions); - } - - // Input arg validation. - var parent; - if (_childOptions !== undefined) { - parent = options; - options = _childOptions; - if (!(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('options.name (string) is required'); - } - } else { - if (options.name) { - throw new TypeError( - 'invalid options.name: child cannot set logger name'); - } - } - 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 && (typeof (options.serializers) !== 'object' || - Array.isArray(options.serializers))) { - throw new TypeError('invalid options.serializers: must be an object') - } - - EventEmitter.call(this); - - // Fast path for simple child creation. - if (parent && _childSimple) { - // `_isSimpleChild` is a signal to stream close handling that this child - // owns none of its streams. - this._isSimpleChild = true; - - this._level = parent._level; - this.streams = parent.streams; - this.serializers = parent.serializers; - this.src = parent.src; - var fields = this.fields = {}; - var parentFieldNames = Object.keys(parent.fields); - for (var i = 0; i < parentFieldNames.length; i++) { - var name = parentFieldNames[i]; - fields[name] = parent.fields[name]; - } - var names = Object.keys(options); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - fields[name] = options[name]; - } - return; - } - - // Start values. - var self = this; - if (parent) { - this._level = parent._level; - this.streams = []; - for (var i = 0; i < parent.streams.length; i++) { - var s = objCopy(parent.streams[i]); - s.closeOnExit = false; // Don't own parent stream. - this.streams.push(s); - } - this.serializers = objCopy(parent.serializers); - this.src = parent.src; - this.fields = objCopy(parent.fields); - if (options.level) { - this.level(options.level); - } - } else { - this._level = Number.POSITIVE_INFINITY; - this.streams = []; - this.serializers = null; - this.src = false; - this.fields = {}; - } - - if (!dtp && dtrace) { - dtp = dtrace.createDTraceProvider('bunyan'); - - for (var level in levelFromName) { - var probe; - - probes[levelFromName[level]] = probe = - dtp.addProbe('log-' + level, 'char *'); - - // Explicitly add a reference to dtp to prevent it from being GC'd - probe.dtp = dtp; - } - - dtp.enable(); - } - - // Handle *config* options (i.e. options that are not just plain data - // for log records). - if (options.stream) { - self.addStream({ - type: 'stream', - stream: options.stream, - closeOnExit: false, - level: options.level - }); - } else if (options.streams) { - options.streams.forEach(function (s) { - self.addStream(s, options.level); - }); - } else if (parent && options.level) { - this.level(options.level); - } else if (!parent) { - if (runtimeEnv === 'browser') { - /* - * In the browser we'll be emitting to console.log by default. - * Any console.log worth its salt these days can nicely render - * and introspect objects (e.g. the Firefox and Chrome console) - * so let's emit the raw log record. Are there browsers for which - * that breaks things? - */ - self.addStream({ - type: 'raw', - stream: new ConsoleRawStream(), - closeOnExit: false, - level: options.level - }); - } else { - self.addStream({ - type: 'stream', - stream: process.stdout, - closeOnExit: false, - level: options.level - }); - } - } - if (options.serializers) { - self.addSerializers(options.serializers); - } - if (options.src) { - this.src = true; - } - xxx('Logger: ', self) +var isArray = Array.isArray; - // Fields. - // These are the default fields for log records (minus the attributes - // removed in this constructor). To allow storing raw log records - // (unrendered), `this.fields` must never be mutated. Create a copy for - // any changes. - var fields = objCopy(options); - delete fields.stream; - delete fields.level; - delete fields.streams; - delete fields.serializers; - delete fields.src; - if (this.serializers) { - this._applySerializers(fields); - } - if (!fields.hostname && !self.fields.hostname) { - fields.hostname = os.hostname(); - } - if (!fields.pid) { - fields.pid = process.pid; - } - Object.keys(fields).forEach(function (k) { - self.fields[k] = fields[k]; - }); +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); } -util.inherits(Logger, EventEmitter); +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} /** - * Add a stream + * Checks if `value` is a valid array-like length. * - * @param stream {Object}. Object with these fields: - * - `type`: The stream type. See README.md for full details. - * Often this is implied by the other fields. Examples are - * 'file', 'stream' and "raw". - * - `path` or `stream`: The specify the file path or writeable - * stream to which log records are written. E.g. - * `stream: process.stdout`. - * - `level`: Optional. Falls back to `defaultLevel`. - * - `closeOnExit` (boolean): Optional. Default is true for a - * 'file' stream when `path` is given, false otherwise. - * See README.md for full details. - * @param defaultLevel {Number|String} Optional. A level to use if - * `stream.level` is not set. If neither is given, this defaults to INFO. + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false */ -Logger.prototype.addStream = function addStream(s, defaultLevel) { - var self = this; - if (defaultLevel === null || defaultLevel === undefined) { - defaultLevel = INFO; - } +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - s = objCopy(s); +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - // Implicit 'type' from other args. - if (!s.type) { - if (s.stream) { - s.type = 'stream'; - } else if (s.path) { - s.type = 'file' - } - } - s.raw = (s.type === 'raw'); // PERF: Allow for faster check in `_emit`. +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - if (s.level !== undefined) { - s.level = resolveLevel(s.level); - } else { - s.level = resolveLevel(defaultLevel); - } - if (s.level < self._level) { - self._level = s.level; - } +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} - switch (s.type) { - case 'stream': - assert.ok(isWritable(s.stream), - '"stream" stream is not writable: ' + util.inspect(s.stream)); +module.exports = union; - if (!s.closeOnExit) { - s.closeOnExit = false; - } - break; - case 'file': - if (s.reemitErrorEvents === undefined) { - s.reemitErrorEvents = true; - } - if (!s.stream) { - s.stream = fs.createWriteStream(s.path, - {flags: 'a', encoding: 'utf8'}); - if (!s.closeOnExit) { - s.closeOnExit = true; - } - } else { - if (!s.closeOnExit) { - s.closeOnExit = false; - } - } - break; - case 'rotating-file': - assert.ok(!s.stream, - '"rotating-file" stream should not give a "stream"'); - assert.ok(s.path); - assert.ok(mv, '"rotating-file" stream type is not supported: ' - + 'missing "mv" module'); - s.stream = new RotatingFileStream(s); - if (!s.closeOnExit) { - s.closeOnExit = true; - } - break; - case 'raw': - if (!s.closeOnExit) { - s.closeOnExit = false; - } - break; - default: - throw new TypeError('unknown stream type "' + s.type + '"'); - } +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],79:[function(require,module,exports){ +(function (global){ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - if (s.reemitErrorEvents && typeof (s.stream.on) === 'function') { - // TODO: When we have `.close()`, it should remove event - // listeners to not leak Logger instances. - s.stream.on('error', function onStreamError(err) { - self.emit('error', err, s); - }); - } +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; - self.streams.push(s); - delete self.haveNonRawStreams; // reset -} +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; +/** `Object#toString` result references. */ +var funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; /** - * Add serializers - * - * @param serializers {Object} Optional. Object mapping log record field names - * to serializing functions. See README.md for details. + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ -Logger.prototype.addSerializers = function addSerializers(serializers) { - var self = this; +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - if (!self.serializers) { - self.serializers = {}; - } - Object.keys(serializers).forEach(function (field) { - var serializer = serializers[field]; - if (typeof (serializer) !== 'function') { - throw new TypeError(format( - 'invalid serializer for "%s" field: must be a function', - field)); - } else { - self.serializers[field] = serializer; - } - }); -} +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); /** - * Create a child logger, typically to add a few log record fields. - * - * This can be useful when passing a logger to a sub-component, e.g. a - * 'wuzzle' component of your service: - * - * var wuzzleLog = log.child({component: 'wuzzle'}) - * var wuzzle = new Wuzzle({..., log: wuzzleLog}) - * - * Then log records from the wuzzle code will have the same structure as - * the app log, *plus the component='wuzzle' field*. + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. * - * @param options {Object} Optional. Set of options to apply to the child. - * All of the same options for a new Logger apply here. Notes: - * - The parent's streams are inherited and cannot be removed in this - * call. Any given `streams` are *added* to the set inherited from - * the parent. - * - The parent's serializers are inherited, though can effectively be - * overwritten by using duplicate keys. - * - Can use `level` to set the level of the streams inherited from - * the parent. The level for the parent is NOT affected. - * @param simple {Boolean} Optional. Set to true to assert that `options` - * (a) only add fields (no config) and (b) no serialization handling is - * required for them. IOW, this is a fast path for frequent child - * creation. See 'tools/timechild.js' for numbers. + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. */ -Logger.prototype.child = function (options, simple) { - return new (this.constructor)(this, options || {}, simple); +function arrayIncludes(array, value) { + var length = array ? array.length : 0; + return !!length && baseIndexOf(array, value, 0) > -1; } - /** - * A convenience method to reopen 'file' streams on a logger. This can be - * useful with external log rotation utilities that move and re-open log files - * (e.g. logrotate on Linux, logadm on SmartOS/Illumos). Those utilities - * typically have rotation options to copy-and-truncate the log file, but - * you may not want to use that. An alternative is to do this in your - * application: - * - * var log = bunyan.createLogger(...); - * ... - * process.on('SIGUSR2', function () { - * log.reopenFileStreams(); - * }); - * ... + * This function is like `arrayIncludes` except that it accepts a comparator. * - * See . + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. */ -Logger.prototype.reopenFileStreams = function () { - var self = this; - self.streams.forEach(function (s) { - if (s.type === 'file') { - if (s.stream) { - // Not sure if typically would want this, or more immediate - // `s.stream.destroy()`. - s.stream.end(); - s.stream.destroySoon(); - delete s.stream; - } - s.stream = fs.createWriteStream(s.path, - {flags: 'a', encoding: 'utf8'}); - s.stream.on('error', function (err) { - self.emit('error', err, s); - }); - } - }); -}; - +function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array ? array.length : 0; -/* BEGIN JSSTYLED */ -/** - * Close this logger. - * - * This closes streams (that it owns, as per 'endOnClose' attributes on - * streams), etc. Typically you **don't** need to bother calling this. -Logger.prototype.close = function () { - if (this._closed) { - return; - } - if (!this._isSimpleChild) { - self.streams.forEach(function (s) { - if (s.endOnClose) { - xxx('closing stream s:', s); - s.stream.end(); - s.endOnClose = false; - } - }); + while (++index < length) { + if (comparator(value, array[index])) { + return true; } - this._closed = true; + } + return false; } - */ -/* END JSSTYLED */ - /** - * Get/set the level of all streams on this logger. - * - * Get Usage: - * // Returns the current log level (lowest level of all its streams). - * log.level() -> INFO + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. * - * Set Usage: - * log.level(INFO) // set all streams to level INFO - * log.level('info') // can use 'info' et al aliases + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. */ -Logger.prototype.level = function level(value) { - if (value === undefined) { - return this._level; - } - var newLevel = resolveLevel(value); - var len = this.streams.length; - for (var i = 0; i < len; i++) { - this.streams[i].level = newLevel; +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } - this._level = newLevel; + } + return -1; } - /** - * Get/set the level of a particular stream on this logger. - * - * Get Usage: - * // Returns an array of the levels of each stream. - * log.levels() -> [TRACE, INFO] - * - * // Returns a level of the identified stream. - * log.levels(0) -> TRACE // level of stream at index 0 - * log.levels('foo') // level of stream with name 'foo' - * - * Set Usage: - * log.levels(0, INFO) // set level of stream 0 to INFO - * log.levels(0, 'info') // can use 'info' et al aliases - * log.levels('foo', WARN) // set stream named 'foo' to WARN - * - * Stream names: When streams are defined, they can optionally be given - * a name. For example, - * log = new Logger({ - * streams: [ - * { - * name: 'foo', - * path: '/var/log/my-service/foo.log' - * level: 'trace' - * }, - * ... + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * - * @param name {String|Number} The stream index or name. - * @param value {Number|String} The level value (INFO) or alias ('info'). - * If not given, this is a 'get' operation. - * @throws {Error} If there is no stream with the given name. + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. */ -Logger.prototype.levels = function levels(name, value) { - if (name === undefined) { - assert.equal(value, undefined); - return this.streams.map( - function (s) { return s.level }); - } - var stream; - if (typeof (name) === 'number') { - stream = this.streams[name]; - if (stream === undefined) { - throw new Error('invalid stream index: ' + name); - } - } else { - var len = this.streams.length; - for (var i = 0; i < len; 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 (value === undefined) { - return stream.level; - } else { - var newLevel = resolveLevel(value); - stream.level = newLevel; - if (newLevel < this._level) { - this._level = newLevel; - } +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); + } + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; } + } + return -1; } +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} /** - * Apply registered serializers to the appropriate keys in the given fields. + * Checks if a cache value for `key` exists. * - * Pre-condition: This is only called if there is at least one serializer. + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +/** + * Gets the value at `key` of `object`. * - * @param fields (Object) The log record fields. - * @param excludeFields (Object) Optional mapping of keys to `true` for - * keys to NOT apply a serializer. + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. */ -Logger.prototype._applySerializers = function (fields, excludeFields) { - var self = this; +function getValue(object, key) { + return object == null ? undefined : object[key]; +} - xxx('_applySerializers: excludeFields', excludeFields); +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} - // Check each serializer against these (presuming number of serializers - // is typically less than number of fields). - Object.keys(this.serializers).forEach(function (name) { - if (fields[name] === undefined || - (excludeFields && excludeFields[name])) - { - return; - } - xxx('_applySerializers; apply to "%s" key', name) - try { - fields[name] = self.serializers[name](fields[name]); - } catch (err) { - _warn(format('bunyan: ERROR: Exception thrown from the "%s" ' - + 'Bunyan serializer. This should never happen. This is a bug ' - + 'in that serializer function.\n%s', - name, err.stack || err)); - fields[name] = format('(Error in Bunyan log "%s" serializer ' - + 'broke field. See stderr for details.)', name); - } - }); +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; } +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; /** - * Emit a log record. - * - * @param rec {log record} - * @param noemit {Boolean} Optional. Set to true to skip emission - * and just return the JSON string. + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. */ -Logger.prototype._emit = function (rec, noemit) { - var i; +var objectToString = objectProto.toString; - // Lazily determine if this Logger has non-'raw' streams. If there are - // any, then we need to stringify the log record. - if (this.haveNonRawStreams === undefined) { - this.haveNonRawStreams = false; - for (i = 0; i < this.streams.length; i++) { - if (!this.streams[i].raw) { - this.haveNonRawStreams = true; - break; - } - } - } +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); - // Stringify the object (creates a warning str on error). - var str; - if (noemit || this.haveNonRawStreams) { - str = fastAndSafeJsonStringify(rec) + '\n'; - } +/** Built-in value references. */ +var splice = arrayProto.splice; - if (noemit) - return str; +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'), + Set = getNative(root, 'Set'), + nativeCreate = getNative(Object, 'create'); - var level = rec.level; - for (i = 0; i < this.streams.length; i++) { - var s = this.streams[i]; - if (s.level <= level) { - xxx('writing log rec "%s" to "%s" stream (%d <= %d): %j', - rec.msg, s.type, s.level, level, rec); - s.stream.write(s.raw ? rec : str); - } - }; +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; - return str; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } - /** - * Build a record object suitable for emitting from the arguments - * provided to the a log emitter. + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash */ -function mkRecord(log, minLevel, args) { - var excludeFields, fields, msgArgs; - if (args[0] instanceof Error) { - // `log.(err, ...)` - fields = { - // Use this Logger's err serializer, if defined. - err: (log.serializers && log.serializers.err - ? log.serializers.err(args[0]) - : Logger.stdSerializers.err(args[0])) - }; - excludeFields = {err: true}; - if (args.length === 1) { - msgArgs = [fields.err.message]; - } else { - msgArgs = args.slice(1); - } - } else if (typeof (args[0]) !== 'object' || Array.isArray(args[0])) { - // `log.(msg, ...)` - fields = null; - msgArgs = args.slice(); - } else if (Buffer.isBuffer(args[0])) { // `log.(buf, ...)` - // Almost certainly an error, show `inspect(buf)`. See bunyan - // issue #35. - fields = null; - msgArgs = args.slice(); - msgArgs[0] = util.inspect(msgArgs[0]); - } else { // `log.(fields, msg, ...)` - fields = args[0]; - if (fields && args.length === 1 && fields.err && - fields.err instanceof Error) - { - msgArgs = [fields.err.message]; - } else { - msgArgs = args.slice(1); - } - } +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; +} - // Build up the record object. - var rec = objCopy(log.fields); - var level = rec.level = minLevel; - var recFields = (fields ? objCopy(fields) : null); - if (recFields) { - if (log.serializers) { - log._applySerializers(recFields, excludeFields); - } - Object.keys(recFields).forEach(function (k) { - rec[k] = recFields[k]; - }); - } - rec.msg = format.apply(log, msgArgs); - if (!rec.time) { - rec.time = (new Date()); - } - // Get call source info - if (log.src && !rec.src) { - rec.src = getCaller3Info() - } - rec.v = LOG_VERSION; +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + return this.has(key) && delete this.__data__[key]; +} - return rec; -}; +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); +} /** - * Build an array that dtrace-provider can use to fire a USDT probe. If we've - * already built the appropriate string, we use it. Otherwise, build the - * record object and stringify it. + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. */ -function mkProbeArgs(str, log, minLevel, msgArgs) { - return [ str || log._emit(mkRecord(log, minLevel, msgArgs), true) ]; +function hashSet(key, value) { + var data = this.__data__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; } +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; /** - * Build a log emitter function for level minLevel. I.e. this is the - * creator of `log.info`, `log.error`, etc. + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ -function mkLogEmitter(minLevel) { - return function () { - var log = this; - var str = null; - var rec = null; +function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; - if (!this._emit) { - /* - * Show this invalid Bunyan usage warning *once*. - * - * See for - * an example of how this can happen. - */ - var dedupKey = 'unbound'; - if (!_haveWarned[dedupKey]) { - var caller = getCaller3Info(); - _warn(format('bunyan usage error: %s:%s: attempt to log ' - + 'with an unbound log method: `this` is: %s', - caller.file, caller.line, util.inspect(this)), - dedupKey); - } - return; - } else if (arguments.length === 0) { // `log.()` - return (this._level <= minLevel); - } + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} - var msgArgs = new Array(arguments.length); - for (var i = 0; i < msgArgs.length; ++i) { - msgArgs[i] = arguments[i]; - } +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; +} - if (this._level <= minLevel) { - rec = mkRecord(log, minLevel, msgArgs); - str = this._emit(rec); - } +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); - if (probes) { - probes[minLevel].fire(mkProbeArgs, str, log, minLevel, msgArgs); - } - } + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + return true; } - /** - * The functions below log a record at a specific level. - * - * Usages: - * log.() -> boolean is-trace-enabled - * log.( err, [ msg, ...]) - * log.( msg, ...) - * log.( fields, msg, ...) - * - * where is the lowercase version of the log level. E.g.: - * - * log.info() + * Gets the list cache value for `key`. * - * @params fields {Object} Optional set of additional fields to log. - * @params msg {String} Log message. This can be followed by additional - * arguments that are handled like - * [util.format](http://nodejs.org/docs/latest/api/all.html#util.format). + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ -Logger.prototype.trace = mkLogEmitter(TRACE); -Logger.prototype.debug = mkLogEmitter(DEBUG); -Logger.prototype.info = mkLogEmitter(INFO); -Logger.prototype.warn = mkLogEmitter(WARN); -Logger.prototype.error = mkLogEmitter(ERROR); -Logger.prototype.fatal = mkLogEmitter(FATAL); +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + return index < 0 ? undefined : data[index][1]; +} +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} -//---- Standard serializers -// A serializer is a function that serializes a JavaScript object to a -// JSON representation for logging. There is a standard set of presumed -// interesting objects in node.js-land. +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); -Logger.stdSerializers = {}; + if (index < 0) { + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} -// Serialize an HTTP request. -Logger.stdSerializers.req = function (req) { - if (!req || !req.connection) - return req; - return { - method: req.method, - url: req.url, - headers: req.headers, - remoteAddress: req.connection.remoteAddress, - remotePort: req.connection.remotePort - }; - // Trailers: Skipping for speed. If you need trailers in your app, then - // make a custom serializer. - //if (Object.keys(trailers).length > 0) { - // obj.trailers = req.trailers; - //} -}; +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; -// Serialize an HTTP response. -Logger.stdSerializers.res = function (res) { - if (!res || !res.statusCode) - return res; - return { - statusCode: res.statusCode, - header: res._header - } -}; +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} -/* - * This function dumps long stack traces for exceptions having a cause() - * method. The error classes from - * [verror](https://github.com/davepacheco/node-verror) and - * [restify v2.0](https://github.com/mcavage/node-restify) are examples. +/** + * Removes all key-value entries from the map. * - * Based on `dumpException` in - * https://github.com/davepacheco/node-extsprintf/blob/master/lib/extsprintf.js + * @private + * @name clear + * @memberOf MapCache */ -function getFullErrorStack(ex) -{ - var ret = ex.stack || ex.toString(); - if (ex.cause && typeof (ex.cause) === 'function') { - var cex = ex.cause(); - if (cex) { - ret += '\nCaused by: ' + getFullErrorStack(cex); - } - } - return (ret); +function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; } -// Serialize an Error object -// (Core error properties are enumerable in node 0.4, not in 0.6). -var errSerializer = Logger.stdSerializers.err = function (err) { - if (!err || !err.stack) - return err; - var obj = { - message: err.message, - name: err.name, - stack: getFullErrorStack(err), - code: err.code, - signal: err.signal - } - return obj; -}; - - -// A JSON stringifier that handles cycles safely - tracks seen values in a Set. -function safeCyclesSet() { - var seen = new Set(); - return function (key, val) { - if (!val || typeof (val) !== 'object') { - return val; - } - if (seen.has(val)) { - return '[Circular]'; - } - seen.add(val); - return val; - }; +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + return getMapData(this, key)['delete'](key); } /** - * A JSON stringifier that handles cycles safely - tracks seen vals in an Array. + * Gets the map value for `key`. * - * Note: This approach has performance problems when dealing with large objects, - * see trentm/node-bunyan#445, but since this is the only option for node 0.10 - * and earlier (as Set was introduced in Node 0.12), it's used as a fallback - * when Set is not available. + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ -function safeCyclesArray() { - var seen = []; - return function (key, val) { - if (!val || typeof (val) !== 'object') { - return val; - } - if (seen.indexOf(val) !== -1) { - return '[Circular]'; - } - seen.push(val); - return val; - }; +function mapCacheGet(key) { + return getMapData(this, key).get(key); } /** - * A JSON stringifier that handles cycles safely. - * - * Usage: JSON.stringify(obj, safeCycles()) + * Checks if a map value for `key` exists. * - * Choose the best safe cycle function from what is available - see - * trentm/node-bunyan#445. + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ -var safeCycles = typeof (Set) !== 'undefined' ? safeCyclesSet : safeCyclesArray; +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} /** - * A fast JSON.stringify that handles cycles and getter exceptions (when - * safeJsonStringify is installed). + * Sets the map `key` to `value`. * - * This function attempts to use the regular JSON.stringify for speed, but on - * error (e.g. JSON cycle detection exception) it falls back to safe stringify - * handlers that can deal with cycles and/or getter exceptions. + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. */ -function fastAndSafeJsonStringify(rec) { - try { - return JSON.stringify(rec); - } catch (ex) { - try { - return JSON.stringify(rec, safeCycles()); - } catch (e) { - if (safeJsonStringify) { - return safeJsonStringify(rec); - } else { - var dedupKey = e.stack.split(/\n/g, 3).join('\n'); - _warn('bunyan: ERROR: Exception in ' - + '`JSON.stringify(rec)`. You can install the ' - + '"safe-json-stringify" module to have Bunyan fallback ' - + 'to safer stringification. Record:\n' - + _indent(format('%s\n%s', util.inspect(rec), e.stack)), - dedupKey); - return format('(Exception in JSON.stringify(rec): %j. ' - + 'See stderr for details.)', e.message); - } - } - } +function mapCacheSet(key, value) { + getMapData(this, key).set(key, value); + return this; } +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; -var RotatingFileStream = null; -if (mv) { - -RotatingFileStream = function RotatingFileStream(options) { - this.path = options.path; - - this.count = (options.count == null ? 10 : options.count); - assert.equal(typeof (this.count), 'number', - format('rotating-file stream "count" is not a number: %j (%s) in %j', - this.count, typeof (this.count), this)); - assert.ok(this.count >= 0, - format('rotating-file stream "count" is not >= 0: %j in %j', - this.count, this)); +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values ? values.length : 0; - // Parse `options.period`. - if (options.period) { - // where scope is: - // h hours (at the start of the hour) - // d days (at the start of the day, i.e. just after midnight) - // w weeks (at the start of Sunday) - // m months (on the first of the month) - // y years (at the start of Jan 1st) - // with special values 'hourly' (1h), 'daily' (1d), "weekly" (1w), - // 'monthly' (1m) and 'yearly' (1y) - var period = { - 'hourly': '1h', - 'daily': '1d', - 'weekly': '1w', - 'monthly': '1m', - 'yearly': '1y' - }[options.period] || options.period; - var 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'; - } + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} - var lastModified = null; - try { - var fileInfo = fs.statSync(this.path); - lastModified = fileInfo.mtime.getTime(); - } - catch (err) { - // file doesn't exist - } - var rotateAfterOpen = false; - if (lastModified) { - var lastRotTime = this._calcRotTime(0); - if (lastModified < lastRotTime) { - rotateAfterOpen = true; - } - } +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} - // TODO: template support for backup files - // template: - // default is %P.%n - // '/var/log/archive/foo.log' -> foo.log.%n - // '/var/log/archive/foo.log.%n' - // codes: - // XXX support strftime codes (per node version of those) - // or whatever module. Pick non-colliding for extra - // codes - // %P `path` base value - // %n integer number of rotated log (1,2,3,...) - // %d datetime in YYYY-MM-DD_HH-MM-SS - // XXX what should default date format be? - // prior art? Want to avoid ':' in - // filenames (illegal on Windows for one). +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} - this.stream = fs.createWriteStream(this.path, - {flags: 'a', encoding: 'utf8'}); +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; - this.rotQueue = []; - this.rotating = false; - if (rotateAfterOpen) { - this._debug('rotateAfterOpen -> call rotate()'); - this.rotate(); - } else { - this._setupNextRot(); +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; } + } + return -1; } -util.inherits(RotatingFileStream, EventEmitter); +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} -RotatingFileStream.prototype._debug = function () { - // Set this to `true` to add debug logging. - if (false) { - if (arguments.length === 0) { - return true; +/** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; } - var args = Array.prototype.slice.call(arguments); - args[0] = '[' + (new Date().toISOString()) + ', ' - + this.path + '] ' + args[0]; - console.log.apply(this, args); - } else { - return false; + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); } + } + return result; +} + +/** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ +var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); }; -RotatingFileStream.prototype._setupNextRot = function () { - this.rotAt = this._calcRotTime(1); - this._setRotationTimer(); +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } -RotatingFileStream.prototype._setRotationTimer = function () { - var self = this; - var delay = this.rotAt - Date.now(); - // Cap timeout to Node's max setTimeout, see - // . - var TIMEOUT_MAX = 2147483647; // 2^31-1 - if (delay > TIMEOUT_MAX) { - delay = TIMEOUT_MAX; - } - this.timeout = setTimeout( - function () { - self._debug('_setRotationTimer timeout -> call rotate()'); - self.rotate(); - }, - delay); - if (typeof (this.timeout.unref) === 'function') { - this.timeout.unref(); - } +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; } -RotatingFileStream.prototype._calcRotTime = -function _calcRotTime(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': - // Hidden millisecond period for debugging. - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * periodOffset; - } else { - rotAt = Date.now() + this.periodNum * periodOffset; - } - break; - case 'h': - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * 60 * 60 * 1000 * periodOffset; - } else { - // First time: top of the next hour. - rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), - d.getUTCDate(), d.getUTCHours() + periodOffset); - } - break; - case 'd': - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * 24 * 60 * 60 * 1000 - * periodOffset; - } else { - // First time: start of tomorrow (i.e. at the coming midnight) UTC. - rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), - d.getUTCDate() + periodOffset); - } - break; - case 'w': - // Currently, always on Sunday morning at 00:00:00 (UTC). - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * 7 * 24 * 60 * 60 * 1000 - * periodOffset; - } else { - // First time: this coming Sunday. - var dayOffset = (7 - d.getUTCDay()); - if (periodOffset < 1) { - dayOffset = -d.getUTCDay(); - } - if (periodOffset > 1 || periodOffset < -1) { - dayOffset += 7 * periodOffset; - } - rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), - d.getUTCDate() + dayOffset); - } - break; - case 'm': - if (this.rotAt) { - rotAt = Date.UTC(d.getUTCFullYear(), - d.getUTCMonth() + this.periodNum * periodOffset, 1); - } else { - // First time: the start of the next month. - rotAt = Date.UTC(d.getUTCFullYear(), - d.getUTCMonth() + periodOffset, 1); - } - break; - case 'y': - if (this.rotAt) { - rotAt = Date.UTC(d.getUTCFullYear() + this.periodNum * periodOffset, - 0, 1); - } else { - // First time: the start of the next year. - rotAt = Date.UTC(d.getUTCFullYear() + periodOffset, 0, 1); - } - break; - default: - assert.fail(format('invalid period scope: "%s"', this.periodScope)); - } +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} - 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)/1000/60, - (rotAt-now)/1000/60/60); - } - return rotAt; -}; +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} -RotatingFileStream.prototype.rotate = function rotate() { - // XXX What about shutdown? - var self = this; +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} - // If rotation period is > ~25 days, we have to break into multiple - // setTimeout's. See . - if (self.rotAt && self.rotAt > Date.now()) { - return self._setRotationTimer(); - } +/** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each + * element is kept. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ +function uniq(array) { + return (array && array.length) + ? baseUniq(array) + : []; +} - this._debug('rotate'); - if (self.rotating) { - throw new TypeError('cannot start a rotation when already rotating'); - } - self.rotating = true; +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} - self.stream.end(); // XXX can do moves sync after this? test at high rate +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - function del() { - var toDel = self.path + '.' + String(n - 1); - if (n === 0) { - toDel = self.path; - } - n -= 1; - self._debug(' rm %s', toDel); - fs.unlink(toDel, function (delErr) { - //XXX handle err other than not exists - moves(); - }); - } +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - function moves() { - if (self.count === 0 || n < 0) { - return finish(); - } - var before = self.path; - var after = self.path + '.' + String(n); - if (n > 0) { - before += '.' + String(n - 1); - } - n -= 1; - fs.exists(before, function (exists) { - if (!exists) { - moves(); - } else { - self._debug(' mv %s %s', before, after); - mv(before, after, function (mvErr) { - if (mvErr) { - self.emit('error', mvErr); - finish(); // XXX finish here? - } else { - moves(); - } - }); - } - }) - } +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} - function finish() { - self._debug(' open %s', self.path); - self.stream = fs.createWriteStream(self.path, - {flags: 'a', encoding: 'utf8'}); - var q = self.rotQueue, len = q.length; - for (var i = 0; i < len; i++) { - self.stream.write(q[i]); - } - self.rotQueue = []; - self.rotating = false; - self.emit('drain'); - self._setupNextRot(); - } +module.exports = uniq; - var n = this.count; - del(); -}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],80:[function(require,module,exports){ +(function (Buffer){ -RotatingFileStream.prototype.write = function write(s) { - if (this.rotating) { - this.rotQueue.push(s); - return false; - } else { - return this.stream.write(s); +exports.compare = function (a, b) { + + if(Buffer.isBuffer(a)) { + var l = Math.min(a.length, b.length) + for(var i = 0; i < l; i++) { + var cmp = a[i] - b[i] + if(cmp) return cmp } -}; + return a.length - b.length + } -RotatingFileStream.prototype.end = function end(s) { - this.stream.end(); -}; + return a < b ? -1 : a > b ? 1 : 0 +} -RotatingFileStream.prototype.destroy = function destroy(s) { - this.stream.destroy(); -}; +function has(obj, key) { + return Object.hasOwnProperty.call(obj, key) +} -RotatingFileStream.prototype.destroySoon = function destroySoon(s) { - this.stream.destroySoon(); -}; +// to be compatible with the current abstract-leveldown tests +// nullish or empty strings. +// I could use !!val but I want to permit numbers and booleans, +// if possible. -} /* if (mv) */ +function isDef (val) { + return val !== undefined && val !== '' +} +function has (range, name) { + return Object.hasOwnProperty.call(range, name) +} +function hasKey(range, name) { + return Object.hasOwnProperty.call(range, name) && name +} -/** - * RingBuffer is a Writable Stream that just stores the last N records in - * memory. - * - * @param options {Object}, with the following fields: - * - * - limit: number of records to keep in memory - */ -function RingBuffer(options) { - this.limit = options && options.limit ? options.limit : 100; - this.writable = true; - this.records = []; - EventEmitter.call(this); +var lowerBoundKey = exports.lowerBoundKey = function (range) { + return ( + hasKey(range, 'gt') + || hasKey(range, 'gte') + || hasKey(range, 'min') + || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start')) + || undefined + ) } -util.inherits(RingBuffer, EventEmitter); +var lowerBound = exports.lowerBound = function (range, def) { + var k = lowerBoundKey(range) + return k ? range[k] : def +} -RingBuffer.prototype.write = function (record) { - if (!this.writable) - throw (new Error('RingBuffer has been ended already')); +var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) { + return has(range, 'gt') ? false : true +} - this.records.push(record); +var upperBoundInclusive = exports.upperBoundInclusive = + function (range) { + return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true + } - if (this.records.length > this.limit) - this.records.shift(); +var lowerBoundExclusive = exports.lowerBoundExclusive = + function (range) { + return !lowerBoundInclusive(range) + } - return (true); -}; +var upperBoundExclusive = exports.upperBoundExclusive = + function (range) { + return !upperBoundInclusive(range) + } -RingBuffer.prototype.end = function () { - if (arguments.length > 0) - this.write.apply(this, Array.prototype.slice.call(arguments)); - this.writable = false; -}; +var upperBoundKey = exports.upperBoundKey = function (range) { + return ( + hasKey(range, 'lt') + || hasKey(range, 'lte') + || hasKey(range, 'max') + || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end')) + || undefined + ) +} -RingBuffer.prototype.destroy = function () { - this.writable = false; - this.emit('close'); -}; +var upperBound = exports.upperBound = function (range, def) { + var k = upperBoundKey(range) + return k ? range[k] : def +} -RingBuffer.prototype.destroySoon = function () { - this.destroy(); -}; +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 } -//---- Exports +exports.toLtgt = function (range, _range, map, lower, upper) { + _range = _range || {} + map = map || id + var defaults = arguments.length > 3 + var lb = exports.lowerBoundKey(range) + var ub = exports.upperBoundKey(range) + if(lb) { + if(lb === 'gt') _range.gt = map(range.gt, false) + else _range.gte = map(range[lb], false) + } + else if(defaults) + _range.gte = map(lower, false) -module.exports = Logger; + if(ub) { + if(ub === 'lt') _range.lt = map(range.lt, true) + else _range.lte = map(range[ub], true) + } + else if(defaults) + _range.lte = map(upper, true) -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; + if(range.reverse != null) + _range.reverse = !!range.reverse -module.exports.VERSION = VERSION; -module.exports.LOG_VERSION = LOG_VERSION; + //if range was used mutably + //(in level-sublevel it's part of an options object + //that has more properties on it.) + if(has(_range, 'max')) delete _range.max + if(has(_range, 'min')) delete _range.min + if(has(_range, 'start')) delete _range.start + if(has(_range, 'end')) delete _range.end -module.exports.createLogger = function createLogger(options) { - return new Logger(options); -}; + return _range +} -module.exports.RingBuffer = RingBuffer; -module.exports.RotatingFileStream = RotatingFileStream; +exports.contains = function (range, key, compare) { + compare = compare || exports.compare -// Useful for custom `type == 'raw'` streams that may do JSON stringification -// of log records themselves. Usage: -// var str = JSON.stringify(rec, bunyan.safeCycles()); -module.exports.safeCycles = safeCycles; + var lb = lowerBound(range) + if(isDef(lb)) { + var cmp = compare(key, lb) + if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range))) + return false + } -}).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process')) -},{"../../is-buffer/index.js":173,"_process":206,"assert":152,"events":169,"fs":155,"os":204,"safe-json-stringify":222,"stream":223,"util":229}],158:[function(require,module,exports){ -(function (Buffer){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + var ub = upperBound(range) + if(isDef(ub)) { + var cmp = compare(key, ub) + if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range)) + return false + } -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. + return true +} -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); +exports.filter = function (range, compare) { + return function (key) { + return exports.contains(range, key, compare) } - return objectToString(arg) === '[object Array]'; } -exports.isArray = isArray; -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; -function isNullOrUndefined(arg) { - return arg == null; +}).call(this,{"isBuffer":require("../is-buffer/index.js")}) +},{"../is-buffer/index.js":42}],81:[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 } -exports.isNullOrUndefined = isNullOrUndefined; -function isNumber(arg) { - return typeof arg === 'number'; +// 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 } -exports.isNumber = isNumber; -function isString(arg) { - return typeof arg === 'string'; +// 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.isString = isString; -function isSymbol(arg) { - return typeof arg === 'symbol'; +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) + } } -exports.isSymbol = isSymbol; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; +},{}],82:[function(require,module,exports){ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) -function isDate(d) { - return objectToString(d) === '[object Date]'; +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f } -exports.isDate = isDate; -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f } -exports.isError = isError; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; +},{"wrappy":158}],83:[function(require,module,exports){ +exports.endianness = function () { return 'LE' }; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname + } + else return ''; +}; -exports.isBuffer = Buffer.isBuffer; +exports.loadavg = function () { return [] }; -function objectToString(o) { - return Object.prototype.toString.call(o); -} +exports.uptime = function () { return 0 }; -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":173}],159:[function(require,module,exports){ -arguments[4][9][0].apply(exports,arguments) -},{"abstract-leveldown":164,"dup":9,"util":229}],160:[function(require,module,exports){ -(function (Buffer,process){ -var util = require('util') - , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN - , DeferredIterator = require('./deferred-iterator') +exports.freemem = function () { + return Number.MAX_VALUE; +}; -function DeferredLevelDOWN (location) { - AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '') // optional location, who cares? - this._db = undefined - this._operations = [] - this._iterators = [] -} +exports.totalmem = function () { + return Number.MAX_VALUE; +}; -util.inherits(DeferredLevelDOWN, AbstractLevelDOWN) +exports.cpus = function () { return [] }; -// called by LevelUP when we have a real DB to take its place -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) - }) -} +exports.type = function () { return 'Browser' }; -DeferredLevelDOWN.prototype._open = function (options, callback) { - return process.nextTick(callback) -} +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; -// queue a new deferred operation -DeferredLevelDOWN.prototype._operation = function (method, args) { - if (this._db) - return this._db[method].apply(this._db, args) - this._operations.push({ method: method, args: args }) -} +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; -// deferrables -'put get del batch approximateSize'.split(' ').forEach(function (m) { - DeferredLevelDOWN.prototype['_' + m] = function () { - this._operation(m, arguments) - } -}) +exports.arch = function () { return 'javascript' }; -DeferredLevelDOWN.prototype._isBuffer = function (obj) { - return Buffer.isBuffer(obj) +exports.platform = function () { return 'browser' }; + +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; + +exports.EOL = '\n'; + +},{}],84:[function(require,module,exports){ +(function (process){ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; } -DeferredLevelDOWN.prototype._iterator = function (options) { - if (this._db) - return this._db.iterator.apply(this._db, arguments) - var it = new DeferredIterator(options) - this._iterators.push(it) - return it +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } } -module.exports = DeferredLevelDOWN -module.exports.DeferredIterator = DeferredIterator +}).call(this,require('_process')) +},{"_process":85}],85:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; -}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process')) -},{"../is-buffer/index.js":173,"./deferred-iterator":159,"_process":206,"abstract-leveldown":164,"util":229}],161:[function(require,module,exports){ -arguments[4][11][0].apply(exports,arguments) -},{"_process":206,"dup":11}],162:[function(require,module,exports){ -arguments[4][12][0].apply(exports,arguments) -},{"_process":206,"dup":12}],163:[function(require,module,exports){ -(function (Buffer,process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. -var xtend = require('xtend') - , AbstractIterator = require('./abstract-iterator') - , AbstractChainedBatch = require('./abstract-chained-batch') +var cachedSetTimeout; +var cachedClearTimeout; -function AbstractLevelDOWN (location) { - if (!arguments.length || location === undefined) - throw new Error('constructor requires at least a location argument') +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } - if (typeof location != 'string') - throw new Error('constructor requires a location string argument') - this.location = location - this.status = 'new' } +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } -AbstractLevelDOWN.prototype.open = function (options, callback) { - var self = this - , oldStatus = this.status - if (typeof options == 'function') - callback = options - if (typeof callback != 'function') - throw new Error('open() requires a callback argument') +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; - if (typeof options != 'object') - options = {} +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} - options.createIfMissing = options.createIfMissing != false - options.errorIfExists = !!options.errorIfExists +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - if (typeof this._open == 'function') { - this.status = 'opening' - this._open(options, function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'open' - callback() - }) - } else { - this.status = 'open' - process.nextTick(callback) - } + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); } -AbstractLevelDOWN.prototype.close = function (callback) { - var self = this - , oldStatus = this.status - - if (typeof callback != 'function') - throw new Error('close() requires a callback argument') +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; - if (typeof this._close == 'function') { - this.status = 'closing' - this._close(function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'closed' - callback() - }) - } else { - this.status = 'closed' - process.nextTick(callback) - } +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; } +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; -AbstractLevelDOWN.prototype.get = function (key, options, callback) { - var err - - if (typeof options == 'function') - callback = options +function noop() {} - if (typeof callback != 'function') - throw new Error('get() requires a callback argument') +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; - if (err = this._checkKey(key, 'key', this._isBuffer)) - return callback(err) +process.listeners = function (name) { return [] } - if (!this._isBuffer(key)) - key = String(key) +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; - if (typeof options != 'object') - options = {} +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; - options.asBuffer = options.asBuffer != false +},{}],86:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],87:[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 - if (typeof this._get == 'function') - return this._get(key, options, callback) +var noop = function () {} - process.nextTick(function () { callback(new Error('NotFound')) }) +var isFn = function (fn) { + return typeof fn === 'function' } -AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { - var err +var isFS = function (stream) { + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) +} - if (typeof options == 'function') - callback = options +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) +} - if (typeof callback != 'function') - throw new Error('put() requires a callback argument') +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) - if (err = this._checkKey(key, 'key', this._isBuffer)) - return callback(err) + var closed = false + stream.on('close', function () { + closed = true + }) - if (!this._isBuffer(key)) - key = String(key) + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) - // coerce value to string in node, don't touch it in browser - // (indexeddb can store any JS type) - if (value != null && !this._isBuffer(value) && !process.browser) - value = String(value) + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true - if (typeof options != 'object') - options = {} + if (isFS(stream)) return stream.close() // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want - if (typeof this._put == 'function') - return this._put(key, value, options, callback) + if (isFn(stream.destroy)) return stream.destroy() - process.nextTick(callback) + callback(err || new Error('stream was destroyed')) + } } -AbstractLevelDOWN.prototype.del = function (key, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('del() requires a callback argument') - - if (err = this._checkKey(key, 'key', this._isBuffer)) - return callback(err) +var call = function (fn) { + fn() +} - if (!this._isBuffer(key)) - key = String(key) +var pipe = function (from, to) { + return from.pipe(to) +} - if (typeof options != 'object') - options = {} +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop - if (typeof this._del == 'function') - return this._del(key, options, callback) + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') - process.nextTick(callback) + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) + + return streams.reduce(pipe) } -AbstractLevelDOWN.prototype.batch = function (array, options, callback) { - if (!arguments.length) - return this._chainedBatch() +module.exports = pump - if (typeof options == 'function') - callback = options +},{"end-of-stream":33,"fs":7,"once":82}],88:[function(require,module,exports){ +var pump = require('pump') +var inherits = require('inherits') +var Duplexify = require('duplexify') - if (typeof array == 'function') - callback = array +var toArray = function(args) { + if (!args.length) return [] + return Array.isArray(args[0]) ? args[0] : Array.prototype.slice.call(args) +} - if (typeof callback != 'function') - throw new Error('batch(array) requires a callback argument') +var define = function(opts) { + var Pumpify = function() { + var streams = toArray(arguments) + if (!(this instanceof Pumpify)) return new Pumpify(streams) + Duplexify.call(this, null, null, opts) + if (streams.length) this.setPipeline(streams) + } - if (!Array.isArray(array)) - return callback(new Error('batch(array) requires an array argument')) + inherits(Pumpify, Duplexify) - if (!options || typeof options != 'object') - options = {} + Pumpify.prototype.setPipeline = function() { + var streams = toArray(arguments) + var self = this + var ended = false + var w = streams[0] + var r = streams[streams.length-1] - var i = 0 - , l = array.length - , e - , err + r = r.readable ? r : null + w = w.writable ? w : null - for (; i < l; i++) { - e = array[i] - if (typeof e != 'object') - continue + var onclose = function() { + streams[0].emit('error', new Error('stream was destroyed')) + } - if (err = this._checkKey(e.type, 'type', this._isBuffer)) - return callback(err) + this.on('close', onclose) + this.on('prefinish', function() { + if (!ended) self.cork() + }) - if (err = this._checkKey(e.key, 'key', this._isBuffer)) - return callback(err) - } + pump(streams, function(err) { + self.removeListener('close', onclose) + if (err) return self.destroy(err) + ended = true + self.uncork() + }) - if (typeof this._batch == 'function') - return this._batch(array, options, callback) + if (this.destroyed) return onclose() + this.setWritable(w) + this.setReadable(r) + } - process.nextTick(callback) + return Pumpify } -//TODO: remove from here, not a necessary primitive -AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) { - if ( start == null - || end == null - || typeof start == 'function' - || typeof end == 'function') { - throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') - } +module.exports = define({destroy:false}) +module.exports.obj = define({destroy:false, objectMode:true, highWaterMark:16}) - if (typeof callback != 'function') - throw new Error('approximateSize() requires a callback argument') +},{"duplexify":32,"inherits":40,"pump":87}],89:[function(require,module,exports){ +module.exports = require('./lib/_stream_duplex.js'); - if (!this._isBuffer(start)) - start = String(start) +},{"./lib/_stream_duplex.js":90}],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. - if (!this._isBuffer(end)) - end = String(end) +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. - if (typeof this._approximateSize == 'function') - return this._approximateSize(start, end, callback) +'use strict'; - process.nextTick(function () { - callback(null, 0) - }) -} +/**/ -AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { - var self = this +var processNextTick = require('process-nextick-args'); +/**/ - options = xtend(options) +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ - ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) { - if (options[o] && self._isBuffer(options[o]) && options[o].length === 0) - delete options[o] - }) +module.exports = Duplex; - options.reverse = !!options.reverse - options.keys = options.keys != false - options.values = options.values != false - options.limit = 'limit' in options ? options.limit : -1 - options.keyAsBuffer = options.keyAsBuffer != false - options.valueAsBuffer = options.valueAsBuffer != false +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - return options +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } -AbstractLevelDOWN.prototype.iterator = function (options) { - if (typeof options != 'object') - options = {} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); - options = this._setupIteratorOptions(options) + Readable.call(this, options); + Writable.call(this, options); - if (typeof this._iterator == 'function') - return this._iterator(options) + if (options && options.readable === false) this.readable = false; - return new AbstractIterator(this) + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); } -AbstractLevelDOWN.prototype._chainedBatch = function () { - return new AbstractChainedBatch(this) +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); } -AbstractLevelDOWN.prototype._isBuffer = function (obj) { - return Buffer.isBuffer(obj) +function onEndNT(self) { + self.end(); } -AbstractLevelDOWN.prototype._checkKey = function (obj, type) { +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; + } - if (obj === null || obj === undefined) - return new Error(type + ' cannot be `null` or `undefined`') + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); - if (this._isBuffer(obj)) { - if (obj.length === 0) - return new Error(type + ' cannot be an empty Buffer') - } else if (String(obj) === '') - return new Error(type + ' cannot be an empty String') -} +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); -module.exports = AbstractLevelDOWN + processNextTick(cb, err); +}; -}).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) -},{"../../../is-buffer/index.js":173,"./abstract-chained-batch":161,"./abstract-iterator":162,"_process":206,"xtend":230}],164:[function(require,module,exports){ -arguments[4][14][0].apply(exports,arguments) -},{"./abstract-chained-batch":161,"./abstract-iterator":162,"./abstract-leveldown":163,"./is-leveldown":165,"dup":14}],165:[function(require,module,exports){ -arguments[4][15][0].apply(exports,arguments) -},{"./abstract-leveldown":163,"dup":15}],166:[function(require,module,exports){ -arguments[4][31][0].apply(exports,arguments) -},{"dup":31,"prr":168}],167:[function(require,module,exports){ -arguments[4][32][0].apply(exports,arguments) -},{"./custom":166,"dup":32}],168:[function(require,module,exports){ -arguments[4][33][0].apply(exports,arguments) -},{"dup":33}],169:[function(require,module,exports){ +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":40,"process-nextick-args":84}],91:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -30946,1131 +25491,1259 @@ arguments[4][33][0].apply(exports,arguments) // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; +'use strict'; -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; +module.exports = PassThrough; - if (!this._events) - this._events = {}; +var Transform = require('./_stream_transform'); - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } - } +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - handler = this._events[type]; +util.inherits(PassThrough, Transform); - if (isUndefined(handler)) - return false; +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } + Transform.call(this, options); +} - return true; +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); }; +},{"./_stream_transform":93,"core-util-is":11,"inherits":40}],92:[function(require,module,exports){ +(function (process,global){ +// 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. -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; +'use strict'; - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } +/**/ - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } +var processNextTick = require('process-nextick-args'); +/**/ - return this; -}; +module.exports = Readable; -EventEmitter.prototype.on = EventEmitter.prototype.addListener; +/**/ +var isArray = require('isarray'); +/**/ -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); +/**/ +var Duplex; +/**/ - var fired = false; +Readable.ReadableState = ReadableState; - function g() { - this.removeListener(type, g); +/**/ +var EE = require('events').EventEmitter; - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ - g.listener = listener; - this.on(type, g); +/**/ +var Stream = require('./internal/streams/stream'); +/**/ - return this; -}; +// TODO(bmeurer): Change this back to const once hole checks are +// properly optimized away early in Ignition+TurboFan. +/**/ +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - if (!isFunction(listener)) - throw TypeError('listener must be a function'); +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ - if (!this._events || !this._events[type]) - return this; +var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); +var StringDecoder; - list = this._events[type]; - length = list.length; - position = -1; +util.inherits(Readable, Stream); - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } +} - if (position < 0) - return this; +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } + options = options || {}; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - return this; -}; + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - if (!this._events) - return this; + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } + // 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 + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } + // 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; - listeners = this._events[type]; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; + // has it been destroyed + this.destroyed = false; - return this; -}; + // 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'; -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; } - return 0; -}; +} -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); -function isFunction(arg) { - return typeof arg === 'function'; -} + if (!(this instanceof Readable)) return new Readable(options); -function isNumber(arg) { - return typeof arg === 'number'; -} + this._readableState = new ReadableState(options, this); -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} + // legacy + this.readable = true; -function isUndefined(arg) { - return arg === void 0; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); } -},{}],170:[function(require,module,exports){ -arguments[4][34][0].apply(exports,arguments) -},{"dup":34}],171:[function(require,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] +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; + } - i += d + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} +// 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; + var skipChunkCheck; - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } } else { - m = m + Math.pow(2, mLen) - e = e - eBias + skipChunkCheck = true; } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; - value = Math.abs(value) +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } 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' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 + 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 { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; } } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 + return needMoreData(state); } -},{}],172:[function(require,module,exports){ -arguments[4][35][0].apply(exports,arguments) -},{"dup":35}],173:[function(require,module,exports){ -/*! - * Determine if an object is a Buffer - * - * @author Feross Aboukhadijeh - * @license MIT - */ +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); -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -module.exports = function (obj) { - return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); } -function isBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +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; } -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +// 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, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } -},{}],174:[function(require,module,exports){ -arguments[4][36][0].apply(exports,arguments) -},{"dup":36}],175:[function(require,module,exports){ -arguments[4][37][0].apply(exports,arguments) -},{"buffer":156,"dup":37}],176:[function(require,module,exports){ -arguments[4][39][0].apply(exports,arguments) -},{"./lib/encodings":177,"dup":39}],177:[function(require,module,exports){ -arguments[4][40][0].apply(exports,arguments) -},{"buffer":156,"dup":40}],178:[function(require,module,exports){ -arguments[4][41][0].apply(exports,arguments) -},{"dup":41,"errno":167}],179:[function(require,module,exports){ -arguments[4][42][0].apply(exports,arguments) -},{"dup":42,"inherits":172,"level-errors":178,"readable-stream":186,"xtend":230}],180:[function(require,module,exports){ -arguments[4][43][0].apply(exports,arguments) -},{"dup":43}],181:[function(require,module,exports){ -arguments[4][44][0].apply(exports,arguments) -},{"./_stream_readable":183,"./_stream_writable":185,"_process":206,"core-util-is":158,"dup":44,"inherits":172}],182:[function(require,module,exports){ -arguments[4][45][0].apply(exports,arguments) -},{"./_stream_transform":184,"core-util-is":158,"dup":45,"inherits":172}],183:[function(require,module,exports){ -arguments[4][46][0].apply(exports,arguments) -},{"./_stream_duplex":181,"_process":206,"buffer":156,"core-util-is":158,"dup":46,"events":169,"inherits":172,"isarray":180,"stream":223,"string_decoder/":187,"util":154}],184:[function(require,module,exports){ -arguments[4][47][0].apply(exports,arguments) -},{"./_stream_duplex":181,"core-util-is":158,"dup":47,"inherits":172}],185:[function(require,module,exports){ -arguments[4][48][0].apply(exports,arguments) -},{"./_stream_duplex":181,"_process":206,"buffer":156,"core-util-is":158,"dup":48,"inherits":172,"stream":223}],186:[function(require,module,exports){ -arguments[4][49][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":181,"./lib/_stream_passthrough.js":182,"./lib/_stream_readable.js":183,"./lib/_stream_transform.js":184,"./lib/_stream_writable.js":185,"_process":206,"dup":49,"stream":223}],187:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"buffer":156,"dup":50}],188:[function(require,module,exports){ -arguments[4][51][0].apply(exports,arguments) -},{"./iterator":189,"abstract-leveldown":192,"buffer":156,"dup":51,"idb-wrapper":170,"isbuffer":175,"typedarray-to-buffer":225,"util":229,"xtend":199}],189:[function(require,module,exports){ -arguments[4][52][0].apply(exports,arguments) -},{"abstract-leveldown":192,"dup":52,"ltgt":203,"util":229}],190:[function(require,module,exports){ -arguments[4][53][0].apply(exports,arguments) -},{"_process":206,"dup":53}],191:[function(require,module,exports){ -arguments[4][12][0].apply(exports,arguments) -},{"_process":206,"dup":12}],192:[function(require,module,exports){ -(function (Buffer,process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ - -var xtend = require('xtend') - , AbstractIterator = require('./abstract-iterator') - , AbstractChainedBatch = require('./abstract-chained-batch') - -function AbstractLevelDOWN (location) { - if (!arguments.length || location === undefined) - throw new Error('constructor requires at least a location argument') +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; - if (typeof location != 'string') - throw new Error('constructor requires a location string argument') +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; - this.location = location +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; } -AbstractLevelDOWN.prototype.open = function (options, callback) { - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('open() requires a callback argument') - - if (typeof options != 'object') - options = {} +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} - if (typeof this._open == 'function') - return this._open(options, callback) +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; - process.nextTick(callback) -} + if (n !== 0) state.emittedReadable = false; -AbstractLevelDOWN.prototype.close = function (callback) { - if (typeof callback != 'function') - throw new Error('close() requires a callback argument') + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } - if (typeof this._close == 'function') - return this._close(callback) + n = howMuchToRead(n, state); - process.nextTick(callback) -} + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } -AbstractLevelDOWN.prototype.get = function (key, options, callback) { - var err + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - if (typeof options == 'function') - callback = options + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); - if (typeof callback != 'function') - throw new Error('get() requires a callback argument') + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } - if (err = this._checkKeyValue(key, 'key', this._isBuffer)) - return callback(err) + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } - if (!this._isBuffer(key)) - key = String(key) + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - if (typeof options != 'object') - options = {} + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } - if (typeof this._get == 'function') - return this._get(key, options, callback) + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - process.nextTick(function () { callback(new Error('NotFound')) }) -} + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } -AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { - var err + if (ret !== null) this.emit('data', ret); - if (typeof options == 'function') - callback = options + return ret; +}; - if (typeof callback != 'function') - throw new Error('put() requires a callback argument') +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; - if (err = this._checkKeyValue(key, 'key', this._isBuffer)) - return callback(err) + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} - if (err = this._checkKeyValue(value, 'value', this._isBuffer)) - return callback(err) +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} - if (!this._isBuffer(key)) - key = String(key) +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} - // coerce value to string in node, don't touch it in browser - // (indexeddb can store any JS type) - if (!this._isBuffer(value) && !process.browser) - value = String(value) +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} - if (typeof options != 'object') - options = {} +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} - if (typeof this._put == 'function') - return this._put(key, value, options, callback) +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; - process.nextTick(callback) -} +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; -AbstractLevelDOWN.prototype.del = function (key, options, callback) { - var err + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - if (typeof options == 'function') - callback = options + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - if (typeof callback != 'function') - throw new Error('del() requires a callback argument') + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); - if (err = this._checkKeyValue(key, 'key', this._isBuffer)) - return callback(err) + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } - if (!this._isBuffer(key)) - key = String(key) + function onend() { + debug('onend'); + dest.end(); + } - if (typeof options != 'object') - options = {} + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - if (typeof this._del == 'function') - return this._del(key, options, callback) + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + 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); - process.nextTick(callback) -} + cleanedUp = true; -AbstractLevelDOWN.prototype.batch = function (array, options, callback) { - if (!arguments.length) - return this._chainedBatch() + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - if (typeof options == 'function') - callback = options + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } - if (typeof callback != 'function') - throw new Error('batch(array) requires a callback argument') + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } - if (!Array.isArray(array)) - return callback(new Error('batch(array) requires an array argument')) + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - if (typeof options != 'object') - options = {} + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - var i = 0 - , l = array.length - , e - , err + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } - for (; i < l; i++) { - e = array[i] - if (typeof e != 'object') - continue + // tell the dest that it's being piped to + dest.emit('pipe', src); - if (err = this._checkKeyValue(e.type, 'type', this._isBuffer)) - return callback(err) + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } - if (err = this._checkKeyValue(e.key, 'key', this._isBuffer)) - return callback(err) + return dest; +}; - if (e.type == 'put') { - if (err = this._checkKeyValue(e.value, 'value', this._isBuffer)) - return callback(err) +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); } - } - - if (typeof this._batch == 'function') - return this._batch(array, options, callback) - - process.nextTick(callback) + }; } -//TODO: remove from here, not a necessary primitive -AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) { - if ( start == null - || end == null - || typeof start == 'function' - || typeof end == 'function') { - throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') - } - - if (typeof callback != 'function') - throw new Error('approximateSize() requires a callback argument') +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; - if (!this._isBuffer(start)) - start = String(start) + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - if (!this._isBuffer(end)) - end = String(end) + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - if (typeof this._approximateSize == 'function') - return this._approximateSize(start, end, callback) + if (!dest) dest = state.pipes; - process.nextTick(function () { - callback(null, 0) - }) -} + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } -AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { - var self = this + // slow case. multiple pipe destinations. - options = xtend(options) + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) { - if (options[o] && self._isBuffer(options[o]) && options[o].length === 0) - delete options[o] - }) + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } - options.reverse = !!options.reverse + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; - // fix `start` so it takes into account gt, gte, lt, lte as appropriate - if (options.reverse && options.lt) - options.start = options.lt - if (options.reverse && options.lte) - options.start = options.lte - if (!options.reverse && options.gt) - options.start = options.gt - if (!options.reverse && options.gte) - options.start = options.gte + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - if ((options.reverse && options.lt && !options.lte) - || (!options.reverse && options.gt && !options.gte)) - options.exclusiveStart = true // start should *not* include matching key + dest.emit('unpipe', this, unpipeInfo); - return options -} + return this; +}; -AbstractLevelDOWN.prototype.iterator = function (options) { - if (typeof options != 'object') - options = {} +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); - options = this._setupIteratorOptions(options) + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } - if (typeof this._iterator == 'function') - return this._iterator(options) + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; - return new AbstractIterator(this) +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); } -AbstractLevelDOWN.prototype._chainedBatch = function () { - return new AbstractChainedBatch(this) -} +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; -AbstractLevelDOWN.prototype._isBuffer = function (obj) { - return Buffer.isBuffer(obj) +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } } -AbstractLevelDOWN.prototype._checkKeyValue = function (obj, type) { - - if (obj === null || obj === undefined) - return new Error(type + ' cannot be `null` or `undefined`') +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } - if (this._isBuffer(obj)) { - if (obj.length === 0) - return new Error(type + ' cannot be an empty Buffer') - } else if (String(obj) === '') - return new Error(type + ' cannot be an empty String') + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); } -module.exports.AbstractLevelDOWN = AbstractLevelDOWN -module.exports.AbstractIterator = AbstractIterator -module.exports.AbstractChainedBatch = AbstractChainedBatch +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; -}).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) -},{"../../../is-buffer/index.js":173,"./abstract-chained-batch":190,"./abstract-iterator":191,"_process":206,"xtend":193}],193:[function(require,module,exports){ -arguments[4][56][0].apply(exports,arguments) -},{"dup":56}],194:[function(require,module,exports){ -arguments[4][64][0].apply(exports,arguments) -},{"dup":64}],195:[function(require,module,exports){ -arguments[4][65][0].apply(exports,arguments) -},{"./shim":197,"dup":65}],196:[function(require,module,exports){ -arguments[4][66][0].apply(exports,arguments) -},{"dup":66}],197:[function(require,module,exports){ -arguments[4][67][0].apply(exports,arguments) -},{"./foreach":194,"./isArguments":196,"dup":67}],198:[function(require,module,exports){ -arguments[4][57][0].apply(exports,arguments) -},{"dup":57}],199:[function(require,module,exports){ -arguments[4][58][0].apply(exports,arguments) -},{"./has-keys":198,"dup":58,"object-keys":195}],200:[function(require,module,exports){ -arguments[4][59][0].apply(exports,arguments) -},{"./util":202,"dup":59,"level-errors":178}],201:[function(require,module,exports){ -arguments[4][60][0].apply(exports,arguments) -},{"./batch":200,"./leveldown":154,"./util":202,"_process":206,"deferred-leveldown":160,"dup":60,"events":169,"level-codec":176,"level-errors":178,"level-iterator-stream":179,"prr":207,"util":229,"xtend":230}],202:[function(require,module,exports){ -arguments[4][61][0].apply(exports,arguments) -},{"dup":61,"xtend":230}],203:[function(require,module,exports){ -(function (Buffer){ +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} -exports.compare = function (a, b) { +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; - if(Buffer.isBuffer(a)) { - var l = Math.min(a.length, b.length) - for(var i = 0; i < l; i++) { - var cmp = a[i] - b[i] - if(cmp) return cmp + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); } - return a.length - b.length - } - return a < b ? -1 : a > b ? 1 : 0 -} - -function has(obj, key) { - return Object.hasOwnProperty.call(obj, key) -} + self.push(null); + }); -// to be compatible with the current abstract-leveldown tests -// nullish or empty strings. -// I could use !!val but I want to permit numbers and booleans, -// if possible. + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); -function isDef (val) { - return val !== undefined && val !== '' -} + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; -function has (range, name) { - return Object.hasOwnProperty.call(range, name) -} + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); -function hasKey(range, name) { - return Object.hasOwnProperty.call(range, name) && name -} + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } -var lowerBoundKey = exports.lowerBoundKey = function (range) { - return ( - hasKey(range, 'gt') - || hasKey(range, 'gte') - || hasKey(range, 'min') - || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start')) - || undefined - ) -} + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); + } -var lowerBound = exports.lowerBound = function (range, def) { - var k = lowerBoundKey(range) - return k ? range[k] : def -} + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; -var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) { - return has(range, 'gt') ? false : true -} + return self; +}; -var upperBoundInclusive = exports.upperBoundInclusive = - function (range) { - return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true - } +// exposed for testing purposes only. +Readable._fromList = fromList; -var lowerBoundExclusive = exports.lowerBoundExclusive = - function (range) { - return !lowerBoundInclusive(range) - } +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; -var upperBoundExclusive = exports.upperBoundExclusive = - function (range) { - return !upperBoundInclusive(range) + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); } -var upperBoundKey = exports.upperBoundKey = function (range) { - return ( - hasKey(range, 'lt') - || hasKey(range, 'lte') - || hasKey(range, 'max') - || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end')) - || undefined - ) -} - -var upperBound = exports.upperBound = function (range, def) { - var k = upperBoundKey(range) - return k ? range[k] : def + return ret; } -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) - ) +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; } -function id (e) { return e } - -exports.toLtgt = function (range, _range, map, lower, upper) { - _range = _range || {} - map = map || id - var defaults = arguments.length > 3 - var lb = exports.lowerBoundKey(range) - var ub = exports.upperBoundKey(range) - if(lb) { - if(lb === 'gt') _range.gt = map(range.gt, false) - else _range.gte = map(range[lb], false) +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; } - else if(defaults) - _range.gte = map(lower, false) + list.length -= c; + return ret; +} - if(ub) { - if(ub === 'lt') _range.lt = map(range.lt, true) - else _range.lte = map(range[ub], true) +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; } - else if(defaults) - _range.lte = map(upper, true) + list.length -= c; + return ret; +} - if(range.reverse != null) - _range.reverse = !!range.reverse +function endReadable(stream) { + var state = stream._readableState; - //if range was used mutably - //(in level-sublevel it's part of an options object - //that has more properties on it.) - if(has(_range, 'max')) delete _range.max - if(has(_range, 'min')) delete _range.min - if(has(_range, 'start')) delete _range.start - if(has(_range, 'end')) delete _range.end + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - return _range + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } } -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 || (cmp === 0 && lowerBoundExclusive(range))) - return false +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); } +} - var ub = upperBound(range) - if(isDef(ub)) { - var cmp = compare(key, ub) - if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range)) - return false +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); } - - return true } -exports.filter = function (range, compare) { - return function (key) { - return exports.contains(range, key, compare) +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } + return -1; } +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":90,"./internal/streams/BufferList":95,"./internal/streams/destroy":96,"./internal/streams/stream":97,"_process":85,"core-util-is":11,"events":37,"inherits":40,"isarray":43,"process-nextick-args":84,"safe-buffer":102,"string_decoder/":149,"util":7}],93:[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 +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. +'use strict'; -}).call(this,{"isBuffer":require("../is-buffer/index.js")}) -},{"../is-buffer/index.js":173}],204:[function(require,module,exports){ -exports.endianness = function () { return 'LE' }; - -exports.hostname = function () { - if (typeof location !== 'undefined') { - return location.hostname - } - else return ''; -}; - -exports.loadavg = function () { return [] }; - -exports.uptime = function () { return 0 }; - -exports.freemem = function () { - return Number.MAX_VALUE; -}; - -exports.totalmem = function () { - return Number.MAX_VALUE; -}; +module.exports = Transform; -exports.cpus = function () { return [] }; +var Duplex = require('./_stream_duplex'); -exports.type = function () { return 'Browser' }; +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ -exports.release = function () { - if (typeof navigator !== 'undefined') { - return navigator.appVersion; - } - return ''; -}; +util.inherits(Transform, Duplex); -exports.networkInterfaces -= exports.getNetworkInterfaces -= function () { return {} }; +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; -exports.arch = function () { return 'javascript' }; + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} -exports.platform = function () { return 'browser' }; +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; -exports.tmpdir = exports.tmpDir = function () { - return '/tmp'; -}; + var cb = ts.writecb; -exports.EOL = '\n'; + if (!cb) { + return stream.emit('error', new Error('write callback called multiple times')); + } -},{}],205:[function(require,module,exports){ -arguments[4][69][0].apply(exports,arguments) -},{"_process":206,"dup":69}],206:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; + ts.writechunk = null; + ts.writecb = null; -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. + if (data !== null && data !== undefined) stream.push(data); -var cachedSetTimeout; -var cachedClearTimeout; + cb(er); -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } } -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } + Duplex.call(this, options); + this._transformState = new TransformState(this); + var stream = this; -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er, data) { + done(stream, er, data); + });else done(stream); + }); } -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); }; -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } }; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; -function noop() {} +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; -process.listeners = function (name) { return [] } +Transform.prototype._destroy = function (err, cb) { + var _this = this; -process.binding = function (name) { - throw new Error('process.binding is not supported'); + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this.emit('close'); + }); }; -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; +function done(stream, er, data) { + if (er) return stream.emit('error', er); -},{}],207:[function(require,module,exports){ -arguments[4][33][0].apply(exports,arguments) -},{"dup":33}],208:[function(require,module,exports){ -module.exports = require('./lib/_stream_duplex.js'); + if (data !== null && data !== undefined) stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); -},{"./lib/_stream_duplex.js":209}],209:[function(require,module,exports){ + return stream.push(null); +} +},{"./_stream_duplex":90,"core-util-is":11,"inherits":40}],94:[function(require,module,exports){ +(function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -32092,2420 +26765,4682 @@ module.exports = require('./lib/_stream_duplex.js'); // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. +// 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'; + +/**/ + +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; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + +var destroyImpl = require('./internal/streams/destroy'); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // 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. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // 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'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // 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. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; -'use strict'; + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; -/**/ + // count buffered requests + this.bufferedRequestCount = 0; -var processNextTick = require('process-nextick-args'); -/**/ + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; }; -/**/ -module.exports = Duplex; +(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 util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} -util.inherits(Duplex, Readable); +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); -var keys = objectKeys(Writable.prototype); -for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; -} + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } - Readable.call(this, options); - Writable.call(this, options); + this._writableState = new WritableState(options, this); - if (options && options.readable === false) this.readable = false; + // legacy. + this.writable = true; - if (options && options.writable === false) this.writable = false; + if (options) { + if (typeof options.write === 'function') this._write = options.write; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + if (typeof options.writev === 'function') this._writev = options.writev; - this.once('end', onend); -} + if (typeof options.destroy === 'function') this._destroy = options.destroy; -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + if (typeof options.final === 'function') this._final = options.final; + } - // no more data can be written. - // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); + Stream.call(this); } -function onEndNT(self) { - self.end(); +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); } -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; - } +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } -}); + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = _isUint8Array(chunk) && !state.objectMode; - processNextTick(cb, err); -}; + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } -} -},{"./_stream_readable":211,"./_stream_writable":213,"core-util-is":158,"inherits":172,"process-nextick-args":205}],210:[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. + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; -'use strict'; + if (typeof cb !== 'function') cb = nop; -module.exports = PassThrough; + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } -var Transform = require('./_stream_transform'); + return ret; +}; -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ +Writable.prototype.cork = function () { + var state = this._writableState; -util.inherits(PassThrough, Transform); + state.corked++; +}; -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); +Writable.prototype.uncork = function () { + var state = this._writableState; - Transform.call(this, options); -} + if (state.corked) { + state.corked--; -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } }; -},{"./_stream_transform":212,"core-util-is":158,"inherits":172}],211:[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. - -'use strict'; -/**/ +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; -var processNextTick = require('process-nextick-args'); -/**/ +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} -module.exports = Readable; +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; -/**/ -var isArray = require('isarray'); -/**/ + state.length += len; -/**/ -var Duplex; -/**/ + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; -Readable.ReadableState = ReadableState; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } -/**/ -var EE = require('events').EventEmitter; + return ret; +} -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} -/**/ -var Stream = require('./internal/streams/stream'); -/**/ +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; -// TODO(bmeurer): Change this back to const once hole checks are -// properly optimized away early in Ignition+TurboFan. -/**/ -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); + 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); + } } -/**/ - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ -/**/ -var debugUtil = require('util'); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } -/**/ -var BufferList = require('./internal/streams/BufferList'); -var destroyImpl = require('./internal/streams/destroy'); -var StringDecoder; +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; -util.inherits(Readable, Stream); + onwriteStateUpdate(state); -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } } } -function ReadableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} - options = options || {}; +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + doWrite(stream, state, true, state.length, buffer, '', holder.finish); - // 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 - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - // 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; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + if (entry === null) state.lastBufferedRequest = null; + } - // has it been destroyed - this.destroyed = false; + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = 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'; +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; +Writable.prototype._writev = null; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } -} -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - if (!(this instanceof Readable)) return new Readable(options); + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } - this._readableState = new ReadableState(options, this); + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; - // legacy - this.readable = true; +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +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'); + } + } +} - if (options) { - if (typeof options.read === 'function') this._read = options.read; +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} - if (typeof options.destroy === 'function') this._destroy = options.destroy; +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); } + state.ended = true; + stream.writable = false; +} - Stream.call(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; + } } -Object.defineProperty(Readable.prototype, 'destroyed', { +Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { - if (this._readableState === undefined) { + if (this._writableState === undefined) { return false; } - return this._readableState.destroyed; + return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet - if (!this._readableState) { + if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed - this._readableState.destroyed = value; + this._writableState.destroyed = value; } }); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); cb(err); }; +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":90,"./internal/streams/destroy":96,"./internal/streams/stream":97,"_process":85,"core-util-is":11,"inherits":40,"process-nextick-args":84,"safe-buffer":102,"util-deprecate":154}],95:[function(require,module,exports){ +'use strict'; -// 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; - 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; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = require('safe-buffer').Buffer; +/**/ + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; + 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; + }; -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; + 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; + }; -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } 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); - } + 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; + }; - 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 { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; + 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":102}],96:[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; } - 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); + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - if (state.needReadable) emitReadable(stream); + if (this._readableState) { + this._readableState.destroyed = true; } - 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'); + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; } - 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, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + 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); + } + }); } -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - return n; -} -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; } - return state.length; } -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; +function emitErrorNT(self, err) { + self.emit('error', err); +} - if (n !== 0) state.emittedReadable = false; +module.exports = { + destroy: destroy, + undestroy: undestroy +}; +},{"process-nextick-args":84}],97:[function(require,module,exports){ +module.exports = require('events').EventEmitter; - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } +},{"events":37}],98:[function(require,module,exports){ +module.exports = require('./readable').PassThrough - n = howMuchToRead(n, state); +},{"./readable":99}],99:[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'); - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } +},{"./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}],100:[function(require,module,exports){ +module.exports = require('./readable').Transform - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. +},{"./readable":99}],101:[function(require,module,exports){ +module.exports = require('./lib/_stream_writable.js'); - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); +},{"./lib/_stream_writable.js":94}],102:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); +// 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 +} - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } + return Buffer(arg, encodingOrOffset, length) +} - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } - - if (ret !== null) this.emit('data', ret); - - return ret; -}; - -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) } + } else { + buf.fill(0) } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); + return buf } -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return Buffer(size) } -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) } -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); - } +},{"buffer":9}],103:[function(require,module,exports){ +var hasProp = Object.prototype.hasOwnProperty; + +function throwsMessage(err) { + return '[Throws: ' + (err ? err.message : '?') + ']'; } -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; +function safeGetValueFromPropertyOnObject(obj, property) { + if (hasProp.call(obj, property)) { + try { + return obj[property]; + } + catch (err) { + return throwsMessage(err); + } + } + + return obj[property]; } -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; +function ensureProperties(obj) { + var seen = [ ]; // store references to objects we have seen before -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + function visit(obj) { + if (obj === null || typeof obj !== 'object') { + return obj; + } - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + if (seen.indexOf(obj) !== -1) { + return '[Circular]'; + } + seen.push(obj); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + if (typeof obj.toJSON === 'function') { + try { + return visit(obj.toJSON()); + } catch(err) { + return throwsMessage(err); + } + } - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + if (Array.isArray(obj)) { + return obj.map(visit); + } - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } + return Object.keys(obj).reduce(function(result, prop) { + // prevent faulty defined getter properties + result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop)); + return result; + }, {}); + }; - function onend() { - debug('onend'); - dest.end(); - } + return visit(obj); +} - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); +module.exports = function(data) { + return JSON.stringify(ensureProperties(data)); +} - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - 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); +module.exports.ensureProperties = ensureProperties; - cleanedUp = true; +},{}],104:[function(require,module,exports){ +/* +search-index-adder - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); +The module that adds documents into search-index' can also be run as a +standalone + +*/ + +const bunyan = require('bunyan') +const levelup = require('levelup') +const API = require('./lib/API.js') + +module.exports = function (givenOptions, callback) { + getOptions(givenOptions, function (err, options) { + const api = API(options) + const Indexer = {} + Indexer.options = options + Indexer.add = api.add + Indexer.concurrentAdd = api.concurrentAdd + Indexer.concurrentDel = api.concurrentDel + Indexer.close = api.close + Indexer.dbWriteStream = api.dbWriteStream + Indexer.defaultPipeline = api.defaultPipeline + Indexer.deleteStream = api.deleteStream + Indexer.deleter = api.deleter + Indexer.feed = api.feed + Indexer.flush = api.flush + return callback(err, Indexer) + }) +} + +const getOptions = function (options, done) { + options = Object.assign({}, { + appendOnly: false, + deletable: true, + batchSize: 1000, + compositeField: true, + fastSort: true, + fieldedSearch: true, + fieldOptions: {}, + preserveCase: false, + keySeparator: '○', + storeable: true, + storeDocument: true, + storeVector: true, + searchable: true, + indexPath: 'si', + logLevel: 'error', + nGramLength: 1, + nGramSeparator: ' ', + separator: /\s|\\n|\\u0003|[-.,<>]/, + stopwords: [], + weight: 0, + wildcard: true + }, options) + options.log = bunyan.createLogger({ + name: 'search-index', + level: options.logLevel + }) + if (!options.indexes) { + const leveldown = require('leveldown') + levelup(options.indexPath || 'si', { + valueEncoding: 'json', + db: leveldown + }, function (err, db) { + options.indexes = db + done(err, options) + }) + } else { + done(null, options) } +} - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); +},{"./lib/API.js":105,"bunyan":10,"leveldown":58,"levelup":71}],105:[function(require,module,exports){ +const DBEntries = require('./delete.js').DBEntries +const DBWriteCleanStream = require('./replicate.js').DBWriteCleanStream +const DBWriteMergeStream = require('./replicate.js').DBWriteMergeStream +const DocVector = require('./delete.js').DocVector +const JSONStream = require('JSONStream') +const Readable = require('stream').Readable +const RecalibrateDB = require('./delete.js').RecalibrateDB +const IndexBatch = require('./add.js').IndexBatch +const async = require('async') +const del = require('./delete.js') +const docProc = require('docproc') +const pumpify = require('pumpify') + +module.exports = function (options) { + const 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) + }) + s.push(null) + s.pipe(Indexer.defaultPipeline(batch.batchOps)) + .pipe(Indexer.add()) + .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) - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + const add = function (ops) { + // override options with every add + const thisOps = Object.assign(options, ops) + return pumpify.obj( + new IndexBatch(deleter, thisOps), + new DBWriteMergeStream(thisOps) + ) } - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + const concurrentAdd = function (batchOps, batch, done) { + q.push({ + batch: batch, + batchOps: batchOps, + operation: 'add' + }, function (err) { + done(err) + }) + } - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); + const concurrentDel = function (docIds, done) { + q.push({ + docIds: docIds, + operation: 'delete' + }, function (err) { + done(err) + }) } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + + const close = function (callback) { + options.indexes.close(function (err) { + while (!options.indexes.isClosed()) { + options.log.debug('closing...') + } + if (options.indexes.isClosed()) { + options.log.debug('closed...') + callback(err) + } + }) } - dest.once('finish', onfinish); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); + const dbWriteStream = function (streamOps) { + streamOps = Object.assign({}, { merge: true }, streamOps) + if (streamOps.merge) { + return new DBWriteMergeStream(options) + } else { + return new DBWriteCleanStream(options) + } } - // tell the dest that it's being piped to - dest.emit('pipe', src); + const defaultPipeline = function (batchOptions) { + batchOptions = Object.assign({}, options, batchOptions) + return docProc.pipeline(batchOptions) + } - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); + const deleteStream = function (options) { + return pumpify.obj( + new DocVector(options), + new DBEntries(options), + new RecalibrateDB(options) + ) } - return dest; -}; + const 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 () { + // nowt + }) + .on('end', function () { + done(null) + }) + } -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); + const feed = function (ops) { + if (ops && ops.objectMode) { + // feed from stream of objects + return pumpify.obj( + Indexer.defaultPipeline(ops), + Indexer.add(ops) + ) + } else { + // feed from stream of strings + return pumpify( + JSONStream.parse(), + Indexer.defaultPipeline(ops), + Indexer.add(ops) + ) } - }; -} - -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; + const flush = function (APICallback) { + del.flush(options, function (err) { + return APICallback(err) + }) + } - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + const Indexer = {} + Indexer.add = add + Indexer.concurrentAdd = concurrentAdd + Indexer.concurrentDel = concurrentDel + Indexer.close = close + Indexer.dbWriteStream = dbWriteStream + Indexer.defaultPipeline = defaultPipeline + Indexer.deleteStream = deleteStream + Indexer.deleter = deleter + Indexer.feed = feed + Indexer.flush = flush + return Indexer +} - if (!dest) dest = state.pipes; +},{"./add.js":106,"./delete.js":107,"./replicate.js":108,"JSONStream":3,"async":5,"docproc":19,"pumpify":88,"stream":147}],106:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; +const emitIndexKeys = function (s) { + for (var key in s.deltaIndex) { + s.push({ + key: key, + value: s.deltaIndex[key] + }) } + s.deltaIndex = {} +} - // slow case. multiple pipe destinations. +const noop = function (_, cb) { cb() } - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; +const IndexBatch = function (deleter, options) { + this.batchSize = options.batchSize || 1000 + this.deleter = deleter + this.fastSort = options.fastSort + this.appendOnly = options.appendOnly + this.keySeparator = options.keySeparator || '○' + this.log = options.log + this.storeDocument = options.storeDocument + this.storeVector = options.storeVector + this.deltaIndex = {} + Transform.call(this, { objectMode: true }) +} +exports.IndexBatch = IndexBatch +util.inherits(IndexBatch, Transform) +IndexBatch.prototype._transform = function (ingestedDoc, encoding, end) { + const sep = this.keySeparator + const that = this + const maybedelete = this.appendOnly ? noop : this.deleter.bind(this.indexer) + maybedelete([ingestedDoc.id], function (err) { + if (err) that.indexer.log.info(err) + that.log.info('processing doc ' + ingestedDoc.id) + if (that.storeDocument === true) { + 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]) { + if (that.fastSort) { + var vMagnitude = ingestedDoc.vector[fieldName][token] + var tfKeyName = 'TF' + sep + fieldName + sep + token + that.deltaIndex[tfKeyName] = that.deltaIndex[tfKeyName] || [] + that.deltaIndex[tfKeyName].push([vMagnitude, ingestedDoc.id]) + } + var dfKeyName = 'DF' + sep + fieldName + sep + token + that.deltaIndex[dfKeyName] = that.deltaIndex[dfKeyName] || [] + that.deltaIndex[dfKeyName].push(ingestedDoc.id) + } + if (that.storeVector) { + that.deltaIndex['DOCUMENT-VECTOR' + sep + fieldName + sep + ingestedDoc.id + sep] = + ingestedDoc.vector[fieldName] + } + } + var totalKeys = Object.keys(that.deltaIndex).length + if (totalKeys > that.batchSize) { + that.push({totalKeys: totalKeys}) + that.log.info( + 'deltaIndex is ' + totalKeys + ' long, emitting') + emitIndexKeys(that) + } + return end() + }) +} +IndexBatch.prototype._flush = function (end) { + // merge this index into main index + emitIndexKeys(this) + return end() +} - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; - } +},{"stream":147,"util":157}],107:[function(require,module,exports){ +// deletes all references to a document from the search index - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; +const util = require('util') +const Transform = require('stream').Transform - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; +// Remove all keys in DB +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) { + options.log.error(err, ' failed to empty index') + return callback(err) + }) + .on('end', function () { + options.indexes.batch(deleteOps, callback) + }) +} - dest.emit('unpipe', this, unpipeInfo); +const DocVector = function (options) { + this.options = options + Transform.call(this, { objectMode: true }) +} +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 + var docKey = 'DOCUMENT' + sep + docId + sep + this.options.indexes.get(docKey, function (err, val) { + if (err) return end() + var docFields = Object.keys(val) + docFields.push('*') // may not be there if compositeField: false + docFields = docFields.map(function (item) { + return 'DOCUMENT-VECTOR' + sep + item + sep + docId + sep + }) + var i = 0 + // get value from db and push it to the stream + var pushValue = function (key) { + if (key === undefined) { + that.push({ + key: 'DOCUMENT' + sep + docId + sep, + lastPass: true + }) + return end() + } + that.options.indexes.get(key, function (err, val) { + if (!err) { + that.push({ + key: key, + value: val + }) + } + pushValue(docFields[i++]) + }) + } + pushValue(docFields[0]) + }) +} - return this; -}; +const DBEntries = function (options) { + this.options = options + Transform.call(this, { objectMode: true }) +} +exports.DBEntries = DBEntries +util.inherits(DBEntries, Transform) +DBEntries.prototype._transform = function (vector, encoding, end) { + if (vector.lastPass === true) { + this.push({key: vector.key}) + return end() + } + const sep = this.options.keySeparator + var that = this + var field = vector.key.split(sep)[1] + var docId = vector.key.split(sep)[2] + var vectorKeys = Object.keys(vector.value) + var i = 0 + var pushRecalibrationvalues = function (vec) { + that.push({ + key: 'TF' + sep + field + sep + vectorKeys[i], + value: docId + }) + that.push({ + key: 'DF' + sep + field + sep + vectorKeys[i], + value: docId + }) + if (++i === vectorKeys.length) { + that.push({key: vector.key}) + return end() + } else { + pushRecalibrationvalues(vector[vectorKeys[i]]) + } + } + pushRecalibrationvalues(vector[vectorKeys[0]]) -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); + // TODO: fix this! + // this.push({key: 'DOCUMENT-COUNT'}) +} - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - processNextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); +const RecalibrateDB = function (options) { + this.options = options + this.batch = [] + Transform.call(this, { objectMode: true }) +} +exports.RecalibrateDB = RecalibrateDB +util.inherits(RecalibrateDB, Transform) +// todo: handle deletion of wildcards, and do batched deletes +RecalibrateDB.prototype._transform = function (dbEntry, encoding, end) { + const sep = this.options.keySeparator + var that = this + this.options.indexes.get(dbEntry.key, function (err, value) { + if (err) { + that.options.log.info(err) + } + // handle errors better + if (!value) value = [] + var docId = dbEntry.value + '' + var dbInstruction = {} + dbInstruction.key = dbEntry.key + if (dbEntry.key.substring(0, 3) === 'TF' + sep) { + dbInstruction.value = value.filter(function (item) { + return (item[1] !== docId) + }) + if (dbInstruction.value.length === 0) { + dbInstruction.type = 'del' + } else { + dbInstruction.type = 'put' + } + that.batch.push(dbInstruction) + return end() + } else if (dbEntry.key.substring(0, 3) === 'DF' + sep) { + value.splice(value.indexOf(docId), 1) + dbInstruction.value = value + if (dbInstruction.value.length === 0) { + dbInstruction.type = 'del' + } else { + dbInstruction.type = 'put' } + that.batch.push(dbInstruction) + return end() + } else if (dbEntry.key.substring(0, 16) === 'DOCUMENT-VECTOR' + sep) { + dbInstruction.type = 'del' + that.batch.push(dbInstruction) + return end() + } else if (dbEntry.key.substring(0, 9) === 'DOCUMENT' + sep) { + dbInstruction.type = 'del' + that.batch.push(dbInstruction) + // "DOCUMENT" should be the last instruction for the document + that.options.indexes.batch(that.batch, function (err) { + if (err) { + // then what? + } + that.batch = [] + return end() + }) } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); + }) } -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; +},{"stream":147,"util":157}],108:[function(require,module,exports){ +const Transform = require('stream').Transform +const Writable = require('stream').Writable +const util = require('util') -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); - } +const DBWriteMergeStream = function (options) { + this.options = options + Writable.call(this, { objectMode: true }) } - -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); +exports.DBWriteMergeStream = DBWriteMergeStream +util.inherits(DBWriteMergeStream, Writable) +DBWriteMergeStream.prototype._write = function (data, encoding, end) { + if (data.totalKeys) { + // this.push(data) + return end() } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); + const sep = this.options.keySeparator + var that = this + this.options.indexes.get(data.key, function (err, val) { + err // do something with this error + var newVal + // concat to existing values (only if they exist) + 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 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() + } else if (data.key === 'DOCUMENT-COUNT') { + newVal = (+val) + (+data.value || 0) + } else { + newVal = data.value + } + that.options.indexes.put(data.key, newVal, function (err) { + err // do something with this error + end() + }) + }) } -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); +const DBWriteCleanStream = function (options) { + this.currentBatch = [] + this.options = options + Transform.call(this, { objectMode: true }) +} +util.inherits(DBWriteCleanStream, Transform) +DBWriteCleanStream.prototype._transform = function (data, encoding, end) { + var that = this + this.currentBatch.push(data) + if (this.currentBatch.length % this.options.batchSize === 0) { + this.options.indexes.batch(this.currentBatch, function (err) { + // TODO: some nice error handling if things go wrong + err + that.push('indexing batch') + that.currentBatch = [] // reset batch + end() + }) + } else { + end() } - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} } +DBWriteCleanStream.prototype._flush = function (end) { + var that = this + this.options.indexes.batch(this.currentBatch, function (err) { + // TODO: some nice error handling if things go wrong + err + that.push('remaining data indexed') + end() + }) +} +exports.DBWriteCleanStream = DBWriteCleanStream -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); +},{"stream":147,"util":157}],109:[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 +const CalculateEntireResultSet = require('./lib/CalculateEntireResultSet.js').CalculateEntireResultSet +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 +const MergeOrConditionsTFIDF = require('./lib/MergeOrConditionsTFIDF.js').MergeOrConditionsTFIDF +const MergeOrConditionsFieldSort = require('./lib/MergeOrConditionsFieldSort.js').MergeOrConditionsFieldSort +const Readable = require('stream').Readable +const ScoreDocsOnField = require('./lib/ScoreDocsOnField.js').ScoreDocsOnField +const ScoreTopScoringDocsTFIDF = require('./lib/ScoreTopScoringDocsTFIDF.js').ScoreTopScoringDocsTFIDF +const bunyan = require('bunyan') +const levelup = require('levelup') +const matcher = require('./lib/matcher.js') +const siUtil = require('./lib/siUtil.js') +const sw = require('stopword') - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } +const initModule = function (err, Searcher, moduleReady) { + Searcher.bucketStream = function (q) { + q = siUtil.getQueryDefaults(q) + const s = new Readable({ objectMode: true }) + q.query.forEach(function (clause) { + s.push(clause) + }) + s.push(null) + return s + .pipe(new CalculateResultSetPerClause(Searcher.options, q.filter || {})) + .pipe(new CalculateEntireResultSet(Searcher.options)) + .pipe(new CalculateBuckets(Searcher.options, q.filter || {}, q.buckets)) } - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); + Searcher.categoryStream = function (q) { + q = siUtil.getQueryDefaults(q) + const s = new Readable({ objectMode: true }) + q.query.forEach(function (clause) { + s.push(clause) + }) + s.push(null) + return s + .pipe(new CalculateResultSetPerClause(Searcher.options, q.filter || {})) + .pipe(new CalculateEntireResultSet(Searcher.options)) + .pipe(new CalculateCategories(Searcher.options, q)) } - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - -// exposed for testing purposes only. -Readable._fromList = fromList; + Searcher.classify = function (ops) { + return new Classify(Searcher, ops) + } -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + Searcher.close = function (callback) { + Searcher.options.indexes.close(function (err) { + while (!Searcher.options.indexes.isClosed()) { + Searcher.options.log.debug('closing...') + } + if (Searcher.options.indexes.isClosed()) { + Searcher.options.log.debug('closed...') + callback(err) + } + }) + } - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); + 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)) } - return ret; -} + Searcher.get = function (docIDs) { + var s = new Readable({ objectMode: true }) + docIDs.forEach(function (id) { + s.push(id) + }) + s.push(null) + return s.pipe(new FetchDocsFromDB(Searcher.options)) + } -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + Searcher.fieldNames = function () { + return Searcher.options.indexes.createReadStream({ + gte: 'FIELD', + lte: 'FIELD' + }) } - return ret; -} -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; + Searcher.match = function (q) { + return matcher.match(q, Searcher.options) } - list.length -= c; - return ret; -} -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; + Searcher.dbReadStream = function () { + return Searcher.options.indexes.createReadStream() } - list.length -= c; - return ret; -} -function endReadable(stream) { - var state = stream._readableState; + Searcher.search = function (q) { + q = siUtil.getQueryDefaults(q) + const s = new Readable({ objectMode: true }) + q.query.forEach(function (clause) { + s.push(clause) + }) + s.push(null) + if (q.sort) { + /* - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + Can be 2 scenarios: + 1) Lots of hits in a smallish index (dense) + 2) a few hits in a gigantic index (sparse) - if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); - } -} + Since 2) can be solved by simply sorting afterwards- solve 1) first -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} + should be -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} + 1) Calculate resultset per clause + 2) Traverse TF arrays and check for intersections down to "seek limit" + 3) Merge/trim pages/sort + 4) Fetch stored docs -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + */ + return s + .pipe(new CalculateResultSetPerClause(Searcher.options)) + .pipe(new ScoreDocsOnField(Searcher.options, (q.offset + q.pageSize), q.sort)) + .pipe(new MergeOrConditionsFieldSort(q)) + .pipe(new FetchStoredDoc(Searcher.options)) + } else { + return s + .pipe(new CalculateResultSetPerClause(Searcher.options)) + .pipe(new CalculateTopScoringDocs(Searcher.options, q.offset, q.pageSize)) + .pipe(new ScoreTopScoringDocsTFIDF(Searcher.options)) + .pipe(new MergeOrConditionsTFIDF(q.offset, q.pageSize)) + .pipe(new FetchStoredDoc(Searcher.options)) + } } - return -1; -} -}).call(this,require('_process')) -},{"./_stream_duplex":209,"./internal/streams/BufferList":214,"./internal/streams/destroy":215,"./internal/streams/stream":216,"_process":206,"core-util-is":158,"events":169,"inherits":172,"isarray":174,"process-nextick-args":205,"safe-buffer":221,"string_decoder/":224,"util":154}],212:[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 -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; + // TODO: seriously needs a rewrite + Searcher.scan = function (q) { + q = siUtil.getQueryDefaults(q) + // just make this work for a simple one clause AND + // TODO: add filtering, NOTting, multi-clause AND + var s = new Readable({ objectMode: true }) + s.push('init') + s.push(null) + return s + .pipe(new GetIntersectionStream(Searcher.options, + siUtil.getKeySet( + q.query[0].AND, + Searcher.options.keySeparator + ))) + .pipe(new FetchDocsFromDB(Searcher.options)) + } -module.exports = Transform; + Searcher.totalHits = function (q, callback) { + q = siUtil.getQueryDefaults(q) + const s = new Readable({ objectMode: true }) + 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) + }) + } -var Duplex = require('./_stream_duplex'); + return moduleReady(err, Searcher) +} -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ +const getOptions = function (options, done) { + var Searcher = {} + Searcher.options = Object.assign({}, { + deletable: true, + fieldedSearch: true, + store: true, + indexPath: 'si', + keySeparator: '○', + logLevel: 'error', + nGramLength: 1, + nGramSeparator: ' ', + separator: /[|' .,\-|(\n)]+/, + stopwords: sw.en + }, options) + Searcher.options.log = bunyan.createLogger({ + name: 'search-index', + level: options.logLevel + }) + if (!options.indexes) { + levelup(Searcher.options.indexPath || 'si', { + valueEncoding: 'json' + }, function (err, db) { + Searcher.options.indexes = db + return done(err, Searcher) + }) + } else { + return done(null, Searcher) + } +} -util.inherits(Transform, Duplex); +module.exports = function (givenOptions, moduleReady) { + getOptions(givenOptions, function (err, Searcher) { + initModule(err, Searcher, moduleReady) + }) +} -function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; +},{"./lib/AvailableFields.js":110,"./lib/CalculateBuckets.js":111,"./lib/CalculateCategories.js":112,"./lib/CalculateEntireResultSet.js":113,"./lib/CalculateResultSetPerClause.js":114,"./lib/CalculateTopScoringDocs.js":115,"./lib/CalculateTotalHits.js":116,"./lib/Classify.js":117,"./lib/FetchDocsFromDB.js":118,"./lib/FetchStoredDoc.js":119,"./lib/GetIntersectionStream.js":120,"./lib/MergeOrConditionsFieldSort.js":121,"./lib/MergeOrConditionsTFIDF.js":122,"./lib/ScoreDocsOnField.js":123,"./lib/ScoreTopScoringDocsTFIDF.js":124,"./lib/matcher.js":125,"./lib/siUtil.js":126,"bunyan":10,"levelup":71,"stopword":127,"stream":147}],110:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; +const AvailableFields = function (options) { + this.options = options + Transform.call(this, { objectMode: true }) +} +exports.AvailableFields = AvailableFields +util.inherits(AvailableFields, Transform) +AvailableFields.prototype._transform = function (field, encoding, end) { + this.push(field.key.split(this.options.keySeparator)[1]) + return end() } -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; +},{"stream":147,"util":157}],111:[function(require,module,exports){ +const _intersection = require('lodash.intersection') +const _uniq = require('lodash.uniq') +const Transform = require('stream').Transform +const util = require('util') - var cb = ts.writecb; +const CalculateBuckets = function (options, filter, requestedBuckets) { + this.buckets = requestedBuckets || [] + this.filter = filter + this.options = options + Transform.call(this, { objectMode: true }) +} +exports.CalculateBuckets = CalculateBuckets +util.inherits(CalculateBuckets, Transform) +CalculateBuckets.prototype._transform = function (mergedQueryClauses, encoding, end) { + const that = this + const sep = this.options.keySeparator + var bucketsProcessed = 0 + that.buckets.forEach(function (bucket) { + const gte = 'DF' + sep + bucket.field + sep + bucket.gte + const 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) + if (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) + if (++bucketsProcessed === that.buckets.length) { + return end() + } + }) + }) +} - if (!cb) { - return stream.emit('error', new Error('write callback called multiple times')); +},{"lodash.intersection":74,"lodash.uniq":79,"stream":147,"util":157}],112:[function(require,module,exports){ +const _intersection = require('lodash.intersection') +const Transform = require('stream').Transform +const util = require('util') + +const CalculateCategories = function (options, q) { + var category = q.category || [] + category.values = [] // breaky line + this.offset = +q.offset + this.pageSize = +q.pageSize + this.category = category + this.options = options + this.query = q.query + Transform.call(this, { objectMode: true }) +} +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 + const that = this + const gte = 'DF' + sep + this.category.field + sep + const lte = 'DF' + sep + this.category.field + sep + sep + this.category.values = this.category.values || [] + var i = this.offset + this.pageSize + var j = 0 + const rs = that.options.indexes.createReadStream({gte: gte, lte: lte}) + rs.on('data', function (data) { + // page not yet reached + if (that.offset > j++) return + var IDSet = _intersection(data.value, mergedQueryClauses.set) + if (IDSet.length > 0) { // make this optional + var key = data.key.split(sep)[2] + var value = IDSet.length + if (that.category.set) { + value = IDSet + } + var result = { + key: key, + value: value + } + // set filter: true on queries with a single OR clause + if (that.query.length === 1) { + try { + if (that.query[0].AND[that.category.field].indexOf(key) > -1) { + result.filter = true + } + } catch (e) {} + } + // page size exceeded + if (i-- > that.offset) { + that.push(result) + } else { + rs.destroy() + } + } + }).on('close', function () { + return end() + }) +} - ts.writechunk = null; - ts.writecb = null; +},{"lodash.intersection":74,"stream":147,"util":157}],113:[function(require,module,exports){ +const Transform = require('stream').Transform +const _union = require('lodash.union') +const util = require('util') - if (data !== null && data !== undefined) stream.push(data); +const CalculateEntireResultSet = function (options) { + this.options = options + this.setSoFar = [] + Transform.call(this, { objectMode: true }) +} +exports.CalculateEntireResultSet = CalculateEntireResultSet +util.inherits(CalculateEntireResultSet, Transform) +CalculateEntireResultSet.prototype._transform = function (queryClause, encoding, end) { + this.setSoFar = _union(queryClause.set, this.setSoFar) + return end() +} +CalculateEntireResultSet.prototype._flush = function (end) { + this.push({ + set: this.setSoFar + }) + return end() +} - cb(er); +},{"lodash.union":78,"stream":147,"util":157}],114:[function(require,module,exports){ +const Transform = require('stream').Transform +const _difference = require('lodash.difference') +const _intersection = require('lodash.intersection') +const _spread = require('lodash.spread') +const siUtil = require('./siUtil.js') +const util = require('util') - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); +const CalculateResultSetPerClause = function (options) { + this.options = options + Transform.call(this, { objectMode: true }) +} +exports.CalculateResultSetPerClause = CalculateResultSetPerClause +util.inherits(CalculateResultSetPerClause, Transform) +CalculateResultSetPerClause.prototype._transform = function (queryClause, encoding, end) { + const sep = this.options.keySeparator + const that = this + const frequencies = [] + var NOT = function (includeResults) { + const bigIntersect = _spread(_intersection) + var include = bigIntersect(includeResults) + // if there are no NOT conditions, simply end() + if (siUtil.getKeySet(queryClause.NOT, sep).length === 0) { + that.push({ + queryClause: queryClause, + set: include, + documentFrequencies: frequencies, + WEIGHT: queryClause.WEIGHT || 1 + }) + return end() + } else { + // if there ARE "NOT"-conditions, remove all IDs specified by NOT + var i = 0 + var 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; i < data.value.length; i++) { + excludeSet[data.value[i]] = 1 + } + }) + .on('error', function (err) { + that.options.log.debug(err) + }) + .on('end', function () { + var exclude = Object.keys(excludeSet) + excludeResults.push(exclude.sort()) + if (++i === siUtil.getKeySet(queryClause.NOT, sep).length) { + excludeResults.forEach(function (excludeSet) { + include = _difference(include, excludeSet) + }) + that.push({ + queryClause: queryClause, + set: include, + documentFrequencies: frequencies, + WEIGHT: queryClause.WEIGHT || 1 + }) + return end() + } + }) + }) + } } + // Get all of the IDs in the AND conditions + var IDSets = [] + siUtil.getKeySet(queryClause.AND, sep).forEach(function (item) { + var includeSet = {} + var setLength = 0 + that.options.indexes.createReadStream({gte: item[0], lte: item[1]}) + .on('data', function (data) { + setLength += data.value.length + for (var i = 0; i < data.value.length; i++) { + includeSet[data.value[i]] = 1 + } + }) + .on('error', function (err) { + that.options.log.debug(err) + }) + .on('end', function () { + var include = Object.keys(includeSet) + frequencies.push({ + field: item[0].split(sep)[1], + gte: item[0].split(sep)[2], + lte: item[1].split(sep)[2], + df: include.length, // term frequency- number of docs that term appears in + setLength: setLength // number of array elements that need to be traversed + }) + IDSets.push(include.sort()) + if (IDSets.length === siUtil.getKeySet(queryClause.AND, sep).length) { + NOT(IDSets) + } + }) + }) } -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - - Duplex.call(this, options); - - this._transformState = new TransformState(this); - - var stream = this; +},{"./siUtil.js":126,"lodash.difference":73,"lodash.intersection":74,"lodash.spread":77,"stream":147,"util":157}],115:[function(require,module,exports){ +const Transform = require('stream').Transform +const _sortedIndexOf = require('lodash.sortedindexof') +const util = require('util') - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; +const CalculateTopScoringDocs = function (options, offset, pageSize) { + this.options = options + this.offset = offset + this.pageSize = pageSize + this.seekLimit = offset + pageSize + Transform.call(this, { objectMode: true }) +} +exports.CalculateTopScoringDocs = CalculateTopScoringDocs +util.inherits(CalculateTopScoringDocs, Transform) +CalculateTopScoringDocs.prototype._transform = function (clauseSet, encoding, end) { + const sep = this.options.keySeparator + // clauseSet = JSON.parse(clauseSet) + const that = this - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + // use smallest token set (lowest document frequency) + const lowestFrequency = clauseSet.documentFrequencies.sort(function (a, b) { + return a.setLength - b.setLength + })[0] - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + const gte = 'TF' + sep + lowestFrequency.gte + const lte = 'TF' + sep + lowestFrequency.lte + sep - if (typeof options.flush === 'function') this._flush = options.flush; - } + // walk down the DF array of lowest frequency hit until (offset + + // pagesize) hits have been found - // When the writable side finishes, then flush out anything remaining. - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er, data) { - done(stream, er, data); - });else done(stream); - }); + var topScoringDocs = [] + that.options.indexes.createReadStream({gte: gte, lte: lte}) + .on('data', function (data) { + var intersections = [] + // Do intersection and pagination cutoffs here- only push + // results that are in the resultset + for (var i = 0 + ; ((i < data.value.length) && (intersections.length < that.seekLimit)); i++) { + if (_sortedIndexOf(clauseSet.set, data.value[i][1]) !== -1) { + intersections.push(data.value[i]) + } + } + topScoringDocs = topScoringDocs.concat(intersections) + }) + .on('error', function (err) { + that.options.log.debug(err) + }) + .on('end', function () { + // if no TF keys were present, then index has been generated + // with fastSort disabled. Simply return a page (offset + + // pageSize) sized slice from the beginning of the clauseSet + if (topScoringDocs.length === 0) { + topScoringDocs = clauseSet.set + // slice results from end of array since it is sorted ascendingly + .slice(-that.seekLimit, clauseSet.set.length) + .map(function (id) { + return [1, id] + }) + } + // fetch document vectors for the highest scores and work out + // complete score for each selected doc. + clauseSet['topScoringDocs'] = topScoringDocs + that.push(clauseSet) + return end() + }) } -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; +},{"lodash.sortedindexof":76,"stream":147,"util":157}],116:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; +const CalculateTotalHits = function (options, filter, requestedBuckets) { + this.buckets = requestedBuckets || [] + this.filter = filter + this.options = options + Transform.call(this, { objectMode: true }) +} +exports.CalculateTotalHits = CalculateTotalHits +util.inherits(CalculateTotalHits, Transform) +CalculateTotalHits.prototype._transform = function (mergedQueryClauses, encoding, end) { + this.push(mergedQueryClauses.set.length) + end() +} -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; +},{"stream":147,"util":157}],117:[function(require,module,exports){ +const Transform = require('stream').Transform +const ngraminator = require('ngraminator') +const util = require('util') - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; +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], + field: field, + type: 'ID', + sort: 'alphabetical', + threshold: 0 + } + that.searcher.match(matchQuery) + .on('data', function (match) { + if (match.token === potentialMatches[i]) { that.push(match) } + }).on('end', function () { + match(++i) + }) } -}; - -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); - - if (data !== null && data !== undefined) stream.push(data); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + match(0) +} - if (ws.length) throw new Error('Calling transform done when ws.length != 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 }) +} - if (ts.transforming) throw new Error('Calling transform done when still transforming'); +exports.Classify = Classify - return stream.push(null); -} -},{"./_stream_duplex":209,"core-util-is":158,"inherits":172}],213:[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. +util.inherits(Classify, Transform) -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. +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() + }) +} -'use strict'; +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":81,"stream":147,"util":157}],118:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') -var processNextTick = require('process-nextick-args'); -/**/ +const FetchDocsFromDB = function (options) { + this.options = options + Transform.call(this, { objectMode: true }) +} +exports.FetchDocsFromDB = FetchDocsFromDB +util.inherits(FetchDocsFromDB, Transform) +FetchDocsFromDB.prototype._transform = function (line, encoding, end) { + const sep = this.options.keySeparator + const that = this + this.options.indexes.get('DOCUMENT' + sep + line.toString() + sep, function (err, doc) { + if (!err) { + that.push(doc) + } + end() + }) +} -module.exports = Writable; +},{"stream":147,"util":157}],119:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; +const FetchStoredDoc = function (options) { + this.options = options + Transform.call(this, { objectMode: true }) +} +exports.FetchStoredDoc = FetchStoredDoc +util.inherits(FetchStoredDoc, Transform) +FetchStoredDoc.prototype._transform = function (doc, encoding, end) { + const sep = this.options.keySeparator + var that = this + // doc = JSON.parse(doc) + that.options.indexes.get('DOCUMENT' + sep + doc.id + sep, function (err, stored) { + if (err) that.options.log.debug(err) + if (stored) { + doc.document = stored + } + that.push(doc) + return end() + }) } -// 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; +},{"stream":147,"util":157}],120:[function(require,module,exports){ +const Transform = require('stream').Transform +const iats = require('intersect-arrays-to-stream') +const util = require('util') - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; +// Make a Transform stream stage to get an intersection stream +const GetIntersectionStream = function (options, ANDKeys) { + this.ANDKeys = ANDKeys + this.options = options + Transform.call(this, { objectMode: true }) +} +exports.GetIntersectionStream = GetIntersectionStream +util.inherits(GetIntersectionStream, Transform) +GetIntersectionStream.prototype._transform = function (line, encoding, end) { + const that = this + var IDSets = [] + this.ANDKeys.forEach(function (item) { + var ANDSetIDs = [] + that.options.indexes.createReadStream({gte: item[0], lte: item[1]}) + .on('data', function (data) { + ANDSetIDs = ANDSetIDs.concat(data.value).sort() + }) + .on('end', function () { + IDSets.push(ANDSetIDs) + if (IDSets.length === that.ANDKeys.length) { + iats.getIntersectionStream(IDSets).on('data', function (data) { + that.push(data) + }).on('end', function () { + end() + }) + } + }) + }) } -/* */ -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; -/**/ +},{"intersect-arrays-to-stream":41,"stream":147,"util":157}],121:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') -/**/ -var Duplex; -/**/ +const MergeOrConditionsFieldSort = function (q) { + this.resultSet = [] + this.offset = q.offset + this.pageSize = q.pageSize + this.sortDirection = q.sort.direction || 'desc' + Transform.call(this, { objectMode: true }) +} +exports.MergeOrConditionsFieldSort = MergeOrConditionsFieldSort +util.inherits(MergeOrConditionsFieldSort, Transform) +MergeOrConditionsFieldSort.prototype._transform = function (clause, encoding, end) { + this.resultSet = this.resultSet.concat(clause.topScoringDocs) + return end() +} +MergeOrConditionsFieldSort.prototype._flush = function (end) { + var that = this + // turn top scoring results into a merged map + var resultMap = getResultMap(this.resultSet) + Object.keys(resultMap).map((id) => { + return { + id: id, + scoringCriteria: resultMap[id], + score: resultMap[id][0].score // all scores should be the same so just take first one + } + }).sort((a, b) => { + // sort by score then id descending + if (b.score === a.score) { + return (a.id < b.id) ? 1 : (a.id > b.id) ? -1 : 0 + } -Writable.WritableState = WritableState; + // TODO add numeric sorts -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + if (that.sortDirection === 'asc') { + return (b.score < a.score) + } else { + return (b.score > a.score) + } + }).slice( + // do paging + this.offset, this.offset + this.pageSize + ).forEach((doc) => { + // stream docs + that.push(doc) + }) + return end() +} -/**/ -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ +// Make a merged map of the top scoring documents +const getResultMap = (resultSet) => { + var resultMap = {} + resultSet.forEach((docMatch) => { + resultMap[docMatch.id] = resultMap[docMatch.id] || [] + resultMap[docMatch.id].push(docMatch) + delete docMatch.id + }) + return resultMap +} -/**/ -var Stream = require('./internal/streams/stream'); -/**/ +},{"stream":147,"util":157}],122:[function(require,module,exports){ +const Transform = require('stream').Transform +const util = require('util') -/**/ -var Buffer = require('safe-buffer').Buffer; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); +const MergeOrConditionsTFIDF = function (offset, pageSize) { + this.resultSet = [] + this.offset = offset + this.pageSize = pageSize + Transform.call(this, { objectMode: true }) } -function _isUint8Array(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]' || Buffer.isBuffer(obj); +exports.MergeOrConditionsTFIDF = MergeOrConditionsTFIDF +util.inherits(MergeOrConditionsTFIDF, Transform) +MergeOrConditionsTFIDF.prototype._transform = function (doc, encoding, end) { + // console.log(JSON.stringify(doc, null, 2)) + this.resultSet = this.resultSet.concat(doc.matches) + return end() } -/**/ - -var destroyImpl = require('./internal/streams/destroy'); +MergeOrConditionsTFIDF.prototype._flush = function (end) { + var that = this + // turn top scoring results into a merged map + var resultMap = getResultMap(this.resultSet) -util.inherits(Writable, Stream); + // turn map back into array and score + Object.keys(resultMap).map((id) => { + return { + id: id, + scoringCriteria: resultMap[id], + score: resultMap[id].reduce((sum, matches) => { + return sum + matches.score + }, 0) / resultMap[id].length + } + }).sort((a, b) => { + // sort by score then id descending + if (b.score === a.score) { + return (a.id < b.id) ? 1 : (a.id > b.id) ? -1 : 0 + } + return (b.score - a.score) + }).slice( + // do paging + this.offset, this.offset + this.pageSize + ).forEach((doc) => { + // stream docs + that.push(doc) + }) + return end() + +} -function nop() {} +// Make a merged map of the top scoring documents +const getResultMap = (resultSet) => { + var resultMap = {} + resultSet.forEach((docMatch) => { + resultMap[docMatch.id] = resultMap[docMatch.id] || [] + resultMap[docMatch.id].push(docMatch) + delete docMatch.id + }) + return resultMap +} -function WritableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); +},{"stream":147,"util":157}],123:[function(require,module,exports){ +const Transform = require('stream').Transform +const _sortedIndexOf = require('lodash.sortedindexof') +const util = require('util') - options = options || {}; +const ScoreDocsOnField = function (options, seekLimit, sort) { + this.options = options + this.seekLimit = seekLimit + this.sort = sort + Transform.call(this, { objectMode: true }) +} +exports.ScoreDocsOnField = ScoreDocsOnField +util.inherits(ScoreDocsOnField, Transform) +ScoreDocsOnField.prototype._transform = function (clauseSet, encoding, end) { + const sep = this.options.keySeparator + // clauseSet = JSON.parse(clauseSet) + const that = this - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + const sortDirection = this.sort.direction || 'asc' - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + // if sort direction is asc + // walk down the DF array of lowest frequency hit until (offset + + // pagesize) hits have been found + var tally = 0 + var rangeOptions = { + gte: 'DF' + sep + this.sort.field + sep, + lte: 'DF' + sep + this.sort.field + sep + sep + } + if (sortDirection === 'desc') rangeOptions.reverse = true + clauseSet.topScoringDocs = [] + that.options.indexes.createReadStream(rangeOptions) + .on('data', function (data) { + var token = data.key.split(sep)[2] + if (token === '*') return + if (sortDirection === 'desc') data.value = data.value.reverse() + data.value.some(id => { + if (_sortedIndexOf(clauseSet.set, id) !== -1) { + clauseSet.topScoringDocs.push({ + id: id, + score: token + }) + // only match docs up to the seek limit (offset + pagesize) + if (++tally === that.seekLimit) return true + } + }) + }).on('end', function () { + that.push(clauseSet) + return end() + }) +} - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; +},{"lodash.sortedindexof":76,"stream":147,"util":157}],124:[function(require,module,exports){ +/* + Look at the top scoring docs, and work out which terms give hits in them + */ - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); +const Transform = require('stream').Transform +const util = require('util') - // if _final has been called - this.finalCalled = false; +// TODO: handle offset and pagesize - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; +const ScoreTopScoringDocsTFIDF = function (options, offset, pageSize) { + this.options = options + Transform.call(this, { objectMode: true }) +} +exports.ScoreTopScoringDocsTFIDF = ScoreTopScoringDocsTFIDF +util.inherits(ScoreTopScoringDocsTFIDF, Transform) +ScoreTopScoringDocsTFIDF.prototype._transform = function (clause, encoding, end) { + var that = this + var promises = [] + clause.topScoringDocs.forEach((doc) => { + var docID = doc[1] + promises.push(getMatchesForDoc(docID, that.options, clause)) + }) + Promise.all(promises).then((res) => { + clause.matches = res + that.push(clause) + return end() + }, (err) => { + console.log(err) + }) +} - // has it been destroyed - this.destroyed = false; +// work out matches for each (top scoring) doc +const getMatchesForDoc = (docID, options, clause) => { + return new Promise((resolve, reject) => { + var termVectors = clause.documentFrequencies.map((freq) => { + return gett(freq.field, docID, freq.gte, freq.lte, freq.df, clause.WEIGHT, options) + }) + Promise.all(termVectors).then((matchedTerms) => { + var matches = [].concat.apply([], matchedTerms) // voodoo magic to flatten array + resolve({ + id: docID, + matches: matches, + score: getScore(matches) + }) + }, (err) => { + console.log(err) + }) + }) +} - // 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. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; +// average score for all matches in clause +const getScore = (matchedTerms) => { + return matchedTerms.reduce(function (sum, match) { + return sum + match.score + }, 0) / matchedTerms.length +} - // 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'; +// get term frequency from db, work out tfidf and score +const gett = (field, key, gte, lte, df, weight, options) => { + var s = options.keySeparator + return new Promise((resolve, reject) => { + options.indexes.get('DOCUMENT-VECTOR' + s + field + s + key + s, (err, value) => { + if (err) return reject(err) + var matchedTerms = Object.keys(value).filter((t) => { + if ((t >= gte) && (t <= lte)) return true + }) + var matchedTermsWithMagnitude = [] + matchedTerms.forEach((t) => { + var tf = value[t] + var tfidf = tf * (Math.log10(1 + (1 / df))) + var term = { + field: field, + term: t, + tf: tf, + df: df, + tfidf: tfidf, + weight: weight, + score: tfidf * weight + } + matchedTermsWithMagnitude.push(term) + }) + return resolve(matchedTermsWithMagnitude) + }) + }) +} - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; +},{"stream":147,"util":157}],125:[function(require,module,exports){ +const Readable = require('stream').Readable +const Transform = require('stream').Transform +const util = require('util') - // a flag to see when we're in the middle of a write. - this.writing = false; +const MatchMostFrequent = function (q, options) { + this.options = options + Transform.call(this, { objectMode: true }) +} +util.inherits(MatchMostFrequent, Transform) +MatchMostFrequent.prototype._transform = function (q, encoding, end) { + const sep = this.options.keySeparator + const 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', sortResults) + .on('end', function () { + results.sort(function (a, b) { + // sort first by frequency and then by value + var frequencySort = b.value.length - a.value.length + if (frequencySort === 0) { + // sort alphabetically by key ascending + if (b.key < a.key) return 1 + if (b.key > a.key) return -1 + return 0 + } else { + // sort by frequency (value.length) + return frequencySort + } + }) + .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() + }) +} - // when true all writes will be buffered until .uncork() call - this.corked = 0; +const MatchAlphabetical = function (q, options) { + this.options = options + Transform.call(this, { objectMode: true }) +} +util.inherits(MatchAlphabetical, Transform) +MatchAlphabetical.prototype._transform = function (q, encoding, end) { + const sep = this.options.keySeparator + const that = this - // 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. - this.sync = true; + var space = { + start: 'DF' + sep + q.field + sep + q.beginsWith, + end: 'DF' + sep + q.field + sep + q.beginsWith + sep + } + var i = 0 + var rs = this.options.indexes.createReadStream(space) + rs.on('data', function (data) { + var m = {} + switch (q.type) { + case 'ID': m = { + token: data.key.split(sep)[2], + documents: data.value + }; break + case 'count': m = { + token: data.key.split(sep)[2], + documentCount: data.value.length + }; break + default: m = data.key.split(sep)[2] + } + that.push(m) + if (++i === q.limit) { + rs.destroy() + return end() + } + }) + rs.on('error', function (err) { + that.options.log.error('Oh my!', err) + }) + rs.on('end', function () { + return end() + }) +} - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; +exports.match = function (q, options) { + var s = new Readable({ objectMode: true }) + q = Object.assign({}, { + beginsWith: '', + field: '*', + threshold: 3, + limit: 10, + type: 'simple', + sort: 'frequency' + }, q) + if (q.beginsWith.length < q.threshold) { + s.push(null) + return s + } + s.push(q) + s.push(null) + if (q.sort === 'alphabetical') { + return s.pipe(new MatchAlphabetical(q, options)) + } else { + // default to "sort by frequency" + return s.pipe(new MatchMostFrequent(q, options)) + } +} - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; +},{"stream":147,"util":157}],126:[function(require,module,exports){ +exports.getKeySet = function (clause, sep) { + var keySet = [] + for (var fieldName in clause) { + clause[fieldName].forEach(function (token) { + var gte = token.gte || token + var lte = token.lte || token + keySet.push([ + 'DF' + sep + fieldName + sep + gte, + 'DF' + sep + fieldName + sep + lte + ]) + }) + } + return keySet +} - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; +exports.getQueryDefaults = function (q) { + // if a string is given- turn it into a query + if (typeof q === 'string') { + q = { + query: [{ + AND: {'*': q.split(' ')} + }] + } + } + // Make sure that user query is arrayified + if (q) { + if (q.query) { + if (Object.prototype.toString.call(q.query) !== '[object Array]') { + q.query = [q.query] + } + } + } + // cast strings to int, where possible ("2" = 2) + try { + if (q.offset) q.offset = parseInt(q.offset) + } catch (e) {} + try { + if (q.pageSize) q.pageSize = parseInt(q.pageSize) + } catch (e) {} + return Object.assign({}, { + query: [{ + AND: {'*': ['*']} + }], + offset: 0, + pageSize: 20 + }, q) +} - // the amount that is being written when _write is called. - this.writelen = 0; +},{}],127:[function(require,module,exports){ +const defaultStopwords = require('./stopwords_en.js').words - this.bufferedRequest = null; - this.lastBufferedRequest = null; +exports.removeStopwords = function(tokens, stopwords) { + stopwords = stopwords || defaultStopwords + if (typeof tokens !== 'object' || typeof stopwords != 'object'){ + throw new Error ('expected Arrays try: removeStopwords(Array[, Array])') + } + return tokens.filter(function (value) { + return stopwords.indexOf(value.toLowerCase()) === -1 + }) +} - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; +exports.ar = require('./stopwords_ar.js').words +exports.bn = require('./stopwords_bn.js').words +exports.br = require('./stopwords_br.js').words +exports.da = require('./stopwords_da.js').words +exports.de = require('./stopwords_de.js').words +exports.en = require('./stopwords_en.js').words +exports.es = require('./stopwords_es.js').words +exports.fa = require('./stopwords_fa.js').words +exports.fr = require('./stopwords_fr.js').words +exports.hi = require('./stopwords_hi.js').words +exports.it = require('./stopwords_it.js').words +exports.ja = require('./stopwords_ja.js').words +exports.nl = require('./stopwords_nl.js').words +exports.no = require('./stopwords_no.js').words +exports.pl = require('./stopwords_pl.js').words +exports.pt = require('./stopwords_pt.js').words +exports.ru = require('./stopwords_ru.js').words +exports.sv = require('./stopwords_sv.js').words +exports.zh = require('./stopwords_zh.js').words + +},{"./stopwords_ar.js":128,"./stopwords_bn.js":129,"./stopwords_br.js":130,"./stopwords_da.js":131,"./stopwords_de.js":132,"./stopwords_en.js":133,"./stopwords_es.js":134,"./stopwords_fa.js":135,"./stopwords_fr.js":136,"./stopwords_hi.js":137,"./stopwords_it.js":138,"./stopwords_ja.js":139,"./stopwords_nl.js":140,"./stopwords_no.js":141,"./stopwords_pl.js":142,"./stopwords_pt.js":143,"./stopwords_ru.js":144,"./stopwords_sv.js":145,"./stopwords_zh.js":146}],128:[function(require,module,exports){ +/* +The MIT License (MIT) + +Copyright (c) 2016 Gene Diaz + +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. +*/ - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = ["،","آض","آمينَ","آه","آهاً","آي","أ","أب","أجل","أجمع","أخ","أخذ","أصبح","أضحى","أقبل","أقل","أكثر","ألا","أم","أما","أمامك","أمامكَ","أمسى","أمّا","أن","أنا","أنت","أنتم","أنتما","أنتن","أنتِ","أنشأ","أنّى","أو","أوشك","أولئك","أولئكم","أولاء","أولالك","أوّهْ","أي","أيا","أين","أينما","أيّ","أَنَّ","أََيُّ","أُفٍّ","إذ","إذا","إذاً","إذما","إذن","إلى","إليكم","إليكما","إليكنّ","إليكَ","إلَيْكَ","إلّا","إمّا","إن","إنّما","إي","إياك","إياكم","إياكما","إياكن","إيانا","إياه","إياها","إياهم","إياهما","إياهن","إياي","إيهٍ","إِنَّ","ا","ابتدأ","اثر","اجل","احد","اخرى","اخلولق","اذا","اربعة","ارتدّ","استحال","اطار","اعادة","اعلنت","اف","اكثر","اكد","الألاء","الألى","الا","الاخيرة","الان","الاول","الاولى","التى","التي","الثاني","الثانية","الذاتي","الذى","الذي","الذين","السابق","الف","اللائي","اللاتي","اللتان","اللتيا","اللتين","اللذان","اللذين","اللواتي","الماضي","المقبل","الوقت","الى","اليوم","اما","امام","امس","ان","انبرى","انقلب","انه","انها","او","اول","اي","ايار","ايام","ايضا","ب","بات","باسم","بان","بخٍ","برس","بسبب","بسّ","بشكل","بضع","بطآن","بعد","بعض","بك","بكم","بكما","بكن","بل","بلى","بما","بماذا","بمن","بن","بنا","به","بها","بي","بيد","بين","بَسْ","بَلْهَ","بِئْسَ","تانِ","تانِك","تبدّل","تجاه","تحوّل","تلقاء","تلك","تلكم","تلكما","تم","تينك","تَيْنِ","تِه","تِي","ثلاثة","ثم","ثمّ","ثمّة","ثُمَّ","جعل","جلل","جميع","جير","حار","حاشا","حاليا","حاي","حتى","حرى","حسب","حم","حوالى","حول","حيث","حيثما","حين","حيَّ","حَبَّذَا","حَتَّى","حَذارِ","خلا","خلال","دون","دونك","ذا","ذات","ذاك","ذانك","ذانِ","ذلك","ذلكم","ذلكما","ذلكن","ذو","ذوا","ذواتا","ذواتي","ذيت","ذينك","ذَيْنِ","ذِه","ذِي","راح","رجع","رويدك","ريث","رُبَّ","زيارة","سبحان","سرعان","سنة","سنوات","سوف","سوى","سَاءَ","سَاءَمَا","شبه","شخصا","شرع","شَتَّانَ","صار","صباح","صفر","صهٍ","صهْ","ضد","ضمن","طاق","طالما","طفق","طَق","ظلّ","عاد","عام","عاما","عامة","عدا","عدة","عدد","عدم","عسى","عشر","عشرة","علق","على","عليك","عليه","عليها","علًّ","عن","عند","عندما","عوض","عين","عَدَسْ","عَمَّا","غدا","غير","ـ","ف","فان","فلان","فو","فى","في","فيم","فيما","فيه","فيها","قال","قام","قبل","قد","قطّ","قلما","قوة","كأنّما","كأين","كأيّ","كأيّن","كاد","كان","كانت","كذا","كذلك","كرب","كل","كلا","كلاهما","كلتا","كلم","كليكما","كليهما","كلّما","كلَّا","كم","كما","كي","كيت","كيف","كيفما","كَأَنَّ","كِخ","لئن","لا","لات","لاسيما","لدن","لدى","لعمر","لقاء","لك","لكم","لكما","لكن","لكنَّما","لكي","لكيلا","للامم","لم","لما","لمّا","لن","لنا","له","لها","لو","لوكالة","لولا","لوما","لي","لَسْتَ","لَسْتُ","لَسْتُم","لَسْتُمَا","لَسْتُنَّ","لَسْتِ","لَسْنَ","لَعَلَّ","لَكِنَّ","لَيْتَ","لَيْسَ","لَيْسَا","لَيْسَتَا","لَيْسَتْ","لَيْسُوا","لَِسْنَا","ما","ماانفك","مابرح","مادام","ماذا","مازال","مافتئ","مايو","متى","مثل","مذ","مساء","مع","معاذ","مقابل","مكانكم","مكانكما","مكانكنّ","مكانَك","مليار","مليون","مما","ممن","من","منذ","منها","مه","مهما","مَنْ","مِن","نحن","نحو","نعم","نفس","نفسه","نهاية","نَخْ","نِعِمّا","نِعْمَ","ها","هاؤم","هاكَ","هاهنا","هبّ","هذا","هذه","هكذا","هل","هلمَّ","هلّا","هم","هما","هن","هنا","هناك","هنالك","هو","هي","هيا","هيت","هيّا","هَؤلاء","هَاتانِ","هَاتَيْنِ","هَاتِه","هَاتِي","هَجْ","هَذا","هَذانِ","هَذَيْنِ","هَذِه","هَذِي","هَيْهَاتَ","و","و6","وا","واحد","واضاف","واضافت","واكد","وان","واهاً","واوضح","وراءَك","وفي","وقال","وقالت","وقد","وقف","وكان","وكانت","ولا","ولم","ومن","وهو","وهي","ويكأنّ","وَيْ","وُشْكَانََ","يكون","يمكن","يوم","ّأيّان"] - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; +// tell the world about the noise words. +exports.words = words - // count buffered requests - this.bufferedRequestCount = 0; +},{}],129:[function(require,module,exports){ +/* +The MIT License (MIT) + +Copyright (c) 2016 Gene Diaz + +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. +*/ - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = ["অতএব","অথচ","অথবা","অনুযায়ী","অনেক","অনেকে","অনেকেই","অন্তত","অন্য","অবধি","অবশ্য","অর্থাত","আই","আগামী","আগে","আগেই","আছে","আজ","আদ্যভাগে","আপনার","আপনি","আবার","আমরা","আমাকে","আমাদের","আমার","আমি","আর","আরও","ই","ইত্যাদি","ইহা","উচিত","উত্তর","উনি","উপর","উপরে","এ","এঁদের","এঁরা","এই","একই","একটি","একবার","একে","এক্","এখন","এখনও","এখানে","এখানেই","এটা","এটাই","এটি","এত","এতটাই","এতে","এদের","এব","এবং","এবার","এমন","এমনকী","এমনি","এর","এরা","এল","এস","এসে","ঐ","ও","ওঁদের","ওঁর","ওঁরা","ওই","ওকে","ওখানে","ওদের","ওর","ওরা","কখনও","কত","কবে","কমনে","কয়েক","কয়েকটি","করছে","করছেন","করতে","করবে","করবেন","করলে","করলেন","করা","করাই","করায়","করার","করি","করিতে","করিয়া","করিয়ে","করে","করেই","করেছিলেন","করেছে","করেছেন","করেন","কাউকে","কাছ","কাছে","কাজ","কাজে","কারও","কারণ","কি","কিংবা","কিছু","কিছুই","কিন্তু","কী","কে","কেউ","কেউই","কেখা","কেন","কোটি","কোন","কোনও","কোনো","ক্ষেত্রে","কয়েক","খুব","গিয়ে","গিয়েছে","গিয়ে","গুলি","গেছে","গেল","গেলে","গোটা","চলে","চান","চায়","চার","চালু","চেয়ে","চেষ্টা","ছাড়া","ছাড়াও","ছিল","ছিলেন","জন","জনকে","জনের","জন্য","জন্যওজে","জানতে","জানা","জানানো","জানায়","জানিয়ে","জানিয়েছে","জে","জ্নজন","টি","ঠিক","তখন","তত","তথা","তবু","তবে","তা","তাঁকে","তাঁদের","তাঁর","তাঁরা","তাঁাহারা","তাই","তাও","তাকে","তাতে","তাদের","তার","তারপর","তারা","তারৈ","তাহলে","তাহা","তাহাতে","তাহার","তিনঐ","তিনি","তিনিও","তুমি","তুলে","তেমন","তো","তোমার","থাকবে","থাকবেন","থাকা","থাকায়","থাকে","থাকেন","থেকে","থেকেই","থেকেও","দিকে","দিতে","দিন","দিয়ে","দিয়েছে","দিয়েছেন","দিলেন","দু","দুই","দুটি","দুটো","দেওয়া","দেওয়ার","দেওয়া","দেখতে","দেখা","দেখে","দেন","দেয়","দ্বারা","ধরা","ধরে","ধামার","নতুন","নয়","না","নাই","নাকি","নাগাদ","নানা","নিজে","নিজেই","নিজেদের","নিজের","নিতে","নিয়ে","নিয়ে","নেই","নেওয়া","নেওয়ার","নেওয়া","নয়","পক্ষে","পর","পরে","পরেই","পরেও","পর্যন্ত","পাওয়া","পাচ","পারি","পারে","পারেন","পি","পেয়ে","পেয়্র্","প্রতি","প্রথম","প্রভৃতি","প্রযন্ত","প্রাথমিক","প্রায়","প্রায়","ফলে","ফিরে","ফের","বক্তব্য","বদলে","বন","বরং","বলতে","বলল","বললেন","বলা","বলে","বলেছেন","বলেন","বসে","বহু","বা","বাদে","বার","বি","বিনা","বিভিন্ন","বিশেষ","বিষয়টি","বেশ","বেশি","ব্যবহার","ব্যাপারে","ভাবে","ভাবেই","মতো","মতোই","মধ্যভাগে","মধ্যে","মধ্যেই","মধ্যেও","মনে","মাত্র","মাধ্যমে","মোট","মোটেই","যখন","যত","যতটা","যথেষ্ট","যদি","যদিও","যা","যাঁর","যাঁরা","যাওয়া","যাওয়ার","যাওয়া","যাকে","যাচ্ছে","যাতে","যাদের","যান","যাবে","যায়","যার","যারা","যিনি","যে","যেখানে","যেতে","যেন","যেমন","র","রকম","রয়েছে","রাখা","রেখে","লক্ষ","শুধু","শুরু","সঙ্গে","সঙ্গেও","সব","সবার","সমস্ত","সম্প্রতি","সহ","সহিত","সাধারণ","সামনে","সি","সুতরাং","সে","সেই","সেখান","সেখানে","সেটা","সেটাই","সেটাও","সেটি","স্পষ্ট","স্বয়ং","হইতে","হইবে","হইয়া","হওয়া","হওয়ায়","হওয়ার","হচ্ছে","হত","হতে","হতেই","হন","হবে","হবেন","হয়","হয়তো","হয়নি","হয়ে","হয়েই","হয়েছিল","হয়েছে","হয়েছেন","হল","হলে","হলেই","হলেও","হলো","হাজার","হিসাবে","হৈলে","হোক","হয়"] +// tell the world about the noise words. +exports.words = words -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; +},{}],130:[function(require,module,exports){ +/* +Copyright (c) 2017, Micael Levi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'a', + 'agora', + 'ainda', + 'alguém', + 'algum', + 'alguma', + 'algumas', + 'alguns', + 'ampla', + 'amplas', + 'amplo', + 'amplos', + 'ante', + 'antes', + 'ao', + 'aos', + 'após', + 'aquela', + 'aquelas', + 'aquele', + 'aqueles', + 'aquilo', + 'as', + 'até', + 'através', + 'cada', + 'coisa', + 'coisas', + 'com', + 'como', + 'contra', + 'contudo', + 'da', + 'daquele', + 'daqueles', + 'das', + 'de', + 'dela', + 'delas', + 'dele', + 'deles', + 'depois', + 'dessa', + 'dessas', + 'desse', + 'desses', + 'desta', + 'destas', + 'deste', + 'deste', + 'destes', + 'deve', + 'devem', + 'devendo', + 'dever', + 'deverá', + 'deverão', + 'deveria', + 'deveriam', + 'devia', + 'deviam', + 'disse', + 'disso', + 'disto', + 'dito', + 'diz', + 'dizem', + 'do', + 'dos', + 'e', + 'é', + 'ela', + 'elas', + 'ele', + 'eles', + 'em', + 'enquanto', + 'entre', + 'era', + 'essa', + 'essas', + 'esse', + 'esses', + 'esta', + 'está', + 'estamos', + 'estão', + 'estas', + 'estava', + 'estavam', + 'estávamos', + 'este', + 'estes', + 'estou', + 'eu', + 'fazendo', + 'fazer', + 'feita', + 'feitas', + 'feito', + 'feitos', + 'foi', + 'for', + 'foram', + 'fosse', + 'fossem', + 'grande', + 'grandes', + 'há', + 'isso', + 'isto', + 'já', + 'la', + 'lá', + 'lhe', + 'lhes', + 'lo', + 'mas', + 'me', + 'mesma', + 'mesmas', + 'mesmo', + 'mesmos', + 'meu', + 'meus', + 'minha', + 'minhas', + 'muita', + 'muitas', + 'muito', + 'muitos', + 'na', + 'não', + 'nas', + 'nem', + 'nenhum', + 'nessa', + 'nessas', + 'nesta', + 'nestas', + 'ninguém', + 'no', + 'nos', + 'nós', + 'nossa', + 'nossas', + 'nosso', + 'nossos', + 'num', + 'numa', + 'nunca', + 'o', + 'os', + 'ou', + 'outra', + 'outras', + 'outro', + 'outros', + 'para', + 'pela', + 'pelas', + 'pelo', + 'pelos', + 'pequena', + 'pequenas', + 'pequeno', + 'pequenos', + 'per', + 'perante', + 'pode', + 'pude', + 'podendo', + 'poder', + 'poderia', + 'poderiam', + 'podia', + 'podiam', + 'pois', + 'por', + 'porém', + 'porque', + 'posso', + 'pouca', + 'poucas', + 'pouco', + 'poucos', + 'primeiro', + 'primeiros', + 'própria', + 'próprias', + 'próprio', + 'próprios', + 'quais', + 'qual', + 'quando', + 'quanto', + 'quantos', + 'que', + 'quem', + 'são', + 'se', + 'seja', + 'sejam', + 'sem', + 'sempre', + 'sendo', + 'será', + 'serão', + 'seu', + 'seus', + 'si', + 'sido', + 'só', + 'sob', + 'sobre', + 'sua', + 'suas', + 'talvez', + 'também', + 'tampouco', + 'te', + 'tem', + 'tendo', + 'tenha', + 'ter', + 'teu', + 'teus', + 'ti', + 'tido', + 'tinha', + 'tinham', + 'toda', + 'todas', + 'todavia', + 'todo', + 'todos', + 'tu', + 'tua', + 'tuas', + 'tudo', + 'última', + 'últimas', + 'último', + 'últimos', + 'um', + 'uma', + 'umas', + 'uns', + 'vendo', + 'ver', + 'vez', + 'vindo', + 'vir', + 'vos', + 'vós', + '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_' +] -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; +// tell the world about the noise words. +exports.words = words - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} +},{}],131:[function(require,module,exports){ +/* +Creative Commons – Attribution / ShareAlike 3.0 license +http://creativecommons.org/licenses/by-sa/3.0/ -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); +List based on frequently used words in subtitles in 2012. - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. +Thanks to +opensubtitles.org +https://invokeit.wordpress.com/frequency-word-lists/#comment-9707 +*/ - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'er', 'jeg', 'det', 'du', 'ikke', 'i', 'at', 'en', 'og', 'har', + 'vi', 'til', 'på', 'hvad', 'med', 'mig', 'så', 'for', 'de', 'dig', + 'der', 'den', 'han', 'kan', 'af', 'vil', 'var', 'her', 'et', 'skal', + 'ved', 'nu', 'men', 'om', 'ja', 'som', 'nej', 'min', 'noget', 'ham', + 'hun', 'bare', 'kom', 'være', 'din', 'hvor', 'dem', 'ud', 'os', 'hvis', + 'må', 'se', 'godt', 'have', 'fra', 'ville', 'okay', 'lige', 'op', 'alle', + 'lad', 'hvorfor', 'sig', 'hvordan', 'få', 'kunne', 'eller', 'hvem', 'man', 'bliver', + 'havde', 'da', 'ingen', 'efter', 'når', 'alt', 'jo', 'to', 'mit', 'ind', + 'hej', 'aldrig', 'lidt', 'nogen', 'over', 'også', 'mand', 'far', 'skulle', 'selv', + 'får', 'hans', 'ser', 'vores', 'jer', 'sådan', 'dit', 'kun', 'deres', 'ned', + 'mine', 'komme', 'tage', 'denne', 'sige', 'dette', 'blive', 'helt', 'fordi', + 'end', 'tag', 'før', 'fik', 'dine', + '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_'] + +// tell the world about the noise words. +exports.words = words + +},{}],132:[function(require,module,exports){ +/* +*/ - this._writableState = new WritableState(options, this); +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'a', 'ab', 'aber', 'ach', 'acht', 'achte', 'achten', 'achter', 'achtes', 'ag', 'alle', 'allein', 'allem', 'allen', 'aller', 'allerdings', 'alles', 'allgemeinen', 'als', 'also', 'am', 'an', 'ander', 'andere', 'anderem', 'anderen', 'anderer', 'anderes', 'anderm', 'andern', 'anderr', 'anders', 'au', 'auch', 'auf', 'aus', 'ausser', 'ausserdem', 'außer', 'außerdem', 'b', 'bald', 'bei', 'beide', 'beiden', 'beim', 'beispiel', 'bekannt', 'bereits', 'besonders', 'besser', 'besten', 'bin', 'bis', 'bisher', 'bist', 'c', 'd', 'd.h', 'da', 'dabei', 'dadurch', 'dafür', 'dagegen', 'daher', 'dahin', 'dahinter', 'damals', 'damit', 'danach', 'daneben', 'dank', 'dann', 'daran', 'darauf', 'daraus', 'darf', 'darfst', 'darin', 'darum', 'darunter', 'darüber', 'das', 'dasein', 'daselbst', 'dass', 'dasselbe', 'davon', 'davor', 'dazu', 'dazwischen', 'daß', 'dein', 'deine', 'deinem', 'deinen', 'deiner', 'deines', 'dem', 'dementsprechend', 'demgegenüber', 'demgemäss', 'demgemäß', 'demselben', 'demzufolge', 'den', 'denen', 'denn', 'denselben', 'der', 'deren', 'derer', 'derjenige', 'derjenigen', 'dermassen', 'dermaßen', 'derselbe', 'derselben', 'des', 'deshalb', 'desselben', 'dessen', 'deswegen', 'dich', 'die', 'diejenige', 'diejenigen', 'dies', 'diese', 'dieselbe', 'dieselben', 'diesem', 'diesen', 'dieser', 'dieses', 'dir', 'doch', 'dort', 'drei', 'drin', 'dritte', 'dritten', 'dritter', 'drittes', 'du', 'durch', 'durchaus', 'durfte', 'durften', 'dürfen', 'dürft', 'e', 'eben', 'ebenso', 'ehrlich', 'ei', 'ei, ', 'eigen', 'eigene', 'eigenen', 'eigener', 'eigenes', 'ein', 'einander', 'eine', 'einem', 'einen', 'einer', 'eines', 'einig', 'einige', 'einigem', 'einigen', 'einiger', 'einiges', 'einmal', 'eins', 'elf', 'en', 'ende', 'endlich', 'entweder', 'er', 'ernst', 'erst', 'erste', 'ersten', 'erster', 'erstes', 'es', 'etwa', 'etwas', 'euch', 'euer', 'eure', 'eurem', 'euren', 'eurer', 'eures', 'f', 'folgende', 'früher', 'fünf', 'fünfte', 'fünften', 'fünfter', 'fünftes', 'für', 'g', 'gab', 'ganz', 'ganze', 'ganzen', 'ganzer', 'ganzes', 'gar', 'gedurft', 'gegen', 'gegenüber', 'gehabt', 'gehen', 'geht', 'gekannt', 'gekonnt', 'gemacht', 'gemocht', 'gemusst', 'genug', 'gerade', 'gern', 'gesagt', 'geschweige', 'gewesen', 'gewollt', 'geworden', 'gibt', 'ging', 'gleich', 'gott', 'gross', 'grosse', 'grossen', 'grosser', 'grosses', 'groß', 'große', 'großen', 'großer', 'großes', 'gut', 'gute', 'guter', 'gutes', 'h', 'hab', 'habe', 'haben', 'habt', 'hast', 'hat', 'hatte', 'hatten', 'hattest', 'hattet', 'heisst', 'her', 'heute', 'hier', 'hin', 'hinter', 'hoch', 'hätte', 'hätten', 'i', 'ich', 'ihm', 'ihn', 'ihnen', 'ihr', 'ihre', 'ihrem', 'ihren', 'ihrer', 'ihres', 'im', 'immer', 'in', 'indem', 'infolgedessen', 'ins', 'irgend', 'ist', 'j', 'ja', 'jahr', 'jahre', 'jahren', 'je', 'jede', 'jedem', 'jeden', 'jeder', 'jedermann', 'jedermanns', 'jedes', 'jedoch', 'jemand', 'jemandem', 'jemanden', 'jene', 'jenem', 'jenen', 'jener', 'jenes', 'jetzt', 'k', 'kam', 'kann', 'kannst', 'kaum', 'kein', 'keine', 'keinem', 'keinen', 'keiner', 'keines', 'kleine', 'kleinen', 'kleiner', 'kleines', 'kommen', 'kommt', 'konnte', 'konnten', 'kurz', 'können', 'könnt', 'könnte', 'l', 'lang', 'lange', 'leicht', 'leide', 'lieber', 'los', 'm', 'machen', 'macht', 'machte', 'mag', 'magst', 'mahn', 'mal', 'man', 'manche', 'manchem', 'manchen', 'mancher', 'manches', 'mann', 'mehr', 'mein', 'meine', 'meinem', 'meinen', 'meiner', 'meines', 'mensch', 'menschen', 'mich', 'mir', 'mit', 'mittel', 'mochte', 'mochten', 'morgen', 'muss', 'musst', 'musste', 'mussten', 'muß', 'mußt', 'möchte', 'mögen', 'möglich', 'mögt', 'müssen', 'müsst', 'müßt', 'n', 'na', 'nach', 'nachdem', 'nahm', 'natürlich', 'neben', 'nein', 'neue', 'neuen', 'neun', 'neunte', 'neunten', 'neunter', 'neuntes', 'nicht', 'nichts', 'nie', 'niemand', 'niemandem', 'niemanden', 'noch', 'nun', 'nur', 'o', 'ob', 'oben', 'oder', 'offen', 'oft', 'ohne', 'ordnung', 'p', 'q', 'r', 'recht', 'rechte', 'rechten', 'rechter', 'rechtes', 'richtig', 'rund', 's', 'sa', 'sache', 'sagt', 'sagte', 'sah', 'satt', 'schlecht', 'schluss', 'schon', 'sechs', 'sechste', 'sechsten', 'sechster', 'sechstes', 'sehr', 'sei', 'seid', 'seien', 'sein', 'seine', 'seinem', 'seinen', 'seiner', 'seines', 'seit', 'seitdem', 'selbst', 'sich', 'sie', 'sieben', 'siebente', 'siebenten', 'siebenter', 'siebentes', 'sind', 'so', 'solang', 'solche', 'solchem', 'solchen', 'solcher', 'solches', 'soll', 'sollen', 'sollst', 'sollt', 'sollte', 'sollten', 'sondern', 'sonst', 'soweit', 'sowie', 'später', 'startseite', 'statt', 'steht', 'suche', 't', 'tag', 'tage', 'tagen', 'tat', 'teil', 'tel', 'tritt', 'trotzdem', 'tun', 'u', 'uhr', 'um', 'und', 'und?', 'uns', 'unse', 'unsem', 'unsen', 'unser', 'unsere', 'unserer', 'unses', 'unter', 'v', 'vergangenen', 'viel', 'viele', 'vielem', 'vielen', 'vielleicht', 'vier', 'vierte', 'vierten', 'vierter', 'viertes', 'vom', 'von', 'vor', 'w', 'wahr?', 'wann', 'war', 'waren', 'warst', 'wart', 'warum', 'was', 'weg', 'wegen', 'weil', 'weit', 'weiter', 'weitere', 'weiteren', 'weiteres', 'welche', 'welchem', 'welchen', 'welcher', 'welches', 'wem', 'wen', 'wenig', 'wenige', 'weniger', 'weniges', 'wenigstens', 'wenn', 'wer', 'werde', 'werden', 'werdet', 'weshalb', 'wessen', 'wie', 'wieder', 'wieso', 'will', 'willst', 'wir', 'wird', 'wirklich', 'wirst', 'wissen', 'wo', 'woher', 'wohin', 'wohl', 'wollen', 'wollt', 'wollte', 'wollten', 'worden', 'wurde', 'wurden', 'während', 'währenddem', 'währenddessen', 'wäre', 'würde', 'würden', 'x', 'y', 'z', 'z.b', 'zehn', 'zehnte', 'zehnten', 'zehnter', 'zehntes', 'zeit', 'zu', 'zuerst', 'zugleich', 'zum', 'zunächst', 'zur', 'zurück', 'zusammen', 'zwanzig', 'zwar', 'zwei', 'zweite', 'zweiten', 'zweiter', 'zweites', 'zwischen', 'zwölf', 'über', 'überhaupt', 'übrigens' +] - // legacy. - this.writable = true; +// tell the world about the noise words. +exports.words = words - if (options) { - if (typeof options.write === 'function') this._write = options.write; +},{}],133:[function(require,module,exports){ +/* +Copyright (c) 2011, Chris Umbel + +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. +*/ - if (typeof options.writev === 'function') this._writev = options.writev; +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'about', 'after', 'all', 'also', 'am', 'an', 'and', 'another', 'any', 'are', 'as', 'at', 'be', + 'because', 'been', 'before', 'being', 'between', 'both', 'but', 'by', 'came', 'can', + 'come', 'could', 'did', 'do', 'each', 'for', 'from', 'get', 'got', 'has', 'had', + 'he', 'have', 'her', 'here', 'him', 'himself', 'his', 'how', 'if', 'in', 'into', + 'is', 'it', 'like', 'make', 'many', 'me', 'might', 'more', 'most', 'much', 'must', + 'my', 'never', 'now', 'of', 'on', 'only', 'or', 'other', 'our', 'out', 'over', + 'said', 'same', 'see', 'should', 'since', 'some', 'still', 'such', 'take', 'than', + 'that', 'the', 'their', 'them', 'then', 'there', 'these', 'they', 'this', 'those', + 'through', 'to', 'too', 'under', 'up', 'very', 'was', 'way', 'we', 'well', 'were', + 'what', 'where', 'which', 'while', 'who', 'with', 'would', 'you', 'your', 'a', 'i'] + +// tell the world about the noise words. +exports.words = words + +},{}],134:[function(require,module,exports){ +/* +Copyright (c) 2011, David Przybilla, Chris Umbel + +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. +*/ - if (typeof options.destroy === 'function') this._destroy = options.destroy; +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'a', 'un', 'el', 'ella', 'y', 'sobre', 'de', 'la', 'que', 'en', + 'los', 'del', 'se', 'las', 'por', 'un', 'para', 'con', 'no', + 'una', 'su', 'al', 'lo', 'como', 'más', 'pero', 'sus', 'le', + 'ya', 'o', 'porque', 'cuando', 'muy', 'sin', 'sobre', 'también', + 'me', 'hasta', 'donde', 'quien', 'desde', 'nos', 'durante', 'uno', + 'ni', 'contra', 'ese', 'eso', 'mí', 'qué', 'otro', 'él', 'cual', + 'poco', 'mi', 'tú', 'te', 'ti', 'sí', + '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_'] + +// tell the world about the noise words. +exports.words = words + +},{}],135:[function(require,module,exports){ +/* +Copyright (c) 2011, Chris Umbel +Farsi Stop Words by Fardin Koochaki + +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 list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + // Words + 'از', 'با', 'یه', 'برای', 'و', 'باید', 'شاید', + + // Symbols + '؟', '!', '٪', '.', '،', '؛', ':', ';', ',', + + // Numbers + '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹', '۰' +] + +// tell the world about the noise words. +exports.words = words + +},{}],136:[function(require,module,exports){ +/* + Copyright (c) 2014, Ismaël Héry + + 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 list of commonly used french words that have little meaning and can be excluded +// from analysis. + +var words = ['être', 'avoir', 'faire', + 'a', + 'au', + 'aux', + 'avec', + 'ce', + 'ces', + 'dans', + 'de', + 'des', + 'du', + 'elle', + 'en', + 'et', + 'eux', + 'il', + 'je', + 'la', + 'le', + 'leur', + 'lui', + 'ma', + 'mais', + 'me', + 'même', + 'mes', + 'moi', + 'mon', + 'ne', + 'nos', + 'notre', + 'nous', + 'on', + 'ou', + 'où', + 'par', + 'pas', + 'pour', + 'qu', + 'que', + 'qui', + 'sa', + 'se', + 'ses', + 'son', + 'sur', + 'ta', + 'te', + 'tes', + 'toi', + 'ton', + 'tu', + 'un', + 'une', + 'vos', + 'votre', + 'vous', + 'c', + 'd', + 'j', + 'l', + 'à', + 'm', + 'n', + 's', + 't', + 'y', + 'été', + 'étée', + 'étées', + 'étés', + 'étant', + 'suis', + 'es', + 'est', + 'sommes', + 'êtes', + 'sont', + 'serai', + 'seras', + 'sera', + 'serons', + 'serez', + 'seront', + 'serais', + 'serait', + 'serions', + 'seriez', + 'seraient', + 'étais', + 'était', + 'étions', + 'étiez', + 'étaient', + 'fus', + 'fut', + 'fûmes', + 'fûtes', + 'furent', + 'sois', + 'soit', + 'soyons', + 'soyez', + 'soient', + 'fusse', + 'fusses', + 'fût', + 'fussions', + 'fussiez', + 'fussent', + 'ayant', + 'eu', + 'eue', + 'eues', + 'eus', + 'ai', + 'as', + 'avons', + 'avez', + 'ont', + 'aurai', + 'auras', + 'aura', + 'aurons', + 'aurez', + 'auront', + 'aurais', + 'aurait', + 'aurions', + 'auriez', + 'auraient', + 'avais', + 'avait', + 'avions', + 'aviez', + 'avaient', + 'eut', + 'eûmes', + 'eûtes', + 'eurent', + 'aie', + 'aies', + 'ait', + 'ayons', + 'ayez', + 'aient', + 'eusse', + 'eusses', + 'eût', + 'eussions', + 'eussiez', + 'eussent', + 'ceci', + 'cela', + 'cet', + 'cette', + 'ici', + 'ils', + 'les', + 'leurs', + 'quel', + 'quels', + 'quelle', + 'quelles', + 'sans', + 'soi' +] - if (typeof options.final === 'function') this._final = options.final; - } +exports.words = words - Stream.call(this); -} +},{}],137:[function(require,module,exports){ +/* +The MIT License (MIT) -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; +Copyright (c) 2016 Gene Diaz -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - processNextTick(cb, er); -} +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: -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - processNextTick(cb, er); - valid = false; - } - return valid; -} +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. -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = _isUint8Array(chunk) && !state.objectMode; +Originates from: https://github.com/stopwords-iso/stopwords-hi/ +*/ - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'अंदर','अत','अदि','अप','अपना','अपनि','अपनी','अपने','अभि','अभी','आदि','आप','इंहिं', + 'इंहें','इंहों','इतयादि','इत्यादि','इन','इनका','इन्हीं','इन्हें','इन्हों','इस','इसका','इसकि', + 'इसकी','इसके','इसमें','इसि','इसी','इसे','उंहिं','उंहें','उंहों','उन','उनका','उनकि','उनकी', + 'उनके','उनको','उन्हीं','उन्हें','उन्हों','उस','उसके','उसि','उसी','उसे','एक','एवं','एस', + 'एसे','ऐसे','ओर','और','कइ','कई','कर','करता','करते','करना','करने','करें','कहते', + 'कहा','का','काफि','काफ़ी','कि','किंहें','किंहों','कितना','किन्हें','किन्हों','किया','किर','किस', + 'किसि','किसी','किसे','की','कुछ','कुल','के','को','कोइ','कोई','कोन','कोनसा','कौन', + 'कौनसा','गया','घर','जब','जहाँ','जहां','जा','जिंहें','जिंहों','जितना','जिधर','जिन','जिन्हें', + 'जिन्हों','जिस','जिसे','जीधर','जेसा','जेसे','जैसा','जैसे','जो','तक','तब','तरह','तिंहें', + 'तिंहों','तिन','तिन्हें','तिन्हों','तिस','तिसे','तो','था','थि','थी','थे','दबारा','दवारा','दिया', + 'दुसरा','दुसरे','दूसरे','दो','द्वारा','न','नहिं','नहीं','ना','निचे','निहायत','नीचे','ने','पर', + 'पहले','पुरा','पूरा','पे','फिर','बनि','बनी','बहि','बही','बहुत','बाद','बाला','बिलकुल', + 'भि','भितर','भी','भीतर','मगर','मानो','मे','में','यदि','यह','यहाँ','यहां','यहि','यही', + 'या','यिह','ये','रखें','रवासा','रहा','रहे','ऱ्वासा','लिए','लिये','लेकिन','व','वगेरह','वरग', + 'वर्ग','वह','वहाँ','वहां','वहिं','वहीं','वाले','वुह','वे','वग़ैरह','संग','सकता','सकते','सबसे', + 'सभि','सभी','साथ','साबुत','साभ','सारा','से','सो','हि','ही','हुअ','हुआ','हुइ','हुई', + 'हुए','हे','हें','है','हैं','हो','होता','होति','होती','होते','होना','होने'] + +// tell the world about the noise words. +exports.words = words + +},{}],138:[function(require,module,exports){ +/* +Copyright (c) 2011, David Przybilla, Chris Umbel + +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 list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'ad', 'al', 'allo', 'ai', 'agli', 'all', 'agl', 'alla', 'alle', 'con', 'col', 'coi', 'da', 'dal', 'dallo', + 'dai', 'dagli', 'dall', 'dagl', 'dalla', 'dalle', 'di', 'del', 'dello', 'dei', 'degli', 'dell', 'degl', + 'della', 'delle', 'in', 'nel', 'nello', 'nei', 'negli', 'nell', 'negl', 'nella', 'nelle', 'su', 'sul', + 'sullo', 'sui', 'sugli', 'sull', 'sugl', 'sulla', 'sulle', 'per', 'tra', 'contro', 'io', 'tu', 'lui', + 'lei', 'noi', 'voi', 'loro', 'mio', 'mia', 'miei', 'mie', 'tuo', 'tua', 'tuoi', 'tue', 'suo', 'sua', 'suoi', + 'sue', 'nostro', 'nostra', 'nostri', 'nostre', 'vostro', 'vostra', 'vostri', 'vostre', 'mi', 'ti', 'ci', + 'vi', 'lo', 'la', 'li', 'le', 'gli', 'ne', 'il', 'un', 'uno', 'una', 'ma', 'ed', 'se', 'perché', 'anche', 'come', + 'dov', 'dove', 'che', 'chi', 'cui', 'non', 'più', 'quale', 'quanto', 'quanti', 'quanta', 'quante', 'quello', + 'quelli', 'quella', 'quelle', 'questo', 'questi', 'questa', 'queste', 'si', 'tutto', 'tutti', 'a', 'c', 'e', + 'i', 'l', 'o', 'ho', 'hai', 'ha', 'abbiamo', 'avete', 'hanno', 'abbia', 'abbiate', 'abbiano', 'avrò', 'avrai', + 'avrà', 'avremo', 'avrete', 'avranno', 'avrei', 'avresti', 'avrebbe', 'avremmo', 'avreste', 'avrebbero', + 'avevo', 'avevi', 'aveva', 'avevamo', 'avevate', 'avevano', 'ebbi', 'avesti', 'ebbe', 'avemmo', 'aveste', + 'ebbero', 'avessi', 'avesse', 'avessimo', 'avessero', 'avendo', 'avuto', 'avuta', 'avuti', 'avute', 'sono', + 'sei', 'è', 'siamo', 'siete', 'sia', 'siate', 'siano', 'sarò', 'sarai', 'sarà', 'saremo', 'sarete', 'saranno', + 'sarei', 'saresti', 'sarebbe', 'saremmo', 'sareste', 'sarebbero', 'ero', 'eri', 'era', 'eravamo', 'eravate', + 'erano', 'fui', 'fosti', 'fu', 'fummo', 'foste', 'furono', 'fossi', 'fosse', 'fossimo', 'fossero', 'essendo', + 'faccio', 'fai', 'facciamo', 'fanno', 'faccia', 'facciate', 'facciano', 'farò', 'farai', 'farà', 'faremo', + 'farete', 'faranno', 'farei', 'faresti', 'farebbe', 'faremmo', 'fareste', 'farebbero', 'facevo', 'facevi', + 'faceva', 'facevamo', 'facevate', 'facevano', 'feci', 'facesti', 'fece', 'facemmo', 'faceste', 'fecero', + 'facessi', 'facesse', 'facessimo', 'facessero', 'facendo', 'sto', 'stai', 'sta', 'stiamo', 'stanno', 'stia', + 'stiate', 'stiano', 'starò', 'starai', 'starà', 'staremo', 'starete', 'staranno', 'starei', 'staresti', + 'starebbe', 'staremmo', 'stareste', 'starebbero', 'stavo', 'stavi', 'stava', 'stavamo', 'stavate', 'stavano', + 'stetti', 'stesti', 'stette', 'stemmo', 'steste', 'stettero', 'stessi', 'stesse', 'stessimo', 'stessero', 'stando', + '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_'] + +// tell the world about the noise words. +exports.words = words + +},{}],139:[function(require,module,exports){ +// Original copyright: +/* + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +// This version: +/* +Copyright (c) 2012, Guillaume Marty + +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. +*/ - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +// Original location: +// http://svn.apache.org/repos/asf/lucene/dev/trunk/lucene/analysis/kuromoji/src/resources/org/apache/lucene/analysis/ja/stopwords.txt +var words = ['の', 'に', 'は', 'を', 'た', 'が', 'で', 'て', 'と', 'し', 'れ', 'さ', + 'ある', 'いる', 'も', 'する', 'から', 'な', 'こと', 'として', 'い', 'や', 'れる', + 'など', 'なっ', 'ない', 'この', 'ため', 'その', 'あっ', 'よう', 'また', 'もの', + 'という', 'あり', 'まで', 'られ', 'なる', 'へ', 'か', 'だ', 'これ', 'によって', + 'により', 'おり', 'より', 'による', 'ず', 'なり', 'られる', 'において', 'ば', 'なかっ', + 'なく', 'しかし', 'について', 'せ', 'だっ', 'その後', 'できる', 'それ', 'う', 'ので', + 'なお', 'のみ', 'でき', 'き', 'つ', 'における', 'および', 'いう', 'さらに', 'でも', + 'ら', 'たり', 'その他', 'に関する', 'たち', 'ます', 'ん', 'なら', 'に対して', '特に', + 'せる', '及び', 'これら', 'とき', 'では', 'にて', 'ほか', 'ながら', 'うち', 'そして', + 'とともに', 'ただし', 'かつて', 'それぞれ', 'または', 'お', 'ほど', 'ものの', 'に対する', + 'ほとんど', 'と共に', 'といった', 'です', 'とも', 'ところ', 'ここ'] + +// tell the world about the noise words. +exports.words = words + +},{}],140:[function(require,module,exports){ +/* +Copyright (c) 2011, Chris Umbel, Martijn de Boer, Damien van Holten + +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. +*/ - if (typeof cb !== 'function') cb = nop; +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +// This dutch wordlist has been parsed from a list created by Damien van Holten +// source: http://www.damienvanholten.com/blog/dutch-stop-words/ +var words = [ + 'aan', 'af', 'al', 'alles', 'als', 'altijd', 'andere', 'ben', 'bij', 'daar', + 'dan', 'dat', 'de', 'der', 'deze', 'die', 'dit', 'doch', 'doen', 'door', 'dus', + 'een', 'eens', 'en', 'er', 'ge', 'geen', 'geweest', 'haar', 'had', 'heb', + 'hebben', 'heeft', 'hem', 'het', 'hier', 'hij', 'hoe', 'hun', 'iemand', 'iets', + 'ik', 'in', 'is', 'ja', 'je ', 'kan', 'kon', 'kunnen', 'maar', 'me', 'meer', + 'men', 'met', 'mij', 'mijn', 'moet', 'na', 'naar', 'niet', 'niets', 'nog', 'nu', + 'of', 'om', 'omdat', 'ons', 'ook', 'op', 'over', 'reeds', 'te', 'tegen', 'toch', + 'toen', 'tot', 'u', 'uit', 'uw', 'van', 'veel', 'voor', 'want', 'waren', 'was', + 'wat', 'we', 'wel', 'werd', 'wezen', 'wie', 'wij', 'wil', 'worden', 'zal', 'ze', + 'zei', 'zelf', 'zich', 'zij', 'zijn', 'zo', 'zonder', 'zou', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '$', '1', + '2', '3', '4', '5', '6', '7', '8', '9', '0', '_', '-'] + +// tell the world about the noise words. +exports.words = words - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } +},{}],141:[function(require,module,exports){ +/* +Copyright (c) 2014, Kristoffer Brabrand + +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. +*/ - return ret; -}; +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'og', 'i', 'jeg', 'det', 'at', 'en', 'et', 'den', 'til', 'er', 'som', + 'på', 'de', 'med', 'han', 'av', 'ikke', 'der', 'så', 'var', 'meg', + 'seg', 'men', 'ett', 'har', 'om', 'vi', 'min', 'mitt', 'ha', 'hadde', + 'hun', 'nå', 'over', 'da', 'ved', 'fra', 'du', 'ut', 'sin', 'dem', + 'oss', 'opp', 'man', 'kan', 'hans', 'hvor', 'eller', 'hva', 'skal', + 'selv', 'sjøl', 'her', 'alle', 'vil', 'bli', 'ble', 'blitt', 'kunne', + 'inn', 'når', 'kom', 'noen', 'noe', 'ville', 'dere', 'som', + 'deres', 'kun', 'ja', 'etter', 'ned', 'skulle', 'denne', 'for', 'deg', + 'si', 'sine', 'sitt', 'mot', 'å', 'meget', 'hvorfor', 'dette', 'disse', + 'uten', 'hvordan', 'ingen', 'din', 'ditt', 'blir', 'samme', 'hvilken', + 'hvilke', 'sånn', 'inni', 'mellom', 'vår', 'hver', 'hvem', 'vors', + 'hvis', 'både', 'bare', 'enn', 'fordi', 'før', 'mange', 'også', 'slik', + 'vært', 'være', 'begge', 'siden', 'henne', 'hennar', 'hennes', + '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_'] + +// tell the world about the noise words. +exports.words = words -Writable.prototype.cork = function () { - var state = this._writableState; +},{}],142:[function(require,module,exports){ +/* +Copyright (c) 2013, Paweł Łaskarzewski + +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. +*/ - state.corked++; -}; +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +// list based on: http://pl.wikipedia.org/wiki/Wikipedia:Stopwords +var words = [ + 'a', 'aby', 'ach', 'acz', 'aczkolwiek', 'aj', 'albo', 'ale', 'ależ', 'ani', + 'aż', 'bardziej', 'bardzo', 'bo', 'bowiem', 'by', 'byli', 'bynajmniej', + 'być', 'był', 'była', 'było', 'były', 'będzie', 'będą', 'cali', 'cała', + 'cały', 'ci', 'cię', 'ciebie', 'co', 'cokolwiek', 'coś', 'czasami', + 'czasem', 'czemu', 'czy', 'czyli', 'daleko', 'dla', 'dlaczego', 'dlatego', + 'do', 'dobrze', 'dokąd', 'dość', 'dużo', 'dwa', 'dwaj', 'dwie', 'dwoje', + 'dziś', 'dzisiaj', 'gdy', 'gdyby', 'gdyż', 'gdzie', 'gdziekolwiek', + 'gdzieś', 'i', 'ich', 'ile', 'im', 'inna', 'inne', 'inny', 'innych', 'iż', + 'ja', 'ją', 'jak', 'jakaś', 'jakby', 'jaki', 'jakichś', 'jakie', 'jakiś', + 'jakiż', 'jakkolwiek', 'jako', 'jakoś', 'je', 'jeden', 'jedna', 'jedno', + 'jednak', 'jednakże', 'jego', 'jej', 'jemu', 'jest', 'jestem', 'jeszcze', + 'jeśli', 'jeżeli', 'już', 'ją', 'każdy', 'kiedy', 'kilka', 'kimś', 'kto', + 'ktokolwiek', 'ktoś', 'która', 'które', 'którego', 'której', 'który', + 'których', 'którym', 'którzy', 'ku', 'lat', 'lecz', 'lub', 'ma', 'mają', + 'mało', 'mam', 'mi', 'mimo', 'między', 'mną', 'mnie', 'mogą', 'moi', 'moim', + 'moja', 'moje', 'może', 'możliwe', 'można', 'mój', 'mu', 'musi', 'my', 'na', + 'nad', 'nam', 'nami', 'nas', 'nasi', 'nasz', 'nasza', 'nasze', 'naszego', + 'naszych', 'natomiast', 'natychmiast', 'nawet', 'nią', 'nic', 'nich', 'nie', + 'niech', 'niego', 'niej', 'niemu', 'nigdy', 'nim', 'nimi', 'niż', 'no', 'o', + 'obok', 'od', 'około', 'on', 'ona', 'one', 'oni', 'ono', 'oraz', 'oto', + 'owszem', 'pan', 'pana', 'pani', 'po', 'pod', 'podczas', 'pomimo', 'ponad', + 'ponieważ', 'powinien', 'powinna', 'powinni', 'powinno', 'poza', 'prawie', + 'przecież', 'przed', 'przede', 'przedtem', 'przez', 'przy', 'roku', + 'również', 'sam', 'sama', 'są', 'się', 'skąd', 'sobie', 'sobą', 'sposób', + 'swoje', 'ta', 'tak', 'taka', 'taki', 'takie', 'także', 'tam', 'te', 'tego', + 'tej', 'temu', 'ten', 'teraz', 'też', 'to', 'tobą', 'tobie', 'toteż', + 'trzeba', 'tu', 'tutaj', 'twoi', 'twoim', 'twoja', 'twoje', 'twym', 'twój', + 'ty', 'tych', 'tylko', 'tym', 'u', 'w', 'wam', 'wami', 'was', 'wasz', 'zaś', + 'wasza', 'wasze', 'we', 'według', 'wiele', 'wielu', 'więc', 'więcej', 'tę', + 'wszyscy', 'wszystkich', 'wszystkie', 'wszystkim', 'wszystko', 'wtedy', + 'wy', 'właśnie', 'z', 'za', 'zapewne', 'zawsze', 'ze', 'zł', 'znowu', + 'znów', 'został', 'żaden', 'żadna', 'żadne', 'żadnych', 'że', 'żeby', + '$', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_'] + +// tell the world about the noise words. +exports.words = words -Writable.prototype.uncork = function () { - var state = this._writableState; +},{}],143:[function(require,module,exports){ +/* +Copyright (c) 2011, Luís Rodrigues + +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. +*/ - if (state.corked) { - state.corked--; +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'a', + 'à', + 'ao', + 'aos', + 'aquela', + 'aquelas', + 'aquele', + 'aqueles', + 'aquilo', + 'as', + 'às', + 'até', + 'com', + 'como', + 'da', + 'das', + 'de', + 'dela', + 'delas', + 'dele', + 'deles', + 'depois', + 'do', + 'dos', + 'e', + 'ela', + 'elas', + 'ele', + 'eles', + 'em', + 'entre', + 'essa', + 'essas', + 'esse', + 'esses', + 'esta', + 'estas', + 'este', + 'estes', + 'eu', + 'isso', + 'isto', + 'já', + 'lhe', + 'lhes', + 'mais', + 'mas', + 'me', + 'mesmo', + 'meu', + 'meus', + 'minha', + 'minhas', + 'muito', + 'muitos', + 'na', + 'não', + 'nas', + 'nem', + 'no', + 'nos', + 'nós', + 'nossa', + 'nossas', + 'nosso', + 'nossos', + 'num', + 'nuns', + 'numa', + 'numas', + 'o', + 'os', + 'ou', + 'para', + 'pela', + 'pelas', + 'pelo', + 'pelos', + 'por', + 'quais', + 'qual', + 'quando', + 'que', + 'quem', + 'se', + 'sem', + 'seu', + 'seus', + 'só', + 'sua', + 'suas', + 'também', + 'te', + 'teu', + 'teus', + 'tu', + 'tua', + 'tuas', + 'um', + 'uma', + 'umas', + 'você', + 'vocês', + 'vos', + 'vosso', + 'vossos', + '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_' +] - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; +// tell the world about the noise words. +exports.words = words -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; +},{}],144:[function(require,module,exports){ +/* +Copyright (c) 2011, Polyakov Vladimir, Chris Umbel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'о', 'после', 'все', 'также', 'и', 'другие', 'все', 'как', 'во', 'быть', + 'потому', 'был', 'до', 'являюсь', 'между', 'все', 'но', 'от', 'иди', 'могу', + 'подойди', 'мог', 'делал', 'делаю', 'каждый', 'для', 'откуда', 'иметь', 'имел', + 'он', 'имеет', 'её', 'здесь', 'его', 'как', 'если', 'в', 'оно', 'за', + 'делать', 'много', 'я', 'может быть', 'более', 'самый', 'должен', + 'мой', 'никогда', 'сейчас', 'из', 'на', 'только', 'или', 'другой', 'другая', + 'другое', 'наше', 'вне', 'конец', 'сказал', 'сказала', 'также', 'видел', 'c', + 'немного', 'все еще', 'так', 'затем', 'тот', 'их', 'там', 'этот', 'они', 'те', + 'через', 'тоже', 'под', 'над', 'очень', 'был', 'путь', 'мы', 'хорошо', + 'что', 'где', 'который', 'пока', 'кто', 'с кем', 'хотел бы', 'ты', 'твои', + 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', + 'o', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', + 'э', 'ю', 'я', '$', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_'] + +// tell the world about the noise words. +exports.words = words -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; +},{}],145:[function(require,module,exports){ +/* +Creative Commons – Attribution / ShareAlike 3.0 license +http://creativecommons.org/licenses/by-sa/3.0/ - state.length += len; +List based on frequently used words in subtitles in 2012. - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; +Thanks to +opensubtitles.org +https://invokeit.wordpress.com/frequency-word-lists/#comment-9707 +*/ - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } +// a list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + 'jag', 'det', 'är', 'du', 'inte', 'att', 'en', 'och', 'har', 'vi', + 'på', 'i', 'för', 'han', 'vad', 'med', 'mig', 'som', 'här', 'om', + 'dig', 'var', 'den', 'så', 'till', 'kan', 'de', 'ni', 'ska', 'ett', + 'men', 'av', 'vill', 'nu', 'ja', 'nej', 'bara', 'hon', 'hur', 'min', + 'där', 'honom', 'kom', 'din', 'då', 'när', 'ha', 'er', 'ta', 'ut', + 'får', 'man', 'vara', 'oss', 'dem', 'eller', 'varför', 'alla', 'från', 'upp', + 'igen', 'sa', 'hade', 'allt', 'in', 'sig', 'ingen', 'henne', 'vem', 'mitt', + 'nåt', 'blir', 'än', 'bli', 'ju', 'två', 'tar', 'hans', 'ditt', 'mina', + 'åt', 'väl', 'också', 'nån', 'låt', 'detta', 'va', 'dina', 'dom', 'blev', + 'inga', 'sin', 'just', 'många', 'vart', 'vilken', 'ur', 'ens', 'sitt', 'e', + 'jo', 'era', 'deras', 'fem', 'sex', 'denna', 'vilket', 'fyra', 'vårt', 'emot', + 'tio', 'ert', 'sju', 'åtta', 'nånting', 'ned', 'ers', 'nio', 'mej', + '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_'] + +// tell the world about the noise words. +exports.words = words - return ret; -} +},{}],146:[function(require,module,exports){ +/* +Copyright (c) 2011, David Przybilla, Chris Umbel + +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 list of commonly used words that have little meaning and can be excluded +// from analysis. +var words = [ + '的', '地', '得', '和', '跟', + '与', '及', '向', '并', '等', + '更', '已', '含', '做', '我', + '你', '他', '她', '们', '某', + '该', '各', '每', '这', '那', + '哪', '什', '么', '谁', '年', + '月', '日', '时', '分', '秒', + '几', '多', '来', '在', '就', + '又', '很', '呢', '吧', '吗', + '了', '嘛', '哇', '儿', '哼', + '啊', '嗯', '是', '着', '都', + '不', '说', '也', '看', '把', + '还', '个', '有', '小', '到', + '一', '为', '中', '于', '对', + '会', '之', '第', '此', '或', + '共', '按', '请' +] + +// tell the world about the noise words. +exports.words = words -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} +},{}],147:[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. -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; +module.exports = Stream; - 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); - } -} +var EE = require('events').EventEmitter; +var inherits = require('inherits'); -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } } + } - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); } } -} -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} + dest.on('drain', ondrain); -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); } -} -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + dest.end(); + } - 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); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + if (typeof dest.destroy === 'function') dest.destroy(); + } - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. } - - if (entry === null) state.lastBufferedRequest = null; } - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + source.on('error', onerror); + dest.on('error', onerror); -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); -Writable.prototype._writev = null; + source.removeListener('end', onend); + source.removeListener('close', onclose); -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + source.on('end', cleanup); + source.on('close', cleanup); - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + dest.on('close', cleanup); - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; }; -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -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'); - } - } +},{"events":37,"inherits":40,"readable-stream/duplex.js":89,"readable-stream/passthrough.js":98,"readable-stream/readable.js":99,"readable-stream/transform.js":100,"readable-stream/writable.js":101}],148:[function(require,module,exports){ +module.exports = shift + +function shift (stream) { + var rs = stream._readableState + if (!rs) return null + return rs.objectMode ? stream.read() : stream.read(getStateLength(rs)) } -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); +function getStateLength (state) { + if (state.buffer.length) { + // Since node 6.3.0 state.buffer is a BufferList not an array + if (state.buffer.head) { + return state.buffer.head.data.length } - } - return need; -} -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) processNextTick(cb);else stream.once('finish', cb); + return state.buffer[0].length } - state.ended = true; - stream.writable = false; -} -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; - } + return state.length } -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { +},{}],149:[function(require,module,exports){ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (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 true; + default: return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; } - 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; +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; } -}); + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; }; -}).call(this,require('_process')) -},{"./_stream_duplex":209,"./internal/streams/destroy":215,"./internal/streams/stream":216,"_process":206,"core-util-is":158,"inherits":172,"process-nextick-args":205,"safe-buffer":221,"util-deprecate":226}],214:[function(require,module,exports){ -'use strict'; - -/**/ +StringDecoder.prototype.end = utf8End; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; -var Buffer = require('safe-buffer').Buffer; -/**/ +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; -function copyBuffer(src, target, offset) { - src.copy(target, offset); +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return -1; } -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; } - - 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.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.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; + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } - return ret; - }; - - return BufferList; -}(); -},{"safe-buffer":221}],215:[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; + return nb; + } + return 0; +} - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - processNextTick(emitErrorNT, this, err); +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'.repeat(p); + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'.repeat(p + 1); + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'.repeat(p + 2); + } } - 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 - - if (this._readableState) { - this._readableState.destroyed = true; +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +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); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} - this._destroy(err || null, function (err) { - if (!cb && err) { - processNextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; +// For UTF-8, a replacement character for each buffered byte of a (partial) +// character needs to be added to the output. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +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 >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); } - } else if (cb) { - cb(err); } - }); + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); } -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +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; +} - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; } + return buf.toString('base64', i, buf.length - n); } -function emitErrorNT(self, err) { - self.emit('error', err); +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; } -module.exports = { - destroy: destroy, - undestroy: undestroy -}; -},{"process-nextick-args":205}],216:[function(require,module,exports){ -arguments[4][80][0].apply(exports,arguments) -},{"dup":80,"events":169}],217:[function(require,module,exports){ -module.exports = require('./readable').PassThrough - -},{"./readable":218}],218:[function(require,module,exports){ -arguments[4][81][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":209,"./lib/_stream_passthrough.js":210,"./lib/_stream_readable.js":211,"./lib/_stream_transform.js":212,"./lib/_stream_writable.js":213,"dup":81}],219:[function(require,module,exports){ -module.exports = require('./readable').Transform - -},{"./readable":218}],220:[function(require,module,exports){ -module.exports = require('./lib/_stream_writable.js'); +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} -},{"./lib/_stream_writable.js":213}],221:[function(require,module,exports){ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} +},{"safe-buffer":102}],150:[function(require,module,exports){ +exports.doubleNormalization0point5 = 'doubleNormalization0point5' +exports.logNormalization = 'logNormalization' +exports.raw = 'raw' +exports.selfString = 'selfString' +exports.selfNumeric = 'selfNumeric' -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] +exports.getTermFrequency = function (docVector, options) { + options = Object.assign({}, { + scheme: 'raw', + weight: 0 + }, options) + // handle empty docVector + if (!docVector) { + return [] + } + if (docVector.length === 0) { + return [] + } + if (options.scheme === 'logNormalization') { + return docVector.map(function (item) { + return [item[0], +options.weight + Math.log(1 + (+item[1]))] + }) + } else if (options.scheme === 'doubleNormalization0point5') { + var maxFreq = docVector.sort(function (a, b) { + return b[1] - a[1] + })[0][1] + return docVector.map(function (item) { + return [item[0], +options.weight + 0.5 + ((0.5 * +item[1]) / (maxFreq))] + }) + } else if (options.scheme === 'raw') { + return docVector.map(function (item) { + return [item[0], +options.weight + item[1]] + }) + } else if (options.scheme === 'selfString') { + return docVector.map(function (item) { + return [item[0], item[0][0] + ''] + }) + } else if (options.scheme === 'selfNumeric') { + return docVector.map(function (item) { + var value = item[0][0] + // try to cast to number + if (!isNaN(parseFloat(value)) && isFinite(value)) { + value = +options.weight + +item[0][0] + } + return [item[0], value] + }) } -} -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) -} +},{}],151:[function(require,module,exports){ +/** + * search-index module. + * @module term-vector + */ -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +const _isEqual = require('lodash.isequal') -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') +exports.getVector = function (tokens, nGramLength) { + nGramLength = nGramLength || 1 + if (Object.prototype.toString.call(tokens) !== '[object Array]') { + throw new Error('error: input must be an Array') } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + if (nGramLength === 0) { + throw new Error('error: nGramLength must be greater than 0') } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) + var vec = [] + if (!isNaN(nGramLength)) { + return getTermVectorForNgramLength(tokens, nGramLength) + } else if (Object.prototype.toString.call(nGramLength) === '[object Array]') { + for (var i = 0; i < nGramLength.length; i++) { + vec = vec.concat(getTermVectorForNgramLength(tokens, nGramLength[i])) } - } else { - buf.fill(0) - } - return buf + return vec + } else if (typeof (nGramLength) && + ((parseInt(nGramLength.gte) <= + parseInt(nGramLength.lte)))) { + var j = parseInt(nGramLength.gte) + while (j <= nGramLength.lte && tokens[j - 1]) { + vec = vec.concat(getTermVectorForNgramLength(tokens, j++)) + } + return vec + } else throw new Error('nGramLength seems to be maformed- see docs') } -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +// create ngrams of desired length +var getTermVectorForNgramLength = function (tokens, nGramLength) { + // cant make ngram if specified length is longer than token array + if (nGramLength > tokens.length) { + return [] } - return Buffer(size) -} -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + var ngrams = [] + for (var i = 0; i <= (tokens.length - nGramLength); i++) { + ngrams.push(tokens.slice(i, i + nGramLength)) } - return buffer.SlowBuffer(size) + // count ngrams + ngrams = ngrams.sort() + // special case- doc of array length 1 + if (ngrams.length === 1) return [[ngrams[0], 1]] + var counter = 1 + var lastToken = ngrams[0] + var vector = [] + for (var j = 1; j < ngrams.length; j++) { + if (_isEqual(ngrams[j], lastToken)) { + counter++ + } else { + vector.push([lastToken, counter]) + counter = 1 + lastToken = ngrams[j] + } + } + vector.push([ngrams[i - 1], counter]) + return vector } -},{"buffer":156}],222:[function(require,module,exports){ -arguments[4][83][0].apply(exports,arguments) -},{"dup":83}],223:[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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/readable.js'); -Stream.Writable = require('readable-stream/writable.js'); -Stream.Duplex = require('readable-stream/duplex.js'); -Stream.Transform = require('readable-stream/transform.js'); -Stream.PassThrough = require('readable-stream/passthrough.js'); - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - +},{"lodash.isequal":75}],152:[function(require,module,exports){ +(function (process){ +var Stream = require('stream') +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. +exports = module.exports = through +through.through = through -function Stream() { - EE.call(this); -} +//create a readable writable stream. -Stream.prototype.pipe = function(dest, options) { - var source = this; +function through (write, end, opts) { + write = write || function (data) { this.queue(data) } + end = end || function () { this.queue(null) } - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } + var ended = false, destroyed = false, buffer = [], _ended = false + var stream = new Stream() + stream.readable = stream.writable = true + stream.paused = false - source.on('data', ondata); +// stream.autoPause = !(opts && opts.autoPause === false) + stream.autoDestroy = !(opts && opts.autoDestroy === false) - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } + stream.write = function (data) { + write.call(this, data) + return !stream.paused } - dest.on('drain', ondrain); + function drain() { + while(buffer.length && !stream.paused) { + var data = buffer.shift() + if(null === data) + return stream.emit('end') + else + stream.emit('data', data) + } + } - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); + stream.queue = stream.push = function (data) { +// console.error(ended) + if(_ended) return stream + if(data === null) _ended = true + buffer.push(data) + drain() + return stream } - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + //this is only a problem if end is not emitted synchronously. + //a nicer way to do this is to make sure this is the last listener for 'end' - dest.end(); + stream.on('end', function () { + stream.readable = false + if(!stream.writable && stream.autoDestroy) + process.nextTick(function () { + stream.destroy() + }) + }) + + function _end () { + stream.writable = false + end.call(stream) + if(!stream.readable && stream.autoDestroy) + stream.destroy() } + stream.end = function (data) { + if(ended) return + ended = true + if(arguments.length) stream.write(data) + _end() // will emit or queue + return stream + } - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + buffer.length = 0 + stream.writable = stream.readable = false + stream.emit('close') + return stream + } - if (typeof dest.destroy === 'function') dest.destroy(); + stream.pause = function () { + if(stream.paused) return + stream.paused = true + return stream } - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. + stream.resume = function () { + if(stream.paused) { + stream.paused = false + stream.emit('resume') } + drain() + //may have become paused again, + //as drain emits 'data'. + if(!stream.paused) + stream.emit('drain') + return stream } + return stream +} - source.on('error', onerror); - dest.on('error', onerror); - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); +}).call(this,require('_process')) +},{"_process":85,"stream":147}],153:[function(require,module,exports){ +(function (Buffer){ +/** + * Convert a typed array to a Buffer without a copy + * + * Author: Feross Aboukhadijeh + * License: MIT + * + * `npm install typedarray-to-buffer` + */ - source.removeListener('end', onend); - source.removeListener('close', onclose); +module.exports = function (arr) { + if (typeof Buffer._augment === 'function' && Buffer.TYPED_ARRAY_SUPPORT) { + // If `Buffer` is from the `buffer` module and this browser supports typed arrays, + // then augment it with all the `Buffer` methods. + return Buffer._augment(arr) + } else { + // Otherwise, fallback to creating a `Buffer` with a copy. + return new Buffer(arr) + } +} - source.removeListener('error', onerror); - dest.removeListener('error', onerror); +}).call(this,require("buffer").Buffer) +},{"buffer":9}],154:[function(require,module,exports){ +(function (global){ - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); +/** + * Module exports. + */ - dest.removeListener('close', cleanup); +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; } - source.on('end', cleanup); - source.on('close', cleanup); + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } - dest.on('close', cleanup); + return deprecated; +} - dest.emit('pipe', source); +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} -},{"events":169,"inherits":172,"readable-stream/duplex.js":208,"readable-stream/passthrough.js":217,"readable-stream/readable.js":218,"readable-stream/transform.js":219,"readable-stream/writable.js":220}],224:[function(require,module,exports){ -arguments[4][85][0].apply(exports,arguments) -},{"dup":85,"safe-buffer":221}],225:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"buffer":156,"dup":89}],226:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"dup":90}],227:[function(require,module,exports){ -arguments[4][35][0].apply(exports,arguments) -},{"dup":35}],228:[function(require,module,exports){ +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],155:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"dup":40}],156:[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'; } -},{}],229:[function(require,module,exports){ +},{}],157:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -35095,7 +32030,61 @@ function hasOwnProperty(obj, prop) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":228,"_process":206,"inherits":227}],230:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"dup":92}]},{},[150])(150) +},{"./support/isBuffer":156,"_process":85,"inherits":155}],158:[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. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} + +},{}],159:[function(require,module,exports){ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} + +},{}]},{},[1])(1) }); \ No newline at end of file diff --git a/dist/search-index.min.js b/dist/search-index.min.js index 6b85b893..fd06f47b 100644 --- a/dist/search-index.min.js +++ b/dist/search-index.min.js @@ -1,15 +1 @@ -!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;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||e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o]/,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":2,"./lib/delete.js":3,"./lib/replicate.js":4,JSONStream:5,async:6,bunyan:7,docproc:16,leveldown:51,levelup:60,pumpify:73,stream:223}],2:[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+fieldName+sep+ingestedDoc.id+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:223,util:229}],3:[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,docKey="DOCUMENT"+sep+docId+sep;this.options.indexes.get(docKey,function(err,val){if(err)return end();var docFields=Object.keys(val);docFields.push("*"),docFields=docFields.map(function(item){return"DOCUMENT-VECTOR"+sep+item+sep+docId+sep});var i=0,pushValue=function(key){that.options.indexes.get(key,function(err,val){if(err&&that.options.log.info(err),i===docFields.length)return end();that.push({key:key,value:val,lastPass:++i===docFields.length||!1}),pushValue(docFields[i])})};pushValue(docFields[0])})};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 that=this,field=vector.key.split(sep)[1],docId=vector.key.split(sep)[2],vectorKeys=Object.keys(vector.value),i=0,pushRecalibrationvalues=function(vec){if(that.push({key:"TF"+sep+field+sep+vectorKeys[i],value:docId}),that.push({key:"DF"+sep+field+sep+vectorKeys[i],value:docId}),++i===vectorKeys.length)return that.push({key:vector.key}),!0===vector.lastPass&&that.push({key:"DOCUMENT"+sep+docId+sep}),end();pushRecalibrationvalues(vector[vectorKeys[i]])};pushRecalibrationvalues(vector[vectorKeys[0]])};const RecalibrateDB=function(options){this.options=options,this.batch=[],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={};return 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",that.batch.push(dbInstruction),end()):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",that.batch.push(dbInstruction),end()):dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep?(dbInstruction.type="del",that.batch.push(dbInstruction),end()):void(dbEntry.key.substring(0,9)==="DOCUMENT"+sep&&(dbInstruction.type="del",that.batch.push(dbInstruction),that.options.indexes.batch(that.batch,function(err){return that.batch=[],end()})))})}},{stream:223,util:229}],4:[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:223,util:229}],5:[function(require,module,exports){(function(process,Buffer){"use strict";function check(x,y){return"string"==typeof x?y==x:x&&"function"==typeof x.exec?x.exec(y):"boolean"==typeof x||"object"==typeof x?x:"function"==typeof x&&x(y)}var Parser=require("jsonparse"),through=require("through");exports.parse=function(path,map){function setHeaderFooter(key,value){!1!==header&&(header=header||{},header[key]=value),!1!==footer&&!1===header&&(footer=footer||{},footer[key]=value)}var header,footer,parser=new Parser,stream=through(function(chunk){"string"==typeof chunk&&(chunk=new Buffer(chunk)),parser.write(chunk)},function(data){data&&stream.write(data),header&&stream.emit("header",header),footer&&stream.emit("footer",footer),stream.queue(null)});"string"==typeof path&&(path=path.split(".").map(function(e){return"$*"===e?{emitKey:!0}:"*"===e||(""===e?{recurse:!0}:e)}));var count=0;return path&&path.length||(path=null),parser.onValue=function(value){if(this.root||(stream.root=value),path){for(var i=0,j=0,emitKey=!1,emitPath=!1;i-1&&(err.message="Invalid JSON ("+err.message+")"),stream.emit("error",err)},stream},exports.stringify=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="[\n",sep="\n,\n",cl="\n]\n");var stream,first=!0,anyData=!1;return stream=through(function(data){anyData=!0;try{var json=JSON.stringify(data,null,indent)}catch(err){return stream.emit("error",err)}first?(first=!1,stream.queue(op+json)):stream.queue(sep+json)},function(data){anyData||stream.queue(op),stream.queue(cl),stream.queue(null)})},exports.stringifyObject=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="{\n",sep="\n,\n",cl="\n}\n");var first=!0,anyData=!1;return through(function(data){anyData=!0;var json=JSON.stringify(data[0])+":"+JSON.stringify(data[1],null,indent);first?(first=!1,this.queue(op+json)):this.queue(sep+json)},function(data){anyData||this.queue(op),this.queue(cl),this.queue(null)})},module.parent||"browser"===process.title||process.stdin.pipe(exports.parse(process.argv[2])).pipe(exports.stringify("[",",\n","]\n",2)).pipe(process.stdout)}).call(this,require("_process"),require("buffer").Buffer)},{_process:206,buffer:156,jsonparse:38,through:88}],6:[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;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("../../../../search-index/node_modules/is-buffer/index.js")},require("_process"))},{"../../../../search-index/node_modules/is-buffer/index.js":173,_process:206,assert:152,events:169,fs:155,os:204,"safe-json-stringify":83,stream:223,util:229}],8:[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("../../../../search-index/node_modules/is-buffer/index.js")})},{"../../../../search-index/node_modules/is-buffer/index.js":173}],9:[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":14,util:229}],10:[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("../../../search-index/node_modules/is-buffer/index.js")},require("_process"))},{"../../../search-index/node_modules/is-buffer/index.js":173,"./deferred-iterator":9,_process:206,"abstract-leveldown":14,util:229}],11:[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:206}],12:[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:206}],13:[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:223,util:229}],28:[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:206,buffer:156,"end-of-stream":29,inherits:35,"readable-stream":81,"stream-shift":84}],29:[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:30}],30:[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:91}],31:[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:33}],32:[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":31}],33:[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)}})},{}],34:[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=STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8"),this.stringBufferOffset=0),this.stringBuffer[this.stringBufferOffset++]=char},proto.appendStringBuf=function(buf,start,end){var size=buf.length;"number"==typeof start&&(size="number"==typeof end?end<0?buf.length-start+end:end-start:buf.length-start),size<0&&(size=0),this.stringBufferOffset+size>STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0),buf.copy(this.stringBuffer,this.stringBufferOffset,start,end),this.stringBufferOffset+=size},proto.write=function(buffer){"string"==typeof buffer&&(buffer=new Buffer(buffer));for(var n,i=0,l=buffer.length;i=48&&n<64)this.string=String.fromCharCode(n),this.tState=NUMBER3;else if(32!==n&&9!==n&&10!==n&&13!==n)return this.charError(buffer,i)}else if(this.tState===STRING1)if(n=buffer[i],this.bytes_remaining>0){for(var j=0;j=128){if(n<=193||n>244)return this.onError(new Error("Invalid UTF-8 character at position "+i+" in state "+Parser.toknam(this.tState)));if(n>=194&&n<=223&&(this.bytes_in_sequence=2),n>=224&&n<=239&&(this.bytes_in_sequence=3),n>=240&&n<=244&&(this.bytes_in_sequence=4),this.bytes_in_sequence+i>buffer.length){for(var k=0;k<=buffer.length-1-i;k++)this.temp_buffs[this.bytes_in_sequence][k]=buffer[i+k];this.bytes_remaining=i+this.bytes_in_sequence-buffer.length,i=buffer.length-1}else this.appendStringBuf(buffer,i,i+this.bytes_in_sequence),i=i+this.bytes_in_sequence-1}else if(34===n)this.tState=START,this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0,this.onToken(STRING,this.string),this.offset+=Buffer.byteLength(this.string,"utf8")+1,this.string=void 0;else if(92===n)this.tState=STRING2;else{if(!(n>=32))return this.charError(buffer,i);this.appendStringChar(n)}else if(this.tState===STRING2)if(34===(n=buffer[i]))this.appendStringChar(n),this.tState=STRING1;else if(92===n)this.appendStringChar(BACK_SLASH),this.tState=STRING1;else if(47===n)this.appendStringChar(FORWARD_SLASH),this.tState=STRING1;else if(98===n)this.appendStringChar(BACKSPACE),this.tState=STRING1;else if(102===n)this.appendStringChar(FORM_FEED),this.tState=STRING1;else if(110===n)this.appendStringChar(NEWLINE),this.tState=STRING1;else if(114===n)this.appendStringChar(CARRIAGE_RETURN),this.tState=STRING1;else if(116===n)this.appendStringChar(TAB),this.tState=STRING1;else{if(117!==n)return this.charError(buffer,i);this.unicode="",this.tState=STRING3}else if(this.tState===STRING3||this.tState===STRING4||this.tState===STRING5||this.tState===STRING6){if(!((n=buffer[i])>=48&&n<64||n>64&&n<=70||n>96&&n<=102))return this.charError(buffer,i);if(this.unicode+=String.fromCharCode(n),this.tState++===STRING6){var intVal=parseInt(this.unicode,16);this.unicode=void 0,void 0!==this.highSurrogate&&intVal>=56320&&intVal<57344?(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate,intVal))),this.highSurrogate=void 0):void 0===this.highSurrogate&&intVal>=55296&&intVal<56320?this.highSurrogate=intVal:(void 0!==this.highSurrogate&&(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.appendStringBuf(new Buffer(String.fromCharCode(intVal)))),this.tState=STRING1}}else if(this.tState===NUMBER1||this.tState===NUMBER3)switch(n=buffer[i]){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 46:case 101:case 69:case 43:case 45:this.string+=String.fromCharCode(n),this.tState=NUMBER3;break;default:this.tState=START;var result=Number(this.string);if(isNaN(result))return this.charError(buffer,i);this.string.match(/[0-9]+/)==this.string&&result.toString()!=this.string?this.onToken(STRING,this.string):this.onToken(NUMBER,result),this.offset+=this.string.length-1,this.string=void 0,i--}else if(this.tState===TRUE1){if(114!==buffer[i])return this.charError(buffer,i);this.tState=TRUE2}else if(this.tState===TRUE2){if(117!==buffer[i])return this.charError(buffer,i);this.tState=TRUE3}else if(this.tState===TRUE3){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(TRUE,!0),this.offset+=3}else if(this.tState===FALSE1){if(97!==buffer[i])return this.charError(buffer,i);this.tState=FALSE2}else if(this.tState===FALSE2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=FALSE3}else if(this.tState===FALSE3){if(115!==buffer[i])return this.charError(buffer,i);this.tState=FALSE4}else if(this.tState===FALSE4){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(FALSE,!1),this.offset+=4}else if(this.tState===NULL1){if(117!==buffer[i])return this.charError(buffer,i);this.tState=NULL2}else if(this.tState===NULL2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=NULL3}else if(this.tState===NULL3){if(108!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(NULL,null),this.offset+=3}},proto.onToken=function(token,value){},proto.parseError=function(token,value){this.tState=STOP,this.onError(new Error("Unexpected "+Parser.toknam(token)+(value?"("+JSON.stringify(value)+")":"")+" in state "+Parser.toknam(this.state)))},proto.push=function(){this.stack.push({value:this.value,key:this.key,mode:this.mode})},proto.pop=function(){var value=this.value,parent=this.stack.pop();this.value=parent.value,this.key=parent.key,this.mode=parent.mode,this.emit(value),this.mode||(this.state=VALUE)},proto.emit=function(value){this.mode&&(this.state=COMMA),this.onValue(value)},proto.onValue=function(value){},proto.onToken=function(token,value){if(this.state===VALUE)if(token===STRING||token===NUMBER||token===TRUE||token===FALSE||token===NULL)this.value&&(this.value[this.key]=value),this.emit(value);else if(token===LEFT_BRACE)this.push(),this.value?this.value=this.value[this.key]={}:this.value={},this.key=void 0,this.state=KEY,this.mode=OBJECT;else if(token===LEFT_BRACKET)this.push(),this.value?this.value=this.value[this.key]=[]:this.value=[],this.key=0,this.mode=ARRAY,this.state=VALUE;else if(token===RIGHT_BRACE){if(this.mode!==OBJECT)return this.parseError(token,value);this.pop()}else{if(token!==RIGHT_BRACKET)return this.parseError(token,value);if(this.mode!==ARRAY)return this.parseError(token,value);this.pop()}else if(this.state===KEY)if(token===STRING)this.key=value,this.state=COLON;else{if(token!==RIGHT_BRACE)return this.parseError(token,value);this.pop()}else if(this.state===COLON){if(token!==COLON)return this.parseError(token,value);this.state=VALUE}else{if(this.state!==COMMA)return this.parseError(token,value);if(token===COMMA)this.mode===ARRAY?(this.key++,this.state=VALUE):this.mode===OBJECT&&(this.state=KEY);else{if(!(token===RIGHT_BRACKET&&this.mode===ARRAY||token===RIGHT_BRACE&&this.mode===OBJECT))return this.parseError(token,value);this.pop()}}},Parser.C=C,module.exports=Parser}).call(this,require("buffer").Buffer)},{buffer:156}],39:[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":40}],40:[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:156}],41:[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:32}],42:[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:35,"level-errors":41,"readable-stream":49,xtend:92}],43:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],44:[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:156}],51:[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":55,ltgt:63,util:229}],53:[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:206}],54:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{_process:206,dup:12}],55:[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;i-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:{})},{}],63:[function(require,module,exports){(function(Buffer){function has(obj,key){return Object.hasOwnProperty.call(obj,key)}function isDef(val){return void 0!==val&&""!==val}function has(range,name){return Object.hasOwnProperty.call(range,name)}function hasKey(range,name){return Object.hasOwnProperty.call(range,name)&&name}function id(e){return e}exports.compare=function(a,b){if(Buffer.isBuffer(a)){for(var l=Math.min(a.length,b.length),i=0;ib?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("../../../search-index/node_modules/is-buffer/index.js")})},{"../../../search-index/node_modules/is-buffer/index.js":173}],64:[function(require,module,exports){var hasOwn=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,isFunction=function(fn){var isFunc="function"==typeof fn&&!(fn instanceof RegExp)||"[object Function]"===toString.call(fn);return isFunc||"undefined"==typeof window||(isFunc=fn===window.setTimeout||fn===window.alert||fn===window.confirm||fn===window.prompt),isFunc};module.exports=function(obj,fn){if(!isFunction(fn))throw new TypeError("iterator must be a function");var i,k,isString="string"==typeof obj,l=obj.length,context=arguments.length>2?arguments[2]:null;if(l===+l)for(i=0;i=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],67:[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":64,"./isArguments":66}],68:[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:91}],69:[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;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":72,fs:154,once:68}],72:[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:68}],73:[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:28,inherits:35,pump:71}],74:[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 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 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 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(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){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",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;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;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;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)||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(){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)}}).call(this,require("_process"))},{"./_stream_duplex":74,"./internal/streams/stream":80,_process:206,"core-util-is":8,inherits:35,"process-nextick-args":69,"safe-buffer":82,"util-deprecate":90}],79:[function(require,module,exports){"use strict";function BufferList(){this.head=null,this.tail=null,this.length=0}var Buffer=require("safe-buffer").Buffer;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 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;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},{"safe-buffer":82}],80:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:169}],81:[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":74,"./lib/_stream_passthrough.js":75,"./lib/_stream_readable.js":76,"./lib/_stream_transform.js":77,"./lib/_stream_writable.js":78}],82:[function(require,module,exports){module.exports=require("buffer")},{buffer:156}],83:[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},{}],84:[function(require,module,exports){function shift(stream){var rs=stream._readableState;return rs?rs.objectMode?stream.read():stream.read(getStateLength(rs)):null}function getStateLength(state){return state.buffer.length?state.buffer.head?state.buffer.head.data.length:state.buffer[0].length:state.length}module.exports=shift},{}],85:[function(require,module,exports){"use strict";function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0}}function normalizeEncoding(enc){ -var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd)}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){return byte<=127?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(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;j0&&(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":141,"lodash.uniq":145,stream:223,util:229}],96:[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":141,stream:223,util:229}],97:[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":144,stream:223,util:229}],98:[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:223,util:229}],106:[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:223,util:229}],109:[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.lengthsortedSets[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:223}],125:[function(require,module,exports){arguments[4][39][0].apply(exports,arguments)},{"./lib/encodings":126,dup:39}],126:[function(require,module,exports){arguments[4][40][0].apply(exports,arguments)},{buffer:156,dup:40}],127:[function(require,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,errno:121}],128:[function(require,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,inherits:123,"level-errors":127,"readable-stream":135,xtend:149}],129:[function(require,module,exports){arguments[4][43][0].apply(exports,arguments)},{dup:43}],130:[function(require,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./_stream_readable":132,"./_stream_writable":134,_process:206,"core-util-is":112,dup:44,inherits:123}],131:[function(require,module,exports){arguments[4][45][0].apply(exports,arguments)},{"./_stream_transform":133,"core-util-is":112,dup:45,inherits:123}],132:[function(require,module,exports){arguments[4][46][0].apply(exports,arguments)},{"./_stream_duplex":130,_process:206,buffer:156,"core-util-is":112,dup:46,events:169,inherits:123,isarray:129,stream:223,"string_decoder/":136,util:154}],133:[function(require,module,exports){arguments[4][47][0].apply(exports,arguments)},{"./_stream_duplex":130,"core-util-is":112,dup:47,inherits:123}],134:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{"./_stream_duplex":130,_process:206,buffer:156,"core-util-is":112,dup:48,inherits:123,stream:223}],135:[function(require,module,exports){arguments[4][49][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":130,"./lib/_stream_passthrough.js":131,"./lib/_stream_readable.js":132,"./lib/_stream_transform.js":133,"./lib/_stream_writable.js":134,_process:206,dup:49,stream:223}],136:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{buffer:156,dup:50}],137:[function(require,module,exports){arguments[4][59][0].apply(exports,arguments)},{"./util":139,dup:59,"level-errors":127}],138:[function(require,module,exports){arguments[4][60][0].apply(exports,arguments)},{"./batch":137,"./leveldown":154,"./util":139,_process:206,"deferred-leveldown":114,dup:60,events:169,"level-codec":125,"level-errors":127,"level-iterator-stream":128,prr:147,util:229,xtend:149}],139:[function(require,module,exports){arguments[4][61][0].apply(exports,arguments)},{dup:61,xtend:149}],140:[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();++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,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},{}],144:[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(;++index=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/":229}],153:[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,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":173,_process:206,assert:152,events:169,fs:155,os:204,"safe-json-stringify":222,stream:223,util:229}],158:[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":173}],159:[function(require,module,exports){arguments[4][9][0].apply(exports,arguments)},{"abstract-leveldown":164,dup:9,util:229}],160:[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":173,"./deferred-iterator":159,_process:206,"abstract-leveldown":164,util:229}],161:[function(require,module,exports){arguments[4][11][0].apply(exports,arguments)},{_process:206,dup:11}],162:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{_process:206,dup:12}],163:[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;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)}},{}],170:[function(require,module,exports){arguments[4][34][0].apply(exports,arguments)},{dup:34}],171:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN: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}},{}],172:[function(require,module,exports){arguments[4][35][0].apply(exports,arguments)},{dup:35}],173:[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)}},{}],174:[function(require,module,exports){arguments[4][36][0].apply(exports,arguments)},{dup:36}],175:[function(require,module,exports){arguments[4][37][0].apply(exports,arguments)},{buffer:156,dup:37}],176:[function(require,module,exports){arguments[4][39][0].apply(exports,arguments)},{"./lib/encodings":177,dup:39}],177:[function(require,module,exports){arguments[4][40][0].apply(exports,arguments)},{buffer:156,dup:40}],178:[function(require,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,errno:167}],179:[function(require,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,inherits:172,"level-errors":178,"readable-stream":186,xtend:230}],180:[function(require,module,exports){arguments[4][43][0].apply(exports,arguments)},{dup:43}],181:[function(require,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./_stream_readable":183, -"./_stream_writable":185,_process:206,"core-util-is":158,dup:44,inherits:172}],182:[function(require,module,exports){arguments[4][45][0].apply(exports,arguments)},{"./_stream_transform":184,"core-util-is":158,dup:45,inherits:172}],183:[function(require,module,exports){arguments[4][46][0].apply(exports,arguments)},{"./_stream_duplex":181,_process:206,buffer:156,"core-util-is":158,dup:46,events:169,inherits:172,isarray:180,stream:223,"string_decoder/":187,util:154}],184:[function(require,module,exports){arguments[4][47][0].apply(exports,arguments)},{"./_stream_duplex":181,"core-util-is":158,dup:47,inherits:172}],185:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{"./_stream_duplex":181,_process:206,buffer:156,"core-util-is":158,dup:48,inherits:172,stream:223}],186:[function(require,module,exports){arguments[4][49][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":181,"./lib/_stream_passthrough.js":182,"./lib/_stream_readable.js":183,"./lib/_stream_transform.js":184,"./lib/_stream_writable.js":185,_process:206,dup:49,stream:223}],187:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{buffer:156,dup:50}],188:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{"./iterator":189,"abstract-leveldown":192,buffer:156,dup:51,"idb-wrapper":170,isbuffer:175,"typedarray-to-buffer":225,util:229,xtend:199}],189:[function(require,module,exports){arguments[4][52][0].apply(exports,arguments)},{"abstract-leveldown":192,dup:52,ltgt:203,util:229}],190:[function(require,module,exports){arguments[4][53][0].apply(exports,arguments)},{_process:206,dup:53}],191:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{_process:206,dup:12}],192:[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;ib?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":173}],204:[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"},{}],205:[function(require,module,exports){arguments[4][69][0].apply(exports,arguments)},{_process:206,dup:69}],206:[function(require,module,exports){function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex1)for(var i=1;i0?("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":209,"./internal/streams/destroy":215,"./internal/streams/stream":216,_process:206,"core-util-is":158,inherits:172,"process-nextick-args":205,"safe-buffer":221,"util-deprecate":226}],214:[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":221}],215:[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":205}],216:[function(require,module,exports){arguments[4][80][0].apply(exports,arguments)},{dup:80,events:169}],217:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":218}],218:[function(require,module,exports){arguments[4][81][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":209,"./lib/_stream_passthrough.js":210,"./lib/_stream_readable.js":211,"./lib/_stream_transform.js":212,"./lib/_stream_writable.js":213,dup:81}],219:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":218}],220:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":213}],221:[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:156}],222:[function(require,module,exports){arguments[4][83][0].apply(exports,arguments)},{dup:83}],223:[function(require,module,exports){function Stream(){EE.call(this)}module.exports=Stream;var EE=require("events").EventEmitter;require("inherits")(Stream,EE),Stream.Readable=require("readable-stream/readable.js"),Stream.Writable=require("readable-stream/writable.js"),Stream.Duplex=require("readable-stream/duplex.js"),Stream.Transform=require("readable-stream/transform.js"),Stream.PassThrough=require("readable-stream/passthrough.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}var source=this;source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:169,inherits:172,"readable-stream/duplex.js":208,"readable-stream/passthrough.js":217,"readable-stream/readable.js":218,"readable-stream/transform.js":219,"readable-stream/writable.js":220}],224:[function(require,module,exports){arguments[4][85][0].apply(exports,arguments)},{dup:85,"safe-buffer":221}],225:[function(require,module,exports){arguments[4][89][0].apply(exports,arguments)},{buffer:156,dup:89}],226:[function(require,module,exports){arguments[4][90][0].apply(exports,arguments)},{dup:90}],227:[function(require,module,exports){arguments[4][35][0].apply(exports,arguments)},{dup:35}],228:[function(require,module,exports){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],229:[function(require,module,exports){(function(process,global){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){base=" [Function"+(value.name?": "+value.name:"")+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;return output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];i-1&&(err.message="Invalid JSON ("+err.message+")"),stream.emit("error",err)},stream},exports.stringify=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="[\n",sep="\n,\n",cl="\n]\n");var stream,first=!0,anyData=!1;return stream=through(function(data){anyData=!0;try{var json=JSON.stringify(data,null,indent)}catch(err){return stream.emit("error",err)}first?(first=!1,stream.queue(op+json)):stream.queue(sep+json)},function(data){anyData||stream.queue(op),stream.queue(cl),stream.queue(null)})},exports.stringifyObject=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="{\n",sep="\n,\n",cl="\n}\n");var first=!0,anyData=!1;return through(function(data){anyData=!0;var json=JSON.stringify(data[0])+":"+JSON.stringify(data[1],null,indent);first?(first=!1,this.queue(op+json)):this.queue(sep+json)},function(data){anyData||this.queue(op),this.queue(cl),this.queue(null)})},module.parent||"browser"===process.title||process.stdin.pipe(exports.parse(process.argv[2])).pipe(exports.stringify("[",",\n","]\n",2)).pipe(process.stdout)}).call(this,require("_process"),require("buffer").Buffer)},{_process:85,buffer:9,jsonparse:45,through:152}],4:[function(require,module,exports){(function(global){"use strict";function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);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="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/":157}],5:[function(require,module,exports){(function(process,global){!function(global,factory){factory("object"==typeof exports&&void 0!==module?exports: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)<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,1),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){var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(function(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)},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,setImmediate$1=wrap(_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback),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,nativeObjectToString$1=Object.prototype.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,Buffer=freeModule&&freeModule.exports===freeExports?root.Buffer:void 0,isBuffer=(Buffer?Buffer.isBuffer:void 0)||function(){return!1},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,freeProcess=freeModule$1&&freeModule$1.exports===freeExports$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):function(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]},hasOwnProperty$1=Object.prototype.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),hasOwnProperty$3=Object.prototype.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 numTasks=keys(tasks).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 counter=0;readyToCheck.length;)counter++,arrayEach(getDependents(readyToCheck.pop()),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])?",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*"),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 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;i0?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},exports.fromByteArray=function(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,output="",parts=[],i=0,len2=len-extraBytes;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("")};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 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:128==(192&(secondByte=buf[i+1]))&&(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,"")).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=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},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){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;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.12",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:85,assert:4,events:37,fs:8,os:83,"safe-json-stringify":103,stream:147,util:157}],11:[function(require,module,exports){(function(Buffer){function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=function(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)},exports.isBoolean=function(arg){return"boolean"==typeof arg},exports.isNull=function(arg){return null===arg},exports.isNullOrUndefined=function(arg){return null==arg},exports.isNumber=function(arg){return"number"==typeof arg},exports.isString=function(arg){return"string"==typeof arg},exports.isSymbol=function(arg){return"symbol"==typeof arg},exports.isUndefined=function(arg){return void 0===arg},exports.isRegExp=function(re){return"[object RegExp]"===objectToString(re)},exports.isObject=function(arg){return"object"==typeof arg&&null!==arg},exports.isDate=function(d){return"[object Date]"===objectToString(d)},exports.isError=function(e){return"[object Error]"===objectToString(e)||e instanceof Error},exports.isFunction=function(arg){return"function"==typeof arg},exports.isPrimitive=function(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg},exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":42}],12:[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":17,util:157}],13:[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":12,_process:85,"abstract-leveldown":17,util:157}],14:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._serializeKey=function(key){return this._db._serializeKey(key)},AbstractChainedBatch.prototype._serializeValue=function(value){return this._db._serializeValue(value)},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 key=this._serializeKey(key),value=this._serializeValue(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 key=this._serializeKey(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,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:85}],16:[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"))?callback(err):(key=this._serializeKey(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"))?callback(err):(key=this._serializeKey(key),value=this._serializeValue(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"))?callback(err):(key=this._serializeKey(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:147,util:157}],32:[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)writable&&writable.destroy&&writable.destroy();else if(null!==writable&&!1!==writable){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()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=function(){self._writable.removeListener("drain",ondrain),unend()},this.uncork()}else this.end()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)readable&&readable.destroy&&readable.destroy();else{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)};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=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()},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:85,buffer:9,"end-of-stream":33,inherits:40,"readable-stream":99,"stream-shift":148}],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:82}],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),len=(listeners=handler.slice()).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";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)this.onStoreReady();else if(this.db=event.target.result,"string"!=typeof this.db.version)if(this.db.objectStoreNames.contains(this.storeName)){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()}else this.onError(new Error("Object store couldn't be created."));else this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."))}.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&&(onError=onSuccess=options,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;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=function(err){batchTransaction.abort(),called||(called=!0,onError(err))}},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 getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=function(err){called=!0,result=err,onError(err),batchTransaction.abort()}},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))*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:147}],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){var Buffer=require("buffer").Buffer;module.exports=function(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}},{buffer:9}],45:[function(require,module,exports){(function(Buffer){function Parser(){this.tState=START,this.value=void 0,this.string=void 0,this.stringBuffer=Buffer.alloc?Buffer.alloc(STRING_BUFFER_SIZE):new Buffer(STRING_BUFFER_SIZE),this.stringBufferOffset=0,this.unicode=void 0,this.highSurrogate=void 0,this.key=void 0,this.mode=void 0,this.stack=[],this.state=VALUE,this.bytes_remaining=0,this.bytes_in_sequence=0,this.temp_buffs={2:new Buffer(2),3:new Buffer(3),4:new Buffer(4)},this.offset=-1}var C={},LEFT_BRACE=C.LEFT_BRACE=1,RIGHT_BRACE=C.RIGHT_BRACE=2,LEFT_BRACKET=C.LEFT_BRACKET=3,RIGHT_BRACKET=C.RIGHT_BRACKET=4,COLON=C.COLON=5,COMMA=C.COMMA=6,TRUE=C.TRUE=7,FALSE=C.FALSE=8,NULL=C.NULL=9,STRING=C.STRING=10,NUMBER=C.NUMBER=11,START=C.START=17,STOP=C.STOP=18,TRUE1=C.TRUE1=33,TRUE2=C.TRUE2=34,TRUE3=C.TRUE3=35,FALSE1=C.FALSE1=49,FALSE2=C.FALSE2=50,FALSE3=C.FALSE3=51,FALSE4=C.FALSE4=52,NULL1=C.NULL1=65,NULL2=C.NULL2=66,NULL3=C.NULL3=67,NUMBER1=C.NUMBER1=81,NUMBER3=C.NUMBER3=83,STRING1=C.STRING1=97,STRING2=C.STRING2=98,STRING3=C.STRING3=99,STRING4=C.STRING4=100,STRING5=C.STRING5=101,STRING6=C.STRING6=102,VALUE=C.VALUE=113,KEY=C.KEY=114,OBJECT=C.OBJECT=129,ARRAY=C.ARRAY=130,BACK_SLASH="\\".charCodeAt(0),FORWARD_SLASH="/".charCodeAt(0),BACKSPACE="\b".charCodeAt(0),FORM_FEED="\f".charCodeAt(0),NEWLINE="\n".charCodeAt(0),CARRIAGE_RETURN="\r".charCodeAt(0),TAB="\t".charCodeAt(0),STRING_BUFFER_SIZE=65536;Parser.toknam=function(code){for(var keys=Object.keys(C),i=0,l=keys.length;i=STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8"),this.stringBufferOffset=0),this.stringBuffer[this.stringBufferOffset++]=char},proto.appendStringBuf=function(buf,start,end){var size=buf.length;"number"==typeof start&&(size="number"==typeof end?end<0?buf.length-start+end:end-start:buf.length-start),size<0&&(size=0),this.stringBufferOffset+size>STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0),buf.copy(this.stringBuffer,this.stringBufferOffset,start,end),this.stringBufferOffset+=size},proto.write=function(buffer){"string"==typeof buffer&&(buffer=new Buffer(buffer));for(var n,i=0,l=buffer.length;i=48&&n<64)this.string=String.fromCharCode(n),this.tState=NUMBER3;else if(32!==n&&9!==n&&10!==n&&13!==n)return this.charError(buffer,i)}else if(this.tState===STRING1)if(n=buffer[i],this.bytes_remaining>0){for(var j=0;j=128){if(n<=193||n>244)return this.onError(new Error("Invalid UTF-8 character at position "+i+" in state "+Parser.toknam(this.tState)));if(n>=194&&n<=223&&(this.bytes_in_sequence=2),n>=224&&n<=239&&(this.bytes_in_sequence=3),n>=240&&n<=244&&(this.bytes_in_sequence=4),this.bytes_in_sequence+i>buffer.length){for(var k=0;k<=buffer.length-1-i;k++)this.temp_buffs[this.bytes_in_sequence][k]=buffer[i+k];this.bytes_remaining=i+this.bytes_in_sequence-buffer.length,i=buffer.length-1}else this.appendStringBuf(buffer,i,i+this.bytes_in_sequence),i=i+this.bytes_in_sequence-1}else if(34===n)this.tState=START,this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0,this.onToken(STRING,this.string),this.offset+=Buffer.byteLength(this.string,"utf8")+1,this.string=void 0;else if(92===n)this.tState=STRING2;else{if(!(n>=32))return this.charError(buffer,i);this.appendStringChar(n)}else if(this.tState===STRING2)if(34===(n=buffer[i]))this.appendStringChar(n),this.tState=STRING1;else if(92===n)this.appendStringChar(BACK_SLASH),this.tState=STRING1;else if(47===n)this.appendStringChar(FORWARD_SLASH),this.tState=STRING1;else if(98===n)this.appendStringChar(BACKSPACE),this.tState=STRING1;else if(102===n)this.appendStringChar(FORM_FEED),this.tState=STRING1;else if(110===n)this.appendStringChar(NEWLINE),this.tState=STRING1;else if(114===n)this.appendStringChar(CARRIAGE_RETURN),this.tState=STRING1;else if(116===n)this.appendStringChar(TAB),this.tState=STRING1;else{if(117!==n)return this.charError(buffer,i);this.unicode="",this.tState=STRING3}else if(this.tState===STRING3||this.tState===STRING4||this.tState===STRING5||this.tState===STRING6){if(!((n=buffer[i])>=48&&n<64||n>64&&n<=70||n>96&&n<=102))return this.charError(buffer,i);if(this.unicode+=String.fromCharCode(n),this.tState++===STRING6){var intVal=parseInt(this.unicode,16);this.unicode=void 0,void 0!==this.highSurrogate&&intVal>=56320&&intVal<57344?(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate,intVal))),this.highSurrogate=void 0):void 0===this.highSurrogate&&intVal>=55296&&intVal<56320?this.highSurrogate=intVal:(void 0!==this.highSurrogate&&(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.appendStringBuf(new Buffer(String.fromCharCode(intVal)))),this.tState=STRING1}}else if(this.tState===NUMBER1||this.tState===NUMBER3)switch(n=buffer[i]){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 46:case 101:case 69:case 43:case 45:this.string+=String.fromCharCode(n),this.tState=NUMBER3;break;default:this.tState=START;var result=Number(this.string);if(isNaN(result))return this.charError(buffer,i);this.string.match(/[0-9]+/)==this.string&&result.toString()!=this.string?this.onToken(STRING,this.string):this.onToken(NUMBER,result),this.offset+=this.string.length-1,this.string=void 0,i--}else if(this.tState===TRUE1){if(114!==buffer[i])return this.charError(buffer,i);this.tState=TRUE2}else if(this.tState===TRUE2){if(117!==buffer[i])return this.charError(buffer,i);this.tState=TRUE3}else if(this.tState===TRUE3){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(TRUE,!0),this.offset+=3}else if(this.tState===FALSE1){if(97!==buffer[i])return this.charError(buffer,i);this.tState=FALSE2}else if(this.tState===FALSE2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=FALSE3}else if(this.tState===FALSE3){if(115!==buffer[i])return this.charError(buffer,i);this.tState=FALSE4}else if(this.tState===FALSE4){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(FALSE,!1),this.offset+=4}else if(this.tState===NULL1){if(117!==buffer[i])return this.charError(buffer,i);this.tState=NULL2}else if(this.tState===NULL2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=NULL3}else if(this.tState===NULL3){if(108!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(NULL,null),this.offset+=3}},proto.onToken=function(token,value){},proto.parseError=function(token,value){this.tState=STOP,this.onError(new Error("Unexpected "+Parser.toknam(token)+(value?"("+JSON.stringify(value)+")":"")+" in state "+Parser.toknam(this.state)))},proto.push=function(){this.stack.push({value:this.value,key:this.key,mode:this.mode})},proto.pop=function(){var value=this.value,parent=this.stack.pop();this.value=parent.value,this.key=parent.key,this.mode=parent.mode,this.emit(value),this.mode||(this.state=VALUE)},proto.emit=function(value){this.mode&&(this.state=COMMA),this.onValue(value)},proto.onValue=function(value){},proto.onToken=function(token,value){if(this.state===VALUE)if(token===STRING||token===NUMBER||token===TRUE||token===FALSE||token===NULL)this.value&&(this.value[this.key]=value),this.emit(value);else if(token===LEFT_BRACE)this.push(),this.value?this.value=this.value[this.key]={}:this.value={},this.key=void 0,this.state=KEY,this.mode=OBJECT;else if(token===LEFT_BRACKET)this.push(),this.value?this.value=this.value[this.key]=[]:this.value=[],this.key=0,this.mode=ARRAY,this.state=VALUE;else if(token===RIGHT_BRACE){if(this.mode!==OBJECT)return this.parseError(token,value);this.pop()}else{if(token!==RIGHT_BRACKET)return this.parseError(token,value);if(this.mode!==ARRAY)return this.parseError(token,value);this.pop()}else if(this.state===KEY)if(token===STRING)this.key=value,this.state=COLON;else{if(token!==RIGHT_BRACE)return this.parseError(token,value);this.pop()}else if(this.state===COLON){if(token!==COLON)return this.parseError(token,value);this.state=VALUE}else{if(this.state!==COMMA)return this.parseError(token,value);if(token===COMMA)this.mode===ARRAY?(this.key++,this.state=VALUE):this.mode===OBJECT&&(this.state=KEY);else{if(!(token===RIGHT_BRACKET&&this.mode===ARRAY||token===RIGHT_BRACE&&this.mode===OBJECT))return this.parseError(token,value);this.pop()}}},Parser.C=C,module.exports=Parser}).call(this,require("buffer").Buffer)},{buffer:9}],46:[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":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:function(data){return"string"==typeof data?data:String(data)},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.none={encode:identity,decode:identity,buffer:!1,type:"id"},exports.id=exports.none,["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:9}],48:[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}],49:[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":48,"readable-stream":56,xtend:159}],50:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],51:[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){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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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);end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived);var end=(charStr+=buffer.toString(this.encoding,0,end)).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:9}],58:[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":62,ltgt:80,util:157}],60:[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:85}],61:[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:85}],62:[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}},{}],67:[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":64,"./isArguments":66}],68:[function(require,module,exports){module.exports=function(source){return null!==source&&("object"==typeof source||"function"==typeof source)}},{}],69:[function(require,module,exports){var Keys=require("object-keys"),hasKeys=require("./has-keys");module.exports=function(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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=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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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);++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)}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=function(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0},Hash.prototype.delete=function(key){var result=this.has(key)&&delete this.__data__[key];return this.size-=result?1:0,result},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[],this.size=0},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),--this.size,0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this},MapCache.prototype.clear=function(){this.size=0,this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){var result=getMapData(this,key).delete(key);return this.size-=result?1:0,result},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)},Stack.prototype.clear=function(){this.__data__=new ListCache,this.size=0},Stack.prototype.delete=function(key){var data=this.__data__,result=data.delete(key);return this.size=data.size,result},Stack.prototype.get=function(key){return this.__data__.get(key)},Stack.prototype.has=function(key){return this.__data__.has(key)},Stack.prototype.set=function(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),(end=end>length?length: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 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){return value?(value=toNumber(value))===INFINITY||value===-INFINITY?(value<0?-1:1)*MAX_INTEGER:value===value?value:0:0===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,objectToString=Object.prototype.toString,nativeMax=Math.max;module.exports=function(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)})}},{}],78:[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;++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}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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){},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=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},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){};module.exports=function(array){return array&&array.length?baseUniq(array):[]}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],80:[function(require,module,exports){(function(Buffer){function has(obj,key){return Object.hasOwnProperty.call(obj,key)}function isDef(val){return void 0!==val&&""!==val}function has(range,name){return Object.hasOwnProperty.call(range,name)}function hasKey(range,name){return Object.hasOwnProperty.call(range,name)&&name}function id(e){return e}exports.compare=function(a,b){if(Buffer.isBuffer(a)){for(var l=Math.min(a.length,b.length),i=0;ib?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)&&((cmp=compare(key,lb))<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}],81:[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)}}},{}],82:[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:158}],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,exports){(function(process){"use strict";!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?module.exports=function(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)}},{"end-of-stream":33,fs:7,once:82}],88:[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:32,inherits:40,pump:87}],89:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":90}],90:[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||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(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)?(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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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,OurUint8Array=global.Uint8Array||function(){},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"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./_stream_duplex":90,"./internal/streams/destroy":96,"./internal/streams/stream":97,_process:85,"core-util-is":11,inherits:40,"process-nextick-args":84,"safe-buffer":102,"util-deprecate":154}],95:[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":102}],96:[function(require,module,exports){"use strict";function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;readableDestroyed||writableDestroyed?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)}))},undestroy:function(){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)}}},{"process-nextick-args":84}],97:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:37}],98:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":99}],99:[function(require,module,exports){(exports=module.exports=require("./lib/_stream_readable.js")).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}],100:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":99}],101:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":94}],102:[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:9}],103:[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},{}],104:[function(require,module,exports){const bunyan=require("bunyan"),levelup=require("levelup"),API=require("./lib/API.js");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){const api=API(options),Indexer={};return Indexer.options=options,Indexer.add=api.add,Indexer.concurrentAdd=api.concurrentAdd,Indexer.concurrentDel=api.concurrentDel,Indexer.close=api.close,Indexer.dbWriteStream=api.dbWriteStream,Indexer.defaultPipeline=api.defaultPipeline,Indexer.deleteStream=api.deleteStream,Indexer.deleter=api.deleter,Indexer.feed=api.feed,Indexer.flush=api.flush,callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{appendOnly:!1,deletable:!0,batchSize:1e3,compositeField:!0,fastSort:!0,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,storeDocument:!0,storeVector:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0,wildcard:!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/API.js":105,bunyan:10,leveldown:58,levelup:71}],105:[function(require,module,exports){const DBEntries=require("./delete.js").DBEntries,DBWriteCleanStream=require("./replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./replicate.js").DBWriteMergeStream,DocVector=require("./delete.js").DocVector,JSONStream=require("JSONStream"),Readable=require("stream").Readable,RecalibrateDB=require("./delete.js").RecalibrateDB,IndexBatch=require("./add.js").IndexBatch,async=require("async"),del=require("./delete.js"),docProc=require("docproc"),pumpify=require("pumpify");module.exports=function(options){const 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),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={};return Indexer.add=function(ops){const thisOps=Object.assign(options,ops);return pumpify.obj(new IndexBatch(deleter,thisOps),new DBWriteMergeStream(thisOps))},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)).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=deleter,Indexer.feed=function(ops){return ops&&ops.objectMode?pumpify.obj(Indexer.defaultPipeline(ops),Indexer.add(ops)):pumpify(JSONStream.parse(),Indexer.defaultPipeline(ops),Indexer.add(ops))},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},Indexer}},{"./add.js":106,"./delete.js":107,"./replicate.js":108,JSONStream:3,async:5,docproc:19,pumpify:88,stream:147}],106:[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={}},noop=function(_,cb){cb()},IndexBatch=function(deleter,options){this.batchSize=options.batchSize||1e3,this.deleter=deleter,this.fastSort=options.fastSort,this.appendOnly=options.appendOnly,this.keySeparator=options.keySeparator||"○",this.log=options.log,this.storeDocument=options.storeDocument,this.storeVector=options.storeVector,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.keySeparator,that=this;(this.appendOnly?noop:this.deleter.bind(this.indexer))([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.log.info("processing doc "+ingestedDoc.id),!0===that.storeDocument&&(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]){if(that.fastSort){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id])}var dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.storeVector&&(that.deltaIndex["DOCUMENT-VECTOR"+sep+fieldName+sep+ingestedDoc.id+sep]=ingestedDoc.vector[fieldName])}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.batchSize&&(that.push({totalKeys:totalKeys}),that.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:147,util:157}],107:[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,docKey="DOCUMENT"+sep+docId+sep;this.options.indexes.get(docKey,function(err,val){if(err)return end();var docFields=Object.keys(val);docFields.push("*"),docFields=docFields.map(function(item){return"DOCUMENT-VECTOR"+sep+item+sep+docId+sep});var i=0,pushValue=function(key){if(void 0===key)return that.push({key:"DOCUMENT"+sep+docId+sep,lastPass:!0}),end();that.options.indexes.get(key,function(err,val){err||that.push({key:key,value:val}),pushValue(docFields[i++])})};pushValue(docFields[0])})};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){if(!0===vector.lastPass)return this.push({key:vector.key}),end();const sep=this.options.keySeparator;var that=this,field=vector.key.split(sep)[1],docId=vector.key.split(sep)[2],vectorKeys=Object.keys(vector.value),i=0,pushRecalibrationvalues=function(vec){if(that.push({key:"TF"+sep+field+sep+vectorKeys[i],value:docId}),that.push({key:"DF"+sep+field+sep+vectorKeys[i],value:docId}),++i===vectorKeys.length)return that.push({key:vector.key}),end();pushRecalibrationvalues(vector[vectorKeys[i]])};pushRecalibrationvalues(vector[vectorKeys[0]])};const RecalibrateDB=function(options){this.options=options,this.batch=[],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={};return 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",that.batch.push(dbInstruction),end()):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",that.batch.push(dbInstruction),end()):dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep?(dbInstruction.type="del",that.batch.push(dbInstruction),end()):void(dbEntry.key.substring(0,9)==="DOCUMENT"+sep&&(dbInstruction.type="del",that.batch.push(dbInstruction),that.options.indexes.batch(that.batch,function(err){return that.batch=[],end()})))})}},{stream:147,util:157}],108:[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:147,util:157}],109:[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,MergeOrConditionsTFIDF=require("./lib/MergeOrConditionsTFIDF.js").MergeOrConditionsTFIDF,MergeOrConditionsFieldSort=require("./lib/MergeOrConditionsFieldSort.js").MergeOrConditionsFieldSort,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),sw=require("stopword"),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 ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditionsFieldSort(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 MergeOrConditionsTFIDF(q.offset,q.pageSize)).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:sw.en},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":110,"./lib/CalculateBuckets.js":111,"./lib/CalculateCategories.js":112,"./lib/CalculateEntireResultSet.js":113,"./lib/CalculateResultSetPerClause.js":114,"./lib/CalculateTopScoringDocs.js":115,"./lib/CalculateTotalHits.js":116,"./lib/Classify.js":117,"./lib/FetchDocsFromDB.js":118,"./lib/FetchStoredDoc.js":119,"./lib/GetIntersectionStream.js":120,"./lib/MergeOrConditionsFieldSort.js":121,"./lib/MergeOrConditionsTFIDF.js":122,"./lib/ScoreDocsOnField.js":123,"./lib/ScoreTopScoringDocsTFIDF.js":124,"./lib/matcher.js":125,"./lib/siUtil.js":126,bunyan:10,levelup:71,stopword:127,stream:147}],110:[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:147,util:157}],111:[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":74,"lodash.uniq":79,stream:147,util:157}],112:[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":74,stream:147,util:157}],113:[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":78,stream:147,util:157}],114:[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){var include=_spread(_intersection)(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,documentFrequencies:frequencies,WEIGHT:queryClause.WEIGHT||1}),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;i({id:id,scoringCriteria:resultMap[id],score:resultMap[id][0].score})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:"asc"===that.sortDirection?b.scorea.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:147,util:157}],122:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),MergeOrConditionsTFIDF=function(offset,pageSize){this.resultSet=[],this.offset=offset,this.pageSize=pageSize,Transform.call(this,{objectMode:!0})};exports.MergeOrConditionsTFIDF=MergeOrConditionsTFIDF,util.inherits(MergeOrConditionsTFIDF,Transform),MergeOrConditionsTFIDF.prototype._transform=function(doc,encoding,end){return this.resultSet=this.resultSet.concat(doc.matches),end()},MergeOrConditionsTFIDF.prototype._flush=function(end){var that=this,resultMap=getResultMap(this.resultSet);return Object.keys(resultMap).map(id=>({id:id,scoringCriteria:resultMap[id],score:resultMap[id].reduce((sum,matches)=>sum+matches.score,0)/resultMap[id].length})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:b.score-a.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:147,util:157}],123:[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,sortDirection=this.sort.direction||"asc";var tally=0,rangeOptions={gte:"DF"+sep+this.sort.field+sep,lte:"DF"+sep+this.sort.field+sep+sep};"desc"===sortDirection&&(rangeOptions.reverse=!0),clauseSet.topScoringDocs=[],that.options.indexes.createReadStream(rangeOptions).on("data",function(data){var token=data.key.split(sep)[2];"*"!==token&&("desc"===sortDirection&&(data.value=data.value.reverse()),data.value.some(id=>{if(-1!==_sortedIndexOf(clauseSet.set,id)&&(clauseSet.topScoringDocs.push({id:id,score:token}),++tally===that.seekLimit))return!0}))}).on("end",function(){return that.push(clauseSet),end()})}},{"lodash.sortedindexof":76,stream:147,util:157}],124:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),ScoreTopScoringDocsTFIDF=function(options,offset,pageSize){this.options=options,Transform.call(this,{objectMode:!0})};exports.ScoreTopScoringDocsTFIDF=ScoreTopScoringDocsTFIDF,util.inherits(ScoreTopScoringDocsTFIDF,Transform),ScoreTopScoringDocsTFIDF.prototype._transform=function(clause,encoding,end){var that=this,promises=[];clause.topScoringDocs.forEach(doc=>{var docID=doc[1];promises.push(getMatchesForDoc(docID,that.options,clause))}),Promise.all(promises).then(res=>(clause.matches=res,that.push(clause),end()),err=>{console.log(err)})};const getMatchesForDoc=(docID,options,clause)=>new Promise((resolve,reject)=>{var termVectors=clause.documentFrequencies.map(freq=>gett(freq.field,docID,freq.gte,freq.lte,freq.df,clause.WEIGHT,options));Promise.all(termVectors).then(matchedTerms=>{var matches=[].concat.apply([],matchedTerms);resolve({id:docID,matches:matches,score:getScore(matches)})},err=>{console.log(err)})}),getScore=matchedTerms=>matchedTerms.reduce(function(sum,match){return sum+match.score},0)/matchedTerms.length,gett=(field,key,gte,lte,df,weight,options)=>{var s=options.keySeparator;return new Promise((resolve,reject)=>{options.indexes.get("DOCUMENT-VECTOR"+s+field+s+key+s,(err,value)=>{if(err)return reject(err);var matchedTermsWithMagnitude=[];return Object.keys(value).filter(t=>{if(t>=gte&&t<=lte)return!0}).forEach(t=>{var tf=value[t],tfidf=tf*Math.log10(1+1/df),term={field:field,term:t,tf:tf,df:df,tfidf:tfidf,weight:weight,score:tfidf*weight};matchedTermsWithMagnitude.push(term)}),resolve(matchedTermsWithMagnitude)})})}},{stream:147,util:157}],125:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatchMostFrequent=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchMostFrequent,Transform),MatchMostFrequent.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){var frequencySort=b.value.length-a.value.length;return 0===frequencySort?b.keya.key?-1:0:frequencySort}).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()})};const MatchAlphabetical=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchAlphabetical,Transform),MatchAlphabetical.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var space={start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep},i=0,rs=this.options.indexes.createReadStream(space);rs.on("data",function(data){var m={};switch(q.type){case"ID":m={token:data.key.split(sep)[2],documents:data.value};break;case"count":m={token:data.key.split(sep)[2],documentCount:data.value.length};break;default:m=data.key.split(sep)[2]}if(that.push(m),++i===q.limit)return rs.destroy(),end()}),rs.on("error",function(err){that.options.log.error("Oh my!",err)}),rs.on("end",function(){return end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return(q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple",sort:"frequency"},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 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(1===(ngrams=ngrams.sort()).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:"")+"]"),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)).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 isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==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 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]/,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":2,"./lib/delete.js":3,"./lib/replicate.js":4,JSONStream:5,async:6,bunyan:7,docproc:16,leveldown:51,levelup:60,pumpify:73,stream:223}],2:[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+fieldName+sep+ingestedDoc.id+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:223,util:229}],3:[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,docKey="DOCUMENT"+sep+docId+sep;this.options.indexes.get(docKey,function(err,val){if(err)return end();var docFields=Object.keys(val);docFields.push("*"),docFields=docFields.map(function(item){return"DOCUMENT-VECTOR"+sep+item+sep+docId+sep});var i=0,pushValue=function(key){that.options.indexes.get(key,function(err,val){if(err&&that.options.log.info(err),i===docFields.length)return end();that.push({key:key,value:val,lastPass:++i===docFields.length||!1}),pushValue(docFields[i])})};pushValue(docFields[0])})};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 that=this,field=vector.key.split(sep)[1],docId=vector.key.split(sep)[2],vectorKeys=Object.keys(vector.value),i=0,pushRecalibrationvalues=function(vec){if(that.push({key:"TF"+sep+field+sep+vectorKeys[i],value:docId}),that.push({key:"DF"+sep+field+sep+vectorKeys[i],value:docId}),++i===vectorKeys.length)return that.push({key:vector.key}),!0===vector.lastPass&&that.push({key:"DOCUMENT"+sep+docId+sep}),end();pushRecalibrationvalues(vector[vectorKeys[i]])};pushRecalibrationvalues(vector[vectorKeys[0]])};const RecalibrateDB=function(options){this.options=options,this.batch=[],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={};return 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",that.batch.push(dbInstruction),end()):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",that.batch.push(dbInstruction),end()):dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep?(dbInstruction.type="del",that.batch.push(dbInstruction),end()):void(dbEntry.key.substring(0,9)==="DOCUMENT"+sep&&(dbInstruction.type="del",that.batch.push(dbInstruction),that.options.indexes.batch(that.batch,function(err){return that.batch=[],end()})))})}},{stream:223,util:229}],4:[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:223,util:229}],5:[function(require,module,exports){(function(process,Buffer){"use strict";function check(x,y){return"string"==typeof x?y==x:x&&"function"==typeof x.exec?x.exec(y):"boolean"==typeof x||"object"==typeof x?x:"function"==typeof x&&x(y)}var Parser=require("jsonparse"),through=require("through");exports.parse=function(path,map){function setHeaderFooter(key,value){!1!==header&&(header=header||{},header[key]=value),!1!==footer&&!1===header&&(footer=footer||{},footer[key]=value)}var header,footer,parser=new Parser,stream=through(function(chunk){"string"==typeof chunk&&(chunk=new Buffer(chunk)),parser.write(chunk)},function(data){data&&stream.write(data),header&&stream.emit("header",header),footer&&stream.emit("footer",footer),stream.queue(null)});"string"==typeof path&&(path=path.split(".").map(function(e){return"$*"===e?{emitKey:!0}:"*"===e||(""===e?{recurse:!0}:e)}));var count=0;return path&&path.length||(path=null),parser.onValue=function(value){if(this.root||(stream.root=value),path){for(var i=0,j=0,emitKey=!1,emitPath=!1;i-1&&(err.message="Invalid JSON ("+err.message+")"),stream.emit("error",err)},stream},exports.stringify=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="[\n",sep="\n,\n",cl="\n]\n");var stream,first=!0,anyData=!1;return stream=through(function(data){anyData=!0;try{var json=JSON.stringify(data,null,indent)}catch(err){return stream.emit("error",err)}first?(first=!1,stream.queue(op+json)):stream.queue(sep+json)},function(data){anyData||stream.queue(op),stream.queue(cl),stream.queue(null)})},exports.stringifyObject=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="{\n",sep="\n,\n",cl="\n}\n");var first=!0,anyData=!1;return through(function(data){anyData=!0;var json=JSON.stringify(data[0])+":"+JSON.stringify(data[1],null,indent);first?(first=!1,this.queue(op+json)):this.queue(sep+json)},function(data){anyData||this.queue(op),this.queue(cl),this.queue(null)})},module.parent||"browser"===process.title||process.stdin.pipe(exports.parse(process.argv[2])).pipe(exports.stringify("[",",\n","]\n",2)).pipe(process.stdout)}).call(this,require("_process"),require("buffer").Buffer)},{_process:206,buffer:156,jsonparse:38,through:88}],6:[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;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("../../../../search-index/node_modules/is-buffer/index.js")},require("_process"))},{"../../../../search-index/node_modules/is-buffer/index.js":173,_process:206,assert:152,events:169,fs:155,os:204,"safe-json-stringify":83,stream:223,util:229}],8:[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("../../../../search-index/node_modules/is-buffer/index.js")})},{"../../../../search-index/node_modules/is-buffer/index.js":173}],9:[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":14,util:229}],10:[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("../../../search-index/node_modules/is-buffer/index.js")},require("_process"))},{"../../../search-index/node_modules/is-buffer/index.js":173,"./deferred-iterator":9,_process:206,"abstract-leveldown":14,util:229}],11:[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:206}],12:[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:206}],13:[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:223,util:229}],28:[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:206,buffer:156,"end-of-stream":29,inherits:35,"readable-stream":81,"stream-shift":84}],29:[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:30}],30:[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:91}],31:[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:33}],32:[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":31}],33:[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)}})},{}],34:[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=STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8"),this.stringBufferOffset=0),this.stringBuffer[this.stringBufferOffset++]=char},proto.appendStringBuf=function(buf,start,end){var size=buf.length;"number"==typeof start&&(size="number"==typeof end?end<0?buf.length-start+end:end-start:buf.length-start),size<0&&(size=0),this.stringBufferOffset+size>STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0),buf.copy(this.stringBuffer,this.stringBufferOffset,start,end),this.stringBufferOffset+=size},proto.write=function(buffer){"string"==typeof buffer&&(buffer=new Buffer(buffer));for(var n,i=0,l=buffer.length;i=48&&n<64)this.string=String.fromCharCode(n),this.tState=NUMBER3;else if(32!==n&&9!==n&&10!==n&&13!==n)return this.charError(buffer,i)}else if(this.tState===STRING1)if(n=buffer[i],this.bytes_remaining>0){for(var j=0;j=128){if(n<=193||n>244)return this.onError(new Error("Invalid UTF-8 character at position "+i+" in state "+Parser.toknam(this.tState)));if(n>=194&&n<=223&&(this.bytes_in_sequence=2),n>=224&&n<=239&&(this.bytes_in_sequence=3),n>=240&&n<=244&&(this.bytes_in_sequence=4),this.bytes_in_sequence+i>buffer.length){for(var k=0;k<=buffer.length-1-i;k++)this.temp_buffs[this.bytes_in_sequence][k]=buffer[i+k];this.bytes_remaining=i+this.bytes_in_sequence-buffer.length,i=buffer.length-1}else this.appendStringBuf(buffer,i,i+this.bytes_in_sequence),i=i+this.bytes_in_sequence-1}else if(34===n)this.tState=START,this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0,this.onToken(STRING,this.string),this.offset+=Buffer.byteLength(this.string,"utf8")+1,this.string=void 0;else if(92===n)this.tState=STRING2;else{if(!(n>=32))return this.charError(buffer,i);this.appendStringChar(n)}else if(this.tState===STRING2)if(34===(n=buffer[i]))this.appendStringChar(n),this.tState=STRING1;else if(92===n)this.appendStringChar(BACK_SLASH),this.tState=STRING1;else if(47===n)this.appendStringChar(FORWARD_SLASH),this.tState=STRING1;else if(98===n)this.appendStringChar(BACKSPACE),this.tState=STRING1;else if(102===n)this.appendStringChar(FORM_FEED),this.tState=STRING1;else if(110===n)this.appendStringChar(NEWLINE),this.tState=STRING1;else if(114===n)this.appendStringChar(CARRIAGE_RETURN),this.tState=STRING1;else if(116===n)this.appendStringChar(TAB),this.tState=STRING1;else{if(117!==n)return this.charError(buffer,i);this.unicode="",this.tState=STRING3}else if(this.tState===STRING3||this.tState===STRING4||this.tState===STRING5||this.tState===STRING6){if(!((n=buffer[i])>=48&&n<64||n>64&&n<=70||n>96&&n<=102))return this.charError(buffer,i);if(this.unicode+=String.fromCharCode(n),this.tState++===STRING6){var intVal=parseInt(this.unicode,16);this.unicode=void 0,void 0!==this.highSurrogate&&intVal>=56320&&intVal<57344?(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate,intVal))),this.highSurrogate=void 0):void 0===this.highSurrogate&&intVal>=55296&&intVal<56320?this.highSurrogate=intVal:(void 0!==this.highSurrogate&&(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.appendStringBuf(new Buffer(String.fromCharCode(intVal)))),this.tState=STRING1}}else if(this.tState===NUMBER1||this.tState===NUMBER3)switch(n=buffer[i]){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 46:case 101:case 69:case 43:case 45:this.string+=String.fromCharCode(n),this.tState=NUMBER3;break;default:this.tState=START;var result=Number(this.string);if(isNaN(result))return this.charError(buffer,i);this.string.match(/[0-9]+/)==this.string&&result.toString()!=this.string?this.onToken(STRING,this.string):this.onToken(NUMBER,result),this.offset+=this.string.length-1,this.string=void 0,i--}else if(this.tState===TRUE1){if(114!==buffer[i])return this.charError(buffer,i);this.tState=TRUE2}else if(this.tState===TRUE2){if(117!==buffer[i])return this.charError(buffer,i);this.tState=TRUE3}else if(this.tState===TRUE3){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(TRUE,!0),this.offset+=3}else if(this.tState===FALSE1){if(97!==buffer[i])return this.charError(buffer,i);this.tState=FALSE2}else if(this.tState===FALSE2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=FALSE3}else if(this.tState===FALSE3){if(115!==buffer[i])return this.charError(buffer,i);this.tState=FALSE4}else if(this.tState===FALSE4){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(FALSE,!1),this.offset+=4}else if(this.tState===NULL1){if(117!==buffer[i])return this.charError(buffer,i);this.tState=NULL2}else if(this.tState===NULL2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=NULL3}else if(this.tState===NULL3){if(108!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(NULL,null),this.offset+=3}},proto.onToken=function(token,value){},proto.parseError=function(token,value){this.tState=STOP,this.onError(new Error("Unexpected "+Parser.toknam(token)+(value?"("+JSON.stringify(value)+")":"")+" in state "+Parser.toknam(this.state)))},proto.push=function(){this.stack.push({value:this.value,key:this.key,mode:this.mode})},proto.pop=function(){var value=this.value,parent=this.stack.pop();this.value=parent.value,this.key=parent.key,this.mode=parent.mode,this.emit(value),this.mode||(this.state=VALUE)},proto.emit=function(value){this.mode&&(this.state=COMMA),this.onValue(value)},proto.onValue=function(value){},proto.onToken=function(token,value){if(this.state===VALUE)if(token===STRING||token===NUMBER||token===TRUE||token===FALSE||token===NULL)this.value&&(this.value[this.key]=value),this.emit(value);else if(token===LEFT_BRACE)this.push(),this.value?this.value=this.value[this.key]={}:this.value={},this.key=void 0,this.state=KEY,this.mode=OBJECT;else if(token===LEFT_BRACKET)this.push(),this.value?this.value=this.value[this.key]=[]:this.value=[],this.key=0,this.mode=ARRAY,this.state=VALUE;else if(token===RIGHT_BRACE){if(this.mode!==OBJECT)return this.parseError(token,value);this.pop()}else{if(token!==RIGHT_BRACKET)return this.parseError(token,value);if(this.mode!==ARRAY)return this.parseError(token,value);this.pop()}else if(this.state===KEY)if(token===STRING)this.key=value,this.state=COLON;else{if(token!==RIGHT_BRACE)return this.parseError(token,value);this.pop()}else if(this.state===COLON){if(token!==COLON)return this.parseError(token,value);this.state=VALUE}else{if(this.state!==COMMA)return this.parseError(token,value);if(token===COMMA)this.mode===ARRAY?(this.key++,this.state=VALUE):this.mode===OBJECT&&(this.state=KEY);else{if(!(token===RIGHT_BRACKET&&this.mode===ARRAY||token===RIGHT_BRACE&&this.mode===OBJECT))return this.parseError(token,value);this.pop()}}},Parser.C=C,module.exports=Parser}).call(this,require("buffer").Buffer)},{buffer:156}],39:[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":40}],40:[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:156}],41:[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:32}],42:[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:35,"level-errors":41,"readable-stream":49,xtend:92}],43:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],44:[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:156}],51:[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":55,ltgt:63,util:229}],53:[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:206}],54:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{_process:206,dup:12}],55:[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;i-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:{})},{}],63:[function(require,module,exports){(function(Buffer){function has(obj,key){return Object.hasOwnProperty.call(obj,key)}function isDef(val){return void 0!==val&&""!==val}function has(range,name){return Object.hasOwnProperty.call(range,name)}function hasKey(range,name){return Object.hasOwnProperty.call(range,name)&&name}function id(e){return e}exports.compare=function(a,b){if(Buffer.isBuffer(a)){for(var l=Math.min(a.length,b.length),i=0;ib?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("../../../search-index/node_modules/is-buffer/index.js")})},{"../../../search-index/node_modules/is-buffer/index.js":173}],64:[function(require,module,exports){var hasOwn=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,isFunction=function(fn){var isFunc="function"==typeof fn&&!(fn instanceof RegExp)||"[object Function]"===toString.call(fn);return isFunc||"undefined"==typeof window||(isFunc=fn===window.setTimeout||fn===window.alert||fn===window.confirm||fn===window.prompt),isFunc};module.exports=function(obj,fn){if(!isFunction(fn))throw new TypeError("iterator must be a function");var i,k,isString="string"==typeof obj,l=obj.length,context=arguments.length>2?arguments[2]:null;if(l===+l)for(i=0;i=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],67:[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":64,"./isArguments":66}],68:[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:91}],69:[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;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":72,fs:154,once:68}],72:[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:68}],73:[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:28,inherits:35,pump:71}],74:[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 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 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 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(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){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",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;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;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;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)||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(){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)}}).call(this,require("_process"))},{"./_stream_duplex":74,"./internal/streams/stream":80,_process:206,"core-util-is":8,inherits:35,"process-nextick-args":69,"safe-buffer":82,"util-deprecate":90}],79:[function(require,module,exports){"use strict";function BufferList(){this.head=null,this.tail=null,this.length=0}var Buffer=require("safe-buffer").Buffer;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 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;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},{"safe-buffer":82}],80:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:169}],81:[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":74,"./lib/_stream_passthrough.js":75,"./lib/_stream_readable.js":76,"./lib/_stream_transform.js":77,"./lib/_stream_writable.js":78}],82:[function(require,module,exports){module.exports=require("buffer")},{buffer:156}],83:[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},{}],84:[function(require,module,exports){function shift(stream){var rs=stream._readableState;return rs?rs.objectMode?stream.read():stream.read(getStateLength(rs)):null}function getStateLength(state){return state.buffer.length?state.buffer.head?state.buffer.head.data.length:state.buffer[0].length:state.length}module.exports=shift},{}],85:[function(require,module,exports){"use strict";function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0}}function normalizeEncoding(enc){ -var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd)}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){return byte<=127?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(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;j0&&(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":141,"lodash.uniq":145,stream:223,util:229}],96:[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":141,stream:223,util:229}],97:[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":144,stream:223,util:229}],98:[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:223,util:229}],106:[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:223,util:229}],109:[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.lengthsortedSets[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:223}],125:[function(require,module,exports){arguments[4][39][0].apply(exports,arguments)},{"./lib/encodings":126,dup:39}],126:[function(require,module,exports){arguments[4][40][0].apply(exports,arguments)},{buffer:156,dup:40}],127:[function(require,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,errno:121}],128:[function(require,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,inherits:123,"level-errors":127,"readable-stream":135,xtend:149}],129:[function(require,module,exports){arguments[4][43][0].apply(exports,arguments)},{dup:43}],130:[function(require,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./_stream_readable":132,"./_stream_writable":134,_process:206,"core-util-is":112,dup:44,inherits:123}],131:[function(require,module,exports){arguments[4][45][0].apply(exports,arguments)},{"./_stream_transform":133,"core-util-is":112,dup:45,inherits:123}],132:[function(require,module,exports){arguments[4][46][0].apply(exports,arguments)},{"./_stream_duplex":130,_process:206,buffer:156,"core-util-is":112,dup:46,events:169,inherits:123,isarray:129,stream:223,"string_decoder/":136,util:154}],133:[function(require,module,exports){arguments[4][47][0].apply(exports,arguments)},{"./_stream_duplex":130,"core-util-is":112,dup:47,inherits:123}],134:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{"./_stream_duplex":130,_process:206,buffer:156,"core-util-is":112,dup:48,inherits:123,stream:223}],135:[function(require,module,exports){arguments[4][49][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":130,"./lib/_stream_passthrough.js":131,"./lib/_stream_readable.js":132,"./lib/_stream_transform.js":133,"./lib/_stream_writable.js":134,_process:206,dup:49,stream:223}],136:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{buffer:156,dup:50}],137:[function(require,module,exports){arguments[4][59][0].apply(exports,arguments)},{"./util":139,dup:59,"level-errors":127}],138:[function(require,module,exports){arguments[4][60][0].apply(exports,arguments)},{"./batch":137,"./leveldown":154,"./util":139,_process:206,"deferred-leveldown":114,dup:60,events:169,"level-codec":125,"level-errors":127,"level-iterator-stream":128,prr:147,util:229,xtend:149}],139:[function(require,module,exports){arguments[4][61][0].apply(exports,arguments)},{dup:61,xtend:149}],140:[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();++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,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},{}],144:[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(;++index=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/":229}],153:[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,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":173,_process:206,assert:152,events:169,fs:155,os:204,"safe-json-stringify":222,stream:223,util:229}],158:[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":173}],159:[function(require,module,exports){arguments[4][9][0].apply(exports,arguments)},{"abstract-leveldown":164,dup:9,util:229}],160:[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":173,"./deferred-iterator":159,_process:206,"abstract-leveldown":164,util:229}],161:[function(require,module,exports){arguments[4][11][0].apply(exports,arguments)},{_process:206,dup:11}],162:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{_process:206,dup:12}],163:[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;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)}},{}],170:[function(require,module,exports){arguments[4][34][0].apply(exports,arguments)},{dup:34}],171:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN: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}},{}],172:[function(require,module,exports){arguments[4][35][0].apply(exports,arguments)},{dup:35}],173:[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)}},{}],174:[function(require,module,exports){arguments[4][36][0].apply(exports,arguments)},{dup:36}],175:[function(require,module,exports){arguments[4][37][0].apply(exports,arguments)},{buffer:156,dup:37}],176:[function(require,module,exports){arguments[4][39][0].apply(exports,arguments)},{"./lib/encodings":177,dup:39}],177:[function(require,module,exports){arguments[4][40][0].apply(exports,arguments)},{buffer:156,dup:40}],178:[function(require,module,exports){arguments[4][41][0].apply(exports,arguments)},{dup:41,errno:167}],179:[function(require,module,exports){arguments[4][42][0].apply(exports,arguments)},{dup:42,inherits:172,"level-errors":178,"readable-stream":186,xtend:230}],180:[function(require,module,exports){arguments[4][43][0].apply(exports,arguments)},{dup:43}],181:[function(require,module,exports){arguments[4][44][0].apply(exports,arguments)},{"./_stream_readable":183, -"./_stream_writable":185,_process:206,"core-util-is":158,dup:44,inherits:172}],182:[function(require,module,exports){arguments[4][45][0].apply(exports,arguments)},{"./_stream_transform":184,"core-util-is":158,dup:45,inherits:172}],183:[function(require,module,exports){arguments[4][46][0].apply(exports,arguments)},{"./_stream_duplex":181,_process:206,buffer:156,"core-util-is":158,dup:46,events:169,inherits:172,isarray:180,stream:223,"string_decoder/":187,util:154}],184:[function(require,module,exports){arguments[4][47][0].apply(exports,arguments)},{"./_stream_duplex":181,"core-util-is":158,dup:47,inherits:172}],185:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{"./_stream_duplex":181,_process:206,buffer:156,"core-util-is":158,dup:48,inherits:172,stream:223}],186:[function(require,module,exports){arguments[4][49][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":181,"./lib/_stream_passthrough.js":182,"./lib/_stream_readable.js":183,"./lib/_stream_transform.js":184,"./lib/_stream_writable.js":185,_process:206,dup:49,stream:223}],187:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{buffer:156,dup:50}],188:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{"./iterator":189,"abstract-leveldown":192,buffer:156,dup:51,"idb-wrapper":170,isbuffer:175,"typedarray-to-buffer":225,util:229,xtend:199}],189:[function(require,module,exports){arguments[4][52][0].apply(exports,arguments)},{"abstract-leveldown":192,dup:52,ltgt:203,util:229}],190:[function(require,module,exports){arguments[4][53][0].apply(exports,arguments)},{_process:206,dup:53}],191:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{_process:206,dup:12}],192:[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;ib?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":173}],204:[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"},{}],205:[function(require,module,exports){arguments[4][69][0].apply(exports,arguments)},{_process:206,dup:69}],206:[function(require,module,exports){function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex1)for(var i=1;i0?("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":209,"./internal/streams/destroy":215,"./internal/streams/stream":216,_process:206,"core-util-is":158,inherits:172,"process-nextick-args":205,"safe-buffer":221,"util-deprecate":226}],214:[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":221}],215:[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":205}],216:[function(require,module,exports){arguments[4][80][0].apply(exports,arguments)},{dup:80,events:169}],217:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":218}],218:[function(require,module,exports){arguments[4][81][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":209,"./lib/_stream_passthrough.js":210,"./lib/_stream_readable.js":211,"./lib/_stream_transform.js":212,"./lib/_stream_writable.js":213,dup:81}],219:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":218}],220:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":213}],221:[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:156}],222:[function(require,module,exports){arguments[4][83][0].apply(exports,arguments)},{dup:83}],223:[function(require,module,exports){function Stream(){EE.call(this)}module.exports=Stream;var EE=require("events").EventEmitter;require("inherits")(Stream,EE),Stream.Readable=require("readable-stream/readable.js"),Stream.Writable=require("readable-stream/writable.js"),Stream.Duplex=require("readable-stream/duplex.js"),Stream.Transform=require("readable-stream/transform.js"),Stream.PassThrough=require("readable-stream/passthrough.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}var source=this;source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:169,inherits:172,"readable-stream/duplex.js":208,"readable-stream/passthrough.js":217,"readable-stream/readable.js":218,"readable-stream/transform.js":219,"readable-stream/writable.js":220}],224:[function(require,module,exports){arguments[4][85][0].apply(exports,arguments)},{dup:85,"safe-buffer":221}],225:[function(require,module,exports){arguments[4][89][0].apply(exports,arguments)},{buffer:156,dup:89}],226:[function(require,module,exports){arguments[4][90][0].apply(exports,arguments)},{dup:90}],227:[function(require,module,exports){arguments[4][35][0].apply(exports,arguments)},{dup:35}],228:[function(require,module,exports){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],229:[function(require,module,exports){(function(process,global){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){base=" [Function"+(value.name?": "+value.name:"")+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;return output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];i-1&&(err.message="Invalid JSON ("+err.message+")"),stream.emit("error",err)},stream},exports.stringify=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="[\n",sep="\n,\n",cl="\n]\n");var stream,first=!0,anyData=!1;return stream=through(function(data){anyData=!0;try{var json=JSON.stringify(data,null,indent)}catch(err){return stream.emit("error",err)}first?(first=!1,stream.queue(op+json)):stream.queue(sep+json)},function(data){anyData||stream.queue(op),stream.queue(cl),stream.queue(null)})},exports.stringifyObject=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="{\n",sep="\n,\n",cl="\n}\n");var first=!0,anyData=!1;return through(function(data){anyData=!0;var json=JSON.stringify(data[0])+":"+JSON.stringify(data[1],null,indent);first?(first=!1,this.queue(op+json)):this.queue(sep+json)},function(data){anyData||this.queue(op),this.queue(cl),this.queue(null)})},module.parent||"browser"===process.title||process.stdin.pipe(exports.parse(process.argv[2])).pipe(exports.stringify("[",",\n","]\n",2)).pipe(process.stdout)}).call(this,require("_process"),require("buffer").Buffer)},{_process:85,buffer:9,jsonparse:45,through:152}],4:[function(require,module,exports){(function(global){"use strict";function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);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="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/":157}],5:[function(require,module,exports){(function(process,global){!function(global,factory){factory("object"==typeof exports&&void 0!==module?exports: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)<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,1),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){var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(function(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)},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,setImmediate$1=wrap(_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback),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,nativeObjectToString$1=Object.prototype.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,Buffer=freeModule&&freeModule.exports===freeExports?root.Buffer:void 0,isBuffer=(Buffer?Buffer.isBuffer:void 0)||function(){return!1},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,freeProcess=freeModule$1&&freeModule$1.exports===freeExports$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):function(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]},hasOwnProperty$1=Object.prototype.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),hasOwnProperty$3=Object.prototype.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 numTasks=keys(tasks).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 counter=0;readyToCheck.length;)counter++,arrayEach(getDependents(readyToCheck.pop()),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])?",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*"),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 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;i0?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},exports.fromByteArray=function(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,output="",parts=[],i=0,len2=len-extraBytes;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("")};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 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:128==(192&(secondByte=buf[i+1]))&&(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,"")).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=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},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){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;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.12",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:85,assert:4,events:37,fs:8,os:83,"safe-json-stringify":103,stream:147,util:157}],11:[function(require,module,exports){(function(Buffer){function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=function(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)},exports.isBoolean=function(arg){return"boolean"==typeof arg},exports.isNull=function(arg){return null===arg},exports.isNullOrUndefined=function(arg){return null==arg},exports.isNumber=function(arg){return"number"==typeof arg},exports.isString=function(arg){return"string"==typeof arg},exports.isSymbol=function(arg){return"symbol"==typeof arg},exports.isUndefined=function(arg){return void 0===arg},exports.isRegExp=function(re){return"[object RegExp]"===objectToString(re)},exports.isObject=function(arg){return"object"==typeof arg&&null!==arg},exports.isDate=function(d){return"[object Date]"===objectToString(d)},exports.isError=function(e){return"[object Error]"===objectToString(e)||e instanceof Error},exports.isFunction=function(arg){return"function"==typeof arg},exports.isPrimitive=function(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg},exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":42}],12:[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":17,util:157}],13:[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":12,_process:85,"abstract-leveldown":17,util:157}],14:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._serializeKey=function(key){return this._db._serializeKey(key)},AbstractChainedBatch.prototype._serializeValue=function(value){return this._db._serializeValue(value)},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 key=this._serializeKey(key),value=this._serializeValue(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 key=this._serializeKey(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,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:85}],16:[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"))?callback(err):(key=this._serializeKey(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"))?callback(err):(key=this._serializeKey(key),value=this._serializeValue(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"))?callback(err):(key=this._serializeKey(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:147,util:157}],32:[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)writable&&writable.destroy&&writable.destroy();else if(null!==writable&&!1!==writable){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()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=function(){self._writable.removeListener("drain",ondrain),unend()},this.uncork()}else this.end()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)readable&&readable.destroy&&readable.destroy();else{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)};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=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()},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:85,buffer:9,"end-of-stream":33,inherits:40,"readable-stream":99,"stream-shift":148}],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:82}],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),len=(listeners=handler.slice()).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";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)this.onStoreReady();else if(this.db=event.target.result,"string"!=typeof this.db.version)if(this.db.objectStoreNames.contains(this.storeName)){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()}else this.onError(new Error("Object store couldn't be created."));else this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."))}.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&&(onError=onSuccess=options,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;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=function(err){batchTransaction.abort(),called||(called=!0,onError(err))}},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 getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=function(err){called=!0,result=err,onError(err),batchTransaction.abort()}},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))*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:147}],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){var Buffer=require("buffer").Buffer;module.exports=function(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}},{buffer:9}],45:[function(require,module,exports){(function(Buffer){function Parser(){this.tState=START,this.value=void 0,this.string=void 0,this.stringBuffer=Buffer.alloc?Buffer.alloc(STRING_BUFFER_SIZE):new Buffer(STRING_BUFFER_SIZE),this.stringBufferOffset=0,this.unicode=void 0,this.highSurrogate=void 0,this.key=void 0,this.mode=void 0,this.stack=[],this.state=VALUE,this.bytes_remaining=0,this.bytes_in_sequence=0,this.temp_buffs={2:new Buffer(2),3:new Buffer(3),4:new Buffer(4)},this.offset=-1}var C={},LEFT_BRACE=C.LEFT_BRACE=1,RIGHT_BRACE=C.RIGHT_BRACE=2,LEFT_BRACKET=C.LEFT_BRACKET=3,RIGHT_BRACKET=C.RIGHT_BRACKET=4,COLON=C.COLON=5,COMMA=C.COMMA=6,TRUE=C.TRUE=7,FALSE=C.FALSE=8,NULL=C.NULL=9,STRING=C.STRING=10,NUMBER=C.NUMBER=11,START=C.START=17,STOP=C.STOP=18,TRUE1=C.TRUE1=33,TRUE2=C.TRUE2=34,TRUE3=C.TRUE3=35,FALSE1=C.FALSE1=49,FALSE2=C.FALSE2=50,FALSE3=C.FALSE3=51,FALSE4=C.FALSE4=52,NULL1=C.NULL1=65,NULL2=C.NULL2=66,NULL3=C.NULL3=67,NUMBER1=C.NUMBER1=81,NUMBER3=C.NUMBER3=83,STRING1=C.STRING1=97,STRING2=C.STRING2=98,STRING3=C.STRING3=99,STRING4=C.STRING4=100,STRING5=C.STRING5=101,STRING6=C.STRING6=102,VALUE=C.VALUE=113,KEY=C.KEY=114,OBJECT=C.OBJECT=129,ARRAY=C.ARRAY=130,BACK_SLASH="\\".charCodeAt(0),FORWARD_SLASH="/".charCodeAt(0),BACKSPACE="\b".charCodeAt(0),FORM_FEED="\f".charCodeAt(0),NEWLINE="\n".charCodeAt(0),CARRIAGE_RETURN="\r".charCodeAt(0),TAB="\t".charCodeAt(0),STRING_BUFFER_SIZE=65536;Parser.toknam=function(code){for(var keys=Object.keys(C),i=0,l=keys.length;i=STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8"),this.stringBufferOffset=0),this.stringBuffer[this.stringBufferOffset++]=char},proto.appendStringBuf=function(buf,start,end){var size=buf.length;"number"==typeof start&&(size="number"==typeof end?end<0?buf.length-start+end:end-start:buf.length-start),size<0&&(size=0),this.stringBufferOffset+size>STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0),buf.copy(this.stringBuffer,this.stringBufferOffset,start,end),this.stringBufferOffset+=size},proto.write=function(buffer){"string"==typeof buffer&&(buffer=new Buffer(buffer));for(var n,i=0,l=buffer.length;i=48&&n<64)this.string=String.fromCharCode(n),this.tState=NUMBER3;else if(32!==n&&9!==n&&10!==n&&13!==n)return this.charError(buffer,i)}else if(this.tState===STRING1)if(n=buffer[i],this.bytes_remaining>0){for(var j=0;j=128){if(n<=193||n>244)return this.onError(new Error("Invalid UTF-8 character at position "+i+" in state "+Parser.toknam(this.tState)));if(n>=194&&n<=223&&(this.bytes_in_sequence=2),n>=224&&n<=239&&(this.bytes_in_sequence=3),n>=240&&n<=244&&(this.bytes_in_sequence=4),this.bytes_in_sequence+i>buffer.length){for(var k=0;k<=buffer.length-1-i;k++)this.temp_buffs[this.bytes_in_sequence][k]=buffer[i+k];this.bytes_remaining=i+this.bytes_in_sequence-buffer.length,i=buffer.length-1}else this.appendStringBuf(buffer,i,i+this.bytes_in_sequence),i=i+this.bytes_in_sequence-1}else if(34===n)this.tState=START,this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0,this.onToken(STRING,this.string),this.offset+=Buffer.byteLength(this.string,"utf8")+1,this.string=void 0;else if(92===n)this.tState=STRING2;else{if(!(n>=32))return this.charError(buffer,i);this.appendStringChar(n)}else if(this.tState===STRING2)if(34===(n=buffer[i]))this.appendStringChar(n),this.tState=STRING1;else if(92===n)this.appendStringChar(BACK_SLASH),this.tState=STRING1;else if(47===n)this.appendStringChar(FORWARD_SLASH),this.tState=STRING1;else if(98===n)this.appendStringChar(BACKSPACE),this.tState=STRING1;else if(102===n)this.appendStringChar(FORM_FEED),this.tState=STRING1;else if(110===n)this.appendStringChar(NEWLINE),this.tState=STRING1;else if(114===n)this.appendStringChar(CARRIAGE_RETURN),this.tState=STRING1;else if(116===n)this.appendStringChar(TAB),this.tState=STRING1;else{if(117!==n)return this.charError(buffer,i);this.unicode="",this.tState=STRING3}else if(this.tState===STRING3||this.tState===STRING4||this.tState===STRING5||this.tState===STRING6){if(!((n=buffer[i])>=48&&n<64||n>64&&n<=70||n>96&&n<=102))return this.charError(buffer,i);if(this.unicode+=String.fromCharCode(n),this.tState++===STRING6){var intVal=parseInt(this.unicode,16);this.unicode=void 0,void 0!==this.highSurrogate&&intVal>=56320&&intVal<57344?(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate,intVal))),this.highSurrogate=void 0):void 0===this.highSurrogate&&intVal>=55296&&intVal<56320?this.highSurrogate=intVal:(void 0!==this.highSurrogate&&(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.appendStringBuf(new Buffer(String.fromCharCode(intVal)))),this.tState=STRING1}}else if(this.tState===NUMBER1||this.tState===NUMBER3)switch(n=buffer[i]){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 46:case 101:case 69:case 43:case 45:this.string+=String.fromCharCode(n),this.tState=NUMBER3;break;default:this.tState=START;var result=Number(this.string);if(isNaN(result))return this.charError(buffer,i);this.string.match(/[0-9]+/)==this.string&&result.toString()!=this.string?this.onToken(STRING,this.string):this.onToken(NUMBER,result),this.offset+=this.string.length-1,this.string=void 0,i--}else if(this.tState===TRUE1){if(114!==buffer[i])return this.charError(buffer,i);this.tState=TRUE2}else if(this.tState===TRUE2){if(117!==buffer[i])return this.charError(buffer,i);this.tState=TRUE3}else if(this.tState===TRUE3){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(TRUE,!0),this.offset+=3}else if(this.tState===FALSE1){if(97!==buffer[i])return this.charError(buffer,i);this.tState=FALSE2}else if(this.tState===FALSE2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=FALSE3}else if(this.tState===FALSE3){if(115!==buffer[i])return this.charError(buffer,i);this.tState=FALSE4}else if(this.tState===FALSE4){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(FALSE,!1),this.offset+=4}else if(this.tState===NULL1){if(117!==buffer[i])return this.charError(buffer,i);this.tState=NULL2}else if(this.tState===NULL2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=NULL3}else if(this.tState===NULL3){if(108!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(NULL,null),this.offset+=3}},proto.onToken=function(token,value){},proto.parseError=function(token,value){this.tState=STOP,this.onError(new Error("Unexpected "+Parser.toknam(token)+(value?"("+JSON.stringify(value)+")":"")+" in state "+Parser.toknam(this.state)))},proto.push=function(){this.stack.push({value:this.value,key:this.key,mode:this.mode})},proto.pop=function(){var value=this.value,parent=this.stack.pop();this.value=parent.value,this.key=parent.key,this.mode=parent.mode,this.emit(value),this.mode||(this.state=VALUE)},proto.emit=function(value){this.mode&&(this.state=COMMA),this.onValue(value)},proto.onValue=function(value){},proto.onToken=function(token,value){if(this.state===VALUE)if(token===STRING||token===NUMBER||token===TRUE||token===FALSE||token===NULL)this.value&&(this.value[this.key]=value),this.emit(value);else if(token===LEFT_BRACE)this.push(),this.value?this.value=this.value[this.key]={}:this.value={},this.key=void 0,this.state=KEY,this.mode=OBJECT;else if(token===LEFT_BRACKET)this.push(),this.value?this.value=this.value[this.key]=[]:this.value=[],this.key=0,this.mode=ARRAY,this.state=VALUE;else if(token===RIGHT_BRACE){if(this.mode!==OBJECT)return this.parseError(token,value);this.pop()}else{if(token!==RIGHT_BRACKET)return this.parseError(token,value);if(this.mode!==ARRAY)return this.parseError(token,value);this.pop()}else if(this.state===KEY)if(token===STRING)this.key=value,this.state=COLON;else{if(token!==RIGHT_BRACE)return this.parseError(token,value);this.pop()}else if(this.state===COLON){if(token!==COLON)return this.parseError(token,value);this.state=VALUE}else{if(this.state!==COMMA)return this.parseError(token,value);if(token===COMMA)this.mode===ARRAY?(this.key++,this.state=VALUE):this.mode===OBJECT&&(this.state=KEY);else{if(!(token===RIGHT_BRACKET&&this.mode===ARRAY||token===RIGHT_BRACE&&this.mode===OBJECT))return this.parseError(token,value);this.pop()}}},Parser.C=C,module.exports=Parser}).call(this,require("buffer").Buffer)},{buffer:9}],46:[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":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:function(data){return"string"==typeof data?data:String(data)},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.none={encode:identity,decode:identity,buffer:!1,type:"id"},exports.id=exports.none,["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:9}],48:[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}],49:[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":48,"readable-stream":56,xtend:159}],50:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],51:[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){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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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);end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived);var end=(charStr+=buffer.toString(this.encoding,0,end)).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:9}],58:[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":62,ltgt:80,util:157}],60:[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:85}],61:[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:85}],62:[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}},{}],67:[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":64,"./isArguments":66}],68:[function(require,module,exports){module.exports=function(source){return null!==source&&("object"==typeof source||"function"==typeof source)}},{}],69:[function(require,module,exports){var Keys=require("object-keys"),hasKeys=require("./has-keys");module.exports=function(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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=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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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);++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)}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=function(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0},Hash.prototype.delete=function(key){var result=this.has(key)&&delete this.__data__[key];return this.size-=result?1:0,result},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[],this.size=0},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),--this.size,0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this},MapCache.prototype.clear=function(){this.size=0,this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){var result=getMapData(this,key).delete(key);return this.size-=result?1:0,result},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)},Stack.prototype.clear=function(){this.__data__=new ListCache,this.size=0},Stack.prototype.delete=function(key){var data=this.__data__,result=data.delete(key);return this.size=data.size,result},Stack.prototype.get=function(key){return this.__data__.get(key)},Stack.prototype.has=function(key){return this.__data__.has(key)},Stack.prototype.set=function(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),(end=end>length?length: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 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){return value?(value=toNumber(value))===INFINITY||value===-INFINITY?(value<0?-1:1)*MAX_INTEGER:value===value?value:0:0===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,objectToString=Object.prototype.toString,nativeMax=Math.max;module.exports=function(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)})}},{}],78:[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;++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}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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){},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=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},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){};module.exports=function(array){return array&&array.length?baseUniq(array):[]}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],80:[function(require,module,exports){(function(Buffer){function has(obj,key){return Object.hasOwnProperty.call(obj,key)}function isDef(val){return void 0!==val&&""!==val}function has(range,name){return Object.hasOwnProperty.call(range,name)}function hasKey(range,name){return Object.hasOwnProperty.call(range,name)&&name}function id(e){return e}exports.compare=function(a,b){if(Buffer.isBuffer(a)){for(var l=Math.min(a.length,b.length),i=0;ib?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)&&((cmp=compare(key,lb))<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}],81:[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)}}},{}],82:[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:158}],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,exports){(function(process){"use strict";!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?module.exports=function(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)}},{"end-of-stream":33,fs:7,once:82}],88:[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:32,inherits:40,pump:87}],89:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":90}],90:[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||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(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)?(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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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,OurUint8Array=global.Uint8Array||function(){},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"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./_stream_duplex":90,"./internal/streams/destroy":96,"./internal/streams/stream":97,_process:85,"core-util-is":11,inherits:40,"process-nextick-args":84,"safe-buffer":102,"util-deprecate":154}],95:[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":102}],96:[function(require,module,exports){"use strict";function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;readableDestroyed||writableDestroyed?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)}))},undestroy:function(){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)}}},{"process-nextick-args":84}],97:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:37}],98:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":99}],99:[function(require,module,exports){(exports=module.exports=require("./lib/_stream_readable.js")).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}],100:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":99}],101:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":94}],102:[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:9}],103:[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},{}],104:[function(require,module,exports){const bunyan=require("bunyan"),levelup=require("levelup"),API=require("./lib/API.js");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){const api=API(options),Indexer={};return Indexer.options=options,Indexer.add=api.add,Indexer.concurrentAdd=api.concurrentAdd,Indexer.concurrentDel=api.concurrentDel,Indexer.close=api.close,Indexer.dbWriteStream=api.dbWriteStream,Indexer.defaultPipeline=api.defaultPipeline,Indexer.deleteStream=api.deleteStream,Indexer.deleter=api.deleter,Indexer.feed=api.feed,Indexer.flush=api.flush,callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{appendOnly:!1,deletable:!0,batchSize:1e3,compositeField:!0,fastSort:!0,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,storeDocument:!0,storeVector:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0,wildcard:!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/API.js":105,bunyan:10,leveldown:58,levelup:71}],105:[function(require,module,exports){const DBEntries=require("./delete.js").DBEntries,DBWriteCleanStream=require("./replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./replicate.js").DBWriteMergeStream,DocVector=require("./delete.js").DocVector,JSONStream=require("JSONStream"),Readable=require("stream").Readable,RecalibrateDB=require("./delete.js").RecalibrateDB,IndexBatch=require("./add.js").IndexBatch,async=require("async"),del=require("./delete.js"),docProc=require("docproc"),pumpify=require("pumpify");module.exports=function(options){const 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),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={};return Indexer.add=function(ops){const thisOps=Object.assign(options,ops);return pumpify.obj(new IndexBatch(deleter,thisOps),new DBWriteMergeStream(thisOps))},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)).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=deleter,Indexer.feed=function(ops){return ops&&ops.objectMode?pumpify.obj(Indexer.defaultPipeline(ops),Indexer.add(ops)):pumpify(JSONStream.parse(),Indexer.defaultPipeline(ops),Indexer.add(ops))},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},Indexer}},{"./add.js":106,"./delete.js":107,"./replicate.js":108,JSONStream:3,async:5,docproc:19,pumpify:88,stream:147}],106:[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={}},noop=function(_,cb){cb()},IndexBatch=function(deleter,options){this.batchSize=options.batchSize||1e3,this.deleter=deleter,this.fastSort=options.fastSort,this.appendOnly=options.appendOnly,this.keySeparator=options.keySeparator||"○",this.log=options.log,this.storeDocument=options.storeDocument,this.storeVector=options.storeVector,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.keySeparator,that=this;(this.appendOnly?noop:this.deleter.bind(this.indexer))([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.log.info("processing doc "+ingestedDoc.id),!0===that.storeDocument&&(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]){if(that.fastSort){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id])}var dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.storeVector&&(that.deltaIndex["DOCUMENT-VECTOR"+sep+fieldName+sep+ingestedDoc.id+sep]=ingestedDoc.vector[fieldName])}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.batchSize&&(that.push({totalKeys:totalKeys}),that.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:147,util:157}],107:[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,docKey="DOCUMENT"+sep+docId+sep;this.options.indexes.get(docKey,function(err,val){if(err)return end();var docFields=Object.keys(val);docFields.push("*"),docFields=docFields.map(function(item){return"DOCUMENT-VECTOR"+sep+item+sep+docId+sep});var i=0,pushValue=function(key){if(void 0===key)return that.push({key:"DOCUMENT"+sep+docId+sep,lastPass:!0}),end();that.options.indexes.get(key,function(err,val){err||that.push({key:key,value:val}),pushValue(docFields[i++])})};pushValue(docFields[0])})};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){if(!0===vector.lastPass)return this.push({key:vector.key}),end();const sep=this.options.keySeparator;var that=this,field=vector.key.split(sep)[1],docId=vector.key.split(sep)[2],vectorKeys=Object.keys(vector.value),i=0,pushRecalibrationvalues=function(vec){if(that.push({key:"TF"+sep+field+sep+vectorKeys[i],value:docId}),that.push({key:"DF"+sep+field+sep+vectorKeys[i],value:docId}),++i===vectorKeys.length)return that.push({key:vector.key}),end();pushRecalibrationvalues(vector[vectorKeys[i]])};pushRecalibrationvalues(vector[vectorKeys[0]])};const RecalibrateDB=function(options){this.options=options,this.batch=[],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={};return 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",that.batch.push(dbInstruction),end()):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",that.batch.push(dbInstruction),end()):dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep?(dbInstruction.type="del",that.batch.push(dbInstruction),end()):void(dbEntry.key.substring(0,9)==="DOCUMENT"+sep&&(dbInstruction.type="del",that.batch.push(dbInstruction),that.options.indexes.batch(that.batch,function(err){return that.batch=[],end()})))})}},{stream:147,util:157}],108:[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:147,util:157}],109:[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,MergeOrConditionsTFIDF=require("./lib/MergeOrConditionsTFIDF.js").MergeOrConditionsTFIDF,MergeOrConditionsFieldSort=require("./lib/MergeOrConditionsFieldSort.js").MergeOrConditionsFieldSort,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),sw=require("stopword"),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 ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditionsFieldSort(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 MergeOrConditionsTFIDF(q.offset,q.pageSize)).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:sw.en},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":110,"./lib/CalculateBuckets.js":111,"./lib/CalculateCategories.js":112,"./lib/CalculateEntireResultSet.js":113,"./lib/CalculateResultSetPerClause.js":114,"./lib/CalculateTopScoringDocs.js":115,"./lib/CalculateTotalHits.js":116,"./lib/Classify.js":117,"./lib/FetchDocsFromDB.js":118,"./lib/FetchStoredDoc.js":119,"./lib/GetIntersectionStream.js":120,"./lib/MergeOrConditionsFieldSort.js":121,"./lib/MergeOrConditionsTFIDF.js":122,"./lib/ScoreDocsOnField.js":123,"./lib/ScoreTopScoringDocsTFIDF.js":124,"./lib/matcher.js":125,"./lib/siUtil.js":126,bunyan:10,levelup:71,stopword:127,stream:147}],110:[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:147,util:157}],111:[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":74,"lodash.uniq":79,stream:147,util:157}],112:[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":74,stream:147,util:157}],113:[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":78,stream:147,util:157}],114:[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){var include=_spread(_intersection)(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,documentFrequencies:frequencies,WEIGHT:queryClause.WEIGHT||1}),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;i({id:id,scoringCriteria:resultMap[id],score:resultMap[id][0].score})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:"asc"===that.sortDirection?b.scorea.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:147,util:157}],122:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),MergeOrConditionsTFIDF=function(offset,pageSize){this.resultSet=[],this.offset=offset,this.pageSize=pageSize,Transform.call(this,{objectMode:!0})};exports.MergeOrConditionsTFIDF=MergeOrConditionsTFIDF,util.inherits(MergeOrConditionsTFIDF,Transform),MergeOrConditionsTFIDF.prototype._transform=function(doc,encoding,end){return this.resultSet=this.resultSet.concat(doc.matches),end()},MergeOrConditionsTFIDF.prototype._flush=function(end){var that=this,resultMap=getResultMap(this.resultSet);return Object.keys(resultMap).map(id=>({id:id,scoringCriteria:resultMap[id],score:resultMap[id].reduce((sum,matches)=>sum+matches.score,0)/resultMap[id].length})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:b.score-a.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:147,util:157}],123:[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,sortDirection=this.sort.direction||"asc";var tally=0,rangeOptions={gte:"DF"+sep+this.sort.field+sep,lte:"DF"+sep+this.sort.field+sep+sep};"desc"===sortDirection&&(rangeOptions.reverse=!0),clauseSet.topScoringDocs=[],that.options.indexes.createReadStream(rangeOptions).on("data",function(data){var token=data.key.split(sep)[2];"*"!==token&&("desc"===sortDirection&&(data.value=data.value.reverse()),data.value.some(id=>{if(-1!==_sortedIndexOf(clauseSet.set,id)&&(clauseSet.topScoringDocs.push({id:id,score:token}),++tally===that.seekLimit))return!0}))}).on("end",function(){return that.push(clauseSet),end()})}},{"lodash.sortedindexof":76,stream:147,util:157}],124:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),ScoreTopScoringDocsTFIDF=function(options,offset,pageSize){this.options=options,Transform.call(this,{objectMode:!0})};exports.ScoreTopScoringDocsTFIDF=ScoreTopScoringDocsTFIDF,util.inherits(ScoreTopScoringDocsTFIDF,Transform),ScoreTopScoringDocsTFIDF.prototype._transform=function(clause,encoding,end){var that=this,promises=[];clause.topScoringDocs.forEach(doc=>{var docID=doc[1];promises.push(getMatchesForDoc(docID,that.options,clause))}),Promise.all(promises).then(res=>(clause.matches=res,that.push(clause),end()),err=>{console.log(err)})};const getMatchesForDoc=(docID,options,clause)=>new Promise((resolve,reject)=>{var termVectors=clause.documentFrequencies.map(freq=>gett(freq.field,docID,freq.gte,freq.lte,freq.df,clause.WEIGHT,options));Promise.all(termVectors).then(matchedTerms=>{var matches=[].concat.apply([],matchedTerms);resolve({id:docID,matches:matches,score:getScore(matches)})},err=>{console.log(err)})}),getScore=matchedTerms=>matchedTerms.reduce(function(sum,match){return sum+match.score},0)/matchedTerms.length,gett=(field,key,gte,lte,df,weight,options)=>{var s=options.keySeparator;return new Promise((resolve,reject)=>{options.indexes.get("DOCUMENT-VECTOR"+s+field+s+key+s,(err,value)=>{if(err)return reject(err);var matchedTermsWithMagnitude=[];return Object.keys(value).filter(t=>{if(t>=gte&&t<=lte)return!0}).forEach(t=>{var tf=value[t],tfidf=tf*Math.log10(1+1/df),term={field:field,term:t,tf:tf,df:df,tfidf:tfidf,weight:weight,score:tfidf*weight};matchedTermsWithMagnitude.push(term)}),resolve(matchedTermsWithMagnitude)})})}},{stream:147,util:157}],125:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatchMostFrequent=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchMostFrequent,Transform),MatchMostFrequent.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){var frequencySort=b.value.length-a.value.length;return 0===frequencySort?b.keya.key?-1:0:frequencySort}).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()})};const MatchAlphabetical=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchAlphabetical,Transform),MatchAlphabetical.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var space={start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep},i=0,rs=this.options.indexes.createReadStream(space);rs.on("data",function(data){var m={};switch(q.type){case"ID":m={token:data.key.split(sep)[2],documents:data.value};break;case"count":m={token:data.key.split(sep)[2],documentCount:data.value.length};break;default:m=data.key.split(sep)[2]}if(that.push(m),++i===q.limit)return rs.destroy(),end()}),rs.on("error",function(err){that.options.log.error("Oh my!",err)}),rs.on("end",function(){return end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return(q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple",sort:"frequency"},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 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(1===(ngrams=ngrams.sort()).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:"")+"]"),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)).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 isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==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 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