UNPKG

703 kBJavaScriptView Raw
1// PouchDB localStorage plugin 8.0.0
2// Based on localstorage-down: https://github.com/No9/localstorage-down
3//
4// (c) 2012-2022 Dale Harvey and the PouchDB team
5// PouchDB may be freely distributed under the Apache license, version 2.0.
6// For all details and documentation:
7// http://pouchdb.com
8(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
9(function (process){(function (){
10/* Copyright (c) 2013 Rod Vagg, MIT License */
11
12function AbstractChainedBatch (db) {
13 this._db = db
14 this._operations = []
15 this._written = false
16}
17
18AbstractChainedBatch.prototype._checkWritten = function () {
19 if (this._written)
20 throw new Error('write() already called on this batch')
21}
22
23AbstractChainedBatch.prototype.put = function (key, value) {
24 this._checkWritten()
25
26 var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
27 if (err) throw err
28 err = this._db._checkKeyValue(value, 'value', this._db._isBuffer)
29 if (err) throw err
30
31 if (!this._db._isBuffer(key)) key = String(key)
32 if (!this._db._isBuffer(value)) value = String(value)
33
34 if (typeof this._put == 'function' )
35 this._put(key, value)
36 else
37 this._operations.push({ type: 'put', key: key, value: value })
38
39 return this
40}
41
42AbstractChainedBatch.prototype.del = function (key) {
43 this._checkWritten()
44
45 var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
46 if (err) throw err
47
48 if (!this._db._isBuffer(key)) key = String(key)
49
50 if (typeof this._del == 'function' )
51 this._del(key)
52 else
53 this._operations.push({ type: 'del', key: key })
54
55 return this
56}
57
58AbstractChainedBatch.prototype.clear = function () {
59 this._checkWritten()
60
61 this._operations = []
62
63 if (typeof this._clear == 'function' )
64 this._clear()
65
66 return this
67}
68
69AbstractChainedBatch.prototype.write = function (options, callback) {
70 this._checkWritten()
71
72 if (typeof options == 'function')
73 callback = options
74 if (typeof callback != 'function')
75 throw new Error('write() requires a callback argument')
76 if (typeof options != 'object')
77 options = {}
78
79 this._written = true
80
81 if (typeof this._write == 'function' )
82 return this._write(callback)
83
84 if (typeof this._db._batch == 'function')
85 return this._db._batch(this._operations, options, callback)
86
87 process.nextTick(callback)
88}
89
90module.exports = AbstractChainedBatch
91}).call(this)}).call(this,_dereq_(73))
92},{"73":73}],2:[function(_dereq_,module,exports){
93(function (process){(function (){
94/* Copyright (c) 2013 Rod Vagg, MIT License */
95
96function AbstractIterator (db) {
97 this.db = db
98 this._ended = false
99 this._nexting = false
100}
101
102AbstractIterator.prototype.next = function (callback) {
103 var self = this
104
105 if (typeof callback != 'function')
106 throw new Error('next() requires a callback argument')
107
108 if (self._ended)
109 return callback(new Error('cannot call next() after end()'))
110 if (self._nexting)
111 return callback(new Error('cannot call next() before previous next() has completed'))
112
113 self._nexting = true
114 if (typeof self._next == 'function') {
115 return self._next(function () {
116 self._nexting = false
117 callback.apply(null, arguments)
118 })
119 }
120
121 process.nextTick(function () {
122 self._nexting = false
123 callback()
124 })
125}
126
127AbstractIterator.prototype.end = function (callback) {
128 if (typeof callback != 'function')
129 throw new Error('end() requires a callback argument')
130
131 if (this._ended)
132 return callback(new Error('end() already called on iterator'))
133
134 this._ended = true
135
136 if (typeof this._end == 'function')
137 return this._end(callback)
138
139 process.nextTick(callback)
140}
141
142module.exports = AbstractIterator
143
144}).call(this)}).call(this,_dereq_(73))
145},{"73":73}],3:[function(_dereq_,module,exports){
146(function (Buffer,process){(function (){
147/* Copyright (c) 2013 Rod Vagg, MIT License */
148
149var xtend = _dereq_(4)
150 , AbstractIterator = _dereq_(2)
151 , AbstractChainedBatch = _dereq_(1)
152
153function AbstractLevelDOWN (location) {
154 if (!arguments.length || location === undefined)
155 throw new Error('constructor requires at least a location argument')
156
157 if (typeof location != 'string')
158 throw new Error('constructor requires a location string argument')
159
160 this.location = location
161}
162
163AbstractLevelDOWN.prototype.open = function (options, callback) {
164 if (typeof options == 'function')
165 callback = options
166
167 if (typeof callback != 'function')
168 throw new Error('open() requires a callback argument')
169
170 if (typeof options != 'object')
171 options = {}
172
173 if (typeof this._open == 'function')
174 return this._open(options, callback)
175
176 process.nextTick(callback)
177}
178
179AbstractLevelDOWN.prototype.close = function (callback) {
180 if (typeof callback != 'function')
181 throw new Error('close() requires a callback argument')
182
183 if (typeof this._close == 'function')
184 return this._close(callback)
185
186 process.nextTick(callback)
187}
188
189AbstractLevelDOWN.prototype.get = function (key, options, callback) {
190 var err
191
192 if (typeof options == 'function')
193 callback = options
194
195 if (typeof callback != 'function')
196 throw new Error('get() requires a callback argument')
197
198 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
199 return callback(err)
200
201 if (!this._isBuffer(key))
202 key = String(key)
203
204 if (typeof options != 'object')
205 options = {}
206
207 if (typeof this._get == 'function')
208 return this._get(key, options, callback)
209
210 process.nextTick(function () { callback(new Error('NotFound')) })
211}
212
213AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
214 var err
215
216 if (typeof options == 'function')
217 callback = options
218
219 if (typeof callback != 'function')
220 throw new Error('put() requires a callback argument')
221
222 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
223 return callback(err)
224
225 if (err = this._checkKeyValue(value, 'value', this._isBuffer))
226 return callback(err)
227
228 if (!this._isBuffer(key))
229 key = String(key)
230
231 // coerce value to string in node, don't touch it in browser
232 // (indexeddb can store any JS type)
233 if (!this._isBuffer(value) && !process.browser)
234 value = String(value)
235
236 if (typeof options != 'object')
237 options = {}
238
239 if (typeof this._put == 'function')
240 return this._put(key, value, options, callback)
241
242 process.nextTick(callback)
243}
244
245AbstractLevelDOWN.prototype.del = function (key, options, callback) {
246 var err
247
248 if (typeof options == 'function')
249 callback = options
250
251 if (typeof callback != 'function')
252 throw new Error('del() requires a callback argument')
253
254 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
255 return callback(err)
256
257 if (!this._isBuffer(key))
258 key = String(key)
259
260 if (typeof options != 'object')
261 options = {}
262
263 if (typeof this._del == 'function')
264 return this._del(key, options, callback)
265
266 process.nextTick(callback)
267}
268
269AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
270 if (!arguments.length)
271 return this._chainedBatch()
272
273 if (typeof options == 'function')
274 callback = options
275
276 if (typeof callback != 'function')
277 throw new Error('batch(array) requires a callback argument')
278
279 if (!Array.isArray(array))
280 return callback(new Error('batch(array) requires an array argument'))
281
282 if (typeof options != 'object')
283 options = {}
284
285 var i = 0
286 , l = array.length
287 , e
288 , err
289
290 for (; i < l; i++) {
291 e = array[i]
292 if (typeof e != 'object')
293 continue
294
295 if (err = this._checkKeyValue(e.type, 'type', this._isBuffer))
296 return callback(err)
297
298 if (err = this._checkKeyValue(e.key, 'key', this._isBuffer))
299 return callback(err)
300
301 if (e.type == 'put') {
302 if (err = this._checkKeyValue(e.value, 'value', this._isBuffer))
303 return callback(err)
304 }
305 }
306
307 if (typeof this._batch == 'function')
308 return this._batch(array, options, callback)
309
310 process.nextTick(callback)
311}
312
313//TODO: remove from here, not a necessary primitive
314AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
315 if ( start == null
316 || end == null
317 || typeof start == 'function'
318 || typeof end == 'function') {
319 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
320 }
321
322 if (typeof callback != 'function')
323 throw new Error('approximateSize() requires a callback argument')
324
325 if (!this._isBuffer(start))
326 start = String(start)
327
328 if (!this._isBuffer(end))
329 end = String(end)
330
331 if (typeof this._approximateSize == 'function')
332 return this._approximateSize(start, end, callback)
333
334 process.nextTick(function () {
335 callback(null, 0)
336 })
337}
338
339AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
340 var self = this
341
342 options = xtend(options)
343
344 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
345 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
346 delete options[o]
347 })
348
349 options.reverse = !!options.reverse
350
351 // fix `start` so it takes into account gt, gte, lt, lte as appropriate
352 if (options.reverse && options.lt)
353 options.start = options.lt
354 if (options.reverse && options.lte)
355 options.start = options.lte
356 if (!options.reverse && options.gt)
357 options.start = options.gt
358 if (!options.reverse && options.gte)
359 options.start = options.gte
360
361 if ((options.reverse && options.lt && !options.lte)
362 || (!options.reverse && options.gt && !options.gte))
363 options.exclusiveStart = true // start should *not* include matching key
364
365 return options
366}
367
368AbstractLevelDOWN.prototype.iterator = function (options) {
369 if (typeof options != 'object')
370 options = {}
371
372 options = this._setupIteratorOptions(options)
373
374 if (typeof this._iterator == 'function')
375 return this._iterator(options)
376
377 return new AbstractIterator(this)
378}
379
380AbstractLevelDOWN.prototype._chainedBatch = function () {
381 return new AbstractChainedBatch(this)
382}
383
384AbstractLevelDOWN.prototype._isBuffer = function (obj) {
385 return Buffer.isBuffer(obj)
386}
387
388AbstractLevelDOWN.prototype._checkKeyValue = function (obj, type) {
389 if (obj === null || obj === undefined)
390 return new Error(type + ' cannot be `null` or `undefined`')
391
392 if (obj === null || obj === undefined)
393 return new Error(type + ' cannot be `null` or `undefined`')
394
395 if (this._isBuffer(obj)) {
396 if (obj.length === 0)
397 return new Error(type + ' cannot be an empty Buffer')
398 } else if (String(obj) === '')
399 return new Error(type + ' cannot be an empty String')
400}
401
402module.exports.AbstractLevelDOWN = AbstractLevelDOWN
403module.exports.AbstractIterator = AbstractIterator
404module.exports.AbstractChainedBatch = AbstractChainedBatch
405
406}).call(this)}).call(this,{"isBuffer":_dereq_(38)},_dereq_(73))
407},{"1":1,"2":2,"38":38,"4":4,"73":73}],4:[function(_dereq_,module,exports){
408module.exports = extend
409
410function extend() {
411 var target = {}
412
413 for (var i = 0; i < arguments.length; i++) {
414 var source = arguments[i]
415
416 for (var key in source) {
417 if (source.hasOwnProperty(key)) {
418 target[key] = source[key]
419 }
420 }
421 }
422
423 return target
424}
425
426},{}],5:[function(_dereq_,module,exports){
427'use strict';
428
429module.exports = argsArray;
430
431function argsArray(fun) {
432 return function () {
433 var len = arguments.length;
434 if (len) {
435 var args = [];
436 var i = -1;
437 while (++i < len) {
438 args[i] = arguments[i];
439 }
440 return fun.call(this, args);
441 } else {
442 return fun.call(this, []);
443 }
444 };
445}
446},{}],6:[function(_dereq_,module,exports){
447(function (global){(function (){
448'use strict';
449
450var objectAssign = _dereq_(71);
451
452// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
453// original notice:
454
455/*!
456 * The buffer module from node.js, for the browser.
457 *
458 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
459 * @license MIT
460 */
461function compare(a, b) {
462 if (a === b) {
463 return 0;
464 }
465
466 var x = a.length;
467 var y = b.length;
468
469 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
470 if (a[i] !== b[i]) {
471 x = a[i];
472 y = b[i];
473 break;
474 }
475 }
476
477 if (x < y) {
478 return -1;
479 }
480 if (y < x) {
481 return 1;
482 }
483 return 0;
484}
485function isBuffer(b) {
486 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
487 return global.Buffer.isBuffer(b);
488 }
489 return !!(b != null && b._isBuffer);
490}
491
492// based on node assert, original notice:
493// NB: The URL to the CommonJS spec is kept just for tradition.
494// node-assert has evolved a lot since then, both in API and behavior.
495
496// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
497//
498// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
499//
500// Originally from narwhal.js (http://narwhaljs.org)
501// Copyright (c) 2009 Thomas Robinson <280north.com>
502//
503// Permission is hereby granted, free of charge, to any person obtaining a copy
504// of this software and associated documentation files (the 'Software'), to
505// deal in the Software without restriction, including without limitation the
506// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
507// sell copies of the Software, and to permit persons to whom the Software is
508// furnished to do so, subject to the following conditions:
509//
510// The above copyright notice and this permission notice shall be included in
511// all copies or substantial portions of the Software.
512//
513// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
514// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
515// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
516// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
517// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
518// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
519
520var util = _dereq_(9);
521var hasOwn = Object.prototype.hasOwnProperty;
522var pSlice = Array.prototype.slice;
523var functionsHaveNames = (function () {
524 return function foo() {}.name === 'foo';
525}());
526function pToString (obj) {
527 return Object.prototype.toString.call(obj);
528}
529function isView(arrbuf) {
530 if (isBuffer(arrbuf)) {
531 return false;
532 }
533 if (typeof global.ArrayBuffer !== 'function') {
534 return false;
535 }
536 if (typeof ArrayBuffer.isView === 'function') {
537 return ArrayBuffer.isView(arrbuf);
538 }
539 if (!arrbuf) {
540 return false;
541 }
542 if (arrbuf instanceof DataView) {
543 return true;
544 }
545 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
546 return true;
547 }
548 return false;
549}
550// 1. The assert module provides functions that throw
551// AssertionError's when particular conditions are not met. The
552// assert module must conform to the following interface.
553
554var assert = module.exports = ok;
555
556// 2. The AssertionError is defined in assert.
557// new assert.AssertionError({ message: message,
558// actual: actual,
559// expected: expected })
560
561var regex = /\s*function\s+([^\(\s]*)\s*/;
562// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
563function getName(func) {
564 if (!util.isFunction(func)) {
565 return;
566 }
567 if (functionsHaveNames) {
568 return func.name;
569 }
570 var str = func.toString();
571 var match = str.match(regex);
572 return match && match[1];
573}
574assert.AssertionError = function AssertionError(options) {
575 this.name = 'AssertionError';
576 this.actual = options.actual;
577 this.expected = options.expected;
578 this.operator = options.operator;
579 if (options.message) {
580 this.message = options.message;
581 this.generatedMessage = false;
582 } else {
583 this.message = getMessage(this);
584 this.generatedMessage = true;
585 }
586 var stackStartFunction = options.stackStartFunction || fail;
587 if (Error.captureStackTrace) {
588 Error.captureStackTrace(this, stackStartFunction);
589 } else {
590 // non v8 browsers so we can have a stacktrace
591 var err = new Error();
592 if (err.stack) {
593 var out = err.stack;
594
595 // try to strip useless frames
596 var fn_name = getName(stackStartFunction);
597 var idx = out.indexOf('\n' + fn_name);
598 if (idx >= 0) {
599 // once we have located the function frame
600 // we need to strip out everything before it (and its line)
601 var next_line = out.indexOf('\n', idx + 1);
602 out = out.substring(next_line + 1);
603 }
604
605 this.stack = out;
606 }
607 }
608};
609
610// assert.AssertionError instanceof Error
611util.inherits(assert.AssertionError, Error);
612
613function truncate(s, n) {
614 if (typeof s === 'string') {
615 return s.length < n ? s : s.slice(0, n);
616 } else {
617 return s;
618 }
619}
620function inspect(something) {
621 if (functionsHaveNames || !util.isFunction(something)) {
622 return util.inspect(something);
623 }
624 var rawname = getName(something);
625 var name = rawname ? ': ' + rawname : '';
626 return '[Function' + name + ']';
627}
628function getMessage(self) {
629 return truncate(inspect(self.actual), 128) + ' ' +
630 self.operator + ' ' +
631 truncate(inspect(self.expected), 128);
632}
633
634// At present only the three keys mentioned above are used and
635// understood by the spec. Implementations or sub modules can pass
636// other keys to the AssertionError's constructor - they will be
637// ignored.
638
639// 3. All of the following functions must throw an AssertionError
640// when a corresponding condition is not met, with a message that
641// may be undefined if not provided. All assertion methods provide
642// both the actual and expected values to the assertion error for
643// display purposes.
644
645function fail(actual, expected, message, operator, stackStartFunction) {
646 throw new assert.AssertionError({
647 message: message,
648 actual: actual,
649 expected: expected,
650 operator: operator,
651 stackStartFunction: stackStartFunction
652 });
653}
654
655// EXTENSION! allows for well behaved errors defined elsewhere.
656assert.fail = fail;
657
658// 4. Pure assertion tests whether a value is truthy, as determined
659// by !!guard.
660// assert.ok(guard, message_opt);
661// This statement is equivalent to assert.equal(true, !!guard,
662// message_opt);. To test strictly for the value true, use
663// assert.strictEqual(true, guard, message_opt);.
664
665function ok(value, message) {
666 if (!value) fail(value, true, message, '==', assert.ok);
667}
668assert.ok = ok;
669
670// 5. The equality assertion tests shallow, coercive equality with
671// ==.
672// assert.equal(actual, expected, message_opt);
673
674assert.equal = function equal(actual, expected, message) {
675 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
676};
677
678// 6. The non-equality assertion tests for whether two objects are not equal
679// with != assert.notEqual(actual, expected, message_opt);
680
681assert.notEqual = function notEqual(actual, expected, message) {
682 if (actual == expected) {
683 fail(actual, expected, message, '!=', assert.notEqual);
684 }
685};
686
687// 7. The equivalence assertion tests a deep equality relation.
688// assert.deepEqual(actual, expected, message_opt);
689
690assert.deepEqual = function deepEqual(actual, expected, message) {
691 if (!_deepEqual(actual, expected, false)) {
692 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
693 }
694};
695
696assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
697 if (!_deepEqual(actual, expected, true)) {
698 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
699 }
700};
701
702function _deepEqual(actual, expected, strict, memos) {
703 // 7.1. All identical values are equivalent, as determined by ===.
704 if (actual === expected) {
705 return true;
706 } else if (isBuffer(actual) && isBuffer(expected)) {
707 return compare(actual, expected) === 0;
708
709 // 7.2. If the expected value is a Date object, the actual value is
710 // equivalent if it is also a Date object that refers to the same time.
711 } else if (util.isDate(actual) && util.isDate(expected)) {
712 return actual.getTime() === expected.getTime();
713
714 // 7.3 If the expected value is a RegExp object, the actual value is
715 // equivalent if it is also a RegExp object with the same source and
716 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
717 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
718 return actual.source === expected.source &&
719 actual.global === expected.global &&
720 actual.multiline === expected.multiline &&
721 actual.lastIndex === expected.lastIndex &&
722 actual.ignoreCase === expected.ignoreCase;
723
724 // 7.4. Other pairs that do not both pass typeof value == 'object',
725 // equivalence is determined by ==.
726 } else if ((actual === null || typeof actual !== 'object') &&
727 (expected === null || typeof expected !== 'object')) {
728 return strict ? actual === expected : actual == expected;
729
730 // If both values are instances of typed arrays, wrap their underlying
731 // ArrayBuffers in a Buffer each to increase performance
732 // This optimization requires the arrays to have the same type as checked by
733 // Object.prototype.toString (aka pToString). Never perform binary
734 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
735 // bit patterns are not identical.
736 } else if (isView(actual) && isView(expected) &&
737 pToString(actual) === pToString(expected) &&
738 !(actual instanceof Float32Array ||
739 actual instanceof Float64Array)) {
740 return compare(new Uint8Array(actual.buffer),
741 new Uint8Array(expected.buffer)) === 0;
742
743 // 7.5 For all other Object pairs, including Array objects, equivalence is
744 // determined by having the same number of owned properties (as verified
745 // with Object.prototype.hasOwnProperty.call), the same set of keys
746 // (although not necessarily the same order), equivalent values for every
747 // corresponding key, and an identical 'prototype' property. Note: this
748 // accounts for both named and indexed properties on Arrays.
749 } else if (isBuffer(actual) !== isBuffer(expected)) {
750 return false;
751 } else {
752 memos = memos || {actual: [], expected: []};
753
754 var actualIndex = memos.actual.indexOf(actual);
755 if (actualIndex !== -1) {
756 if (actualIndex === memos.expected.indexOf(expected)) {
757 return true;
758 }
759 }
760
761 memos.actual.push(actual);
762 memos.expected.push(expected);
763
764 return objEquiv(actual, expected, strict, memos);
765 }
766}
767
768function isArguments(object) {
769 return Object.prototype.toString.call(object) == '[object Arguments]';
770}
771
772function objEquiv(a, b, strict, actualVisitedObjects) {
773 if (a === null || a === undefined || b === null || b === undefined)
774 return false;
775 // if one is a primitive, the other must be same
776 if (util.isPrimitive(a) || util.isPrimitive(b))
777 return a === b;
778 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
779 return false;
780 var aIsArgs = isArguments(a);
781 var bIsArgs = isArguments(b);
782 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
783 return false;
784 if (aIsArgs) {
785 a = pSlice.call(a);
786 b = pSlice.call(b);
787 return _deepEqual(a, b, strict);
788 }
789 var ka = objectKeys(a);
790 var kb = objectKeys(b);
791 var key, i;
792 // having the same number of owned properties (keys incorporates
793 // hasOwnProperty)
794 if (ka.length !== kb.length)
795 return false;
796 //the same set of keys (although not necessarily the same order),
797 ka.sort();
798 kb.sort();
799 //~~~cheap key test
800 for (i = ka.length - 1; i >= 0; i--) {
801 if (ka[i] !== kb[i])
802 return false;
803 }
804 //equivalent values for every corresponding key, and
805 //~~~possibly expensive deep test
806 for (i = ka.length - 1; i >= 0; i--) {
807 key = ka[i];
808 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
809 return false;
810 }
811 return true;
812}
813
814// 8. The non-equivalence assertion tests for any deep inequality.
815// assert.notDeepEqual(actual, expected, message_opt);
816
817assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
818 if (_deepEqual(actual, expected, false)) {
819 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
820 }
821};
822
823assert.notDeepStrictEqual = notDeepStrictEqual;
824function notDeepStrictEqual(actual, expected, message) {
825 if (_deepEqual(actual, expected, true)) {
826 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
827 }
828}
829
830
831// 9. The strict equality assertion tests strict equality, as determined by ===.
832// assert.strictEqual(actual, expected, message_opt);
833
834assert.strictEqual = function strictEqual(actual, expected, message) {
835 if (actual !== expected) {
836 fail(actual, expected, message, '===', assert.strictEqual);
837 }
838};
839
840// 10. The strict non-equality assertion tests for strict inequality, as
841// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
842
843assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
844 if (actual === expected) {
845 fail(actual, expected, message, '!==', assert.notStrictEqual);
846 }
847};
848
849function expectedException(actual, expected) {
850 if (!actual || !expected) {
851 return false;
852 }
853
854 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
855 return expected.test(actual);
856 }
857
858 try {
859 if (actual instanceof expected) {
860 return true;
861 }
862 } catch (e) {
863 // Ignore. The instanceof check doesn't work for arrow functions.
864 }
865
866 if (Error.isPrototypeOf(expected)) {
867 return false;
868 }
869
870 return expected.call({}, actual) === true;
871}
872
873function _tryBlock(block) {
874 var error;
875 try {
876 block();
877 } catch (e) {
878 error = e;
879 }
880 return error;
881}
882
883function _throws(shouldThrow, block, expected, message) {
884 var actual;
885
886 if (typeof block !== 'function') {
887 throw new TypeError('"block" argument must be a function');
888 }
889
890 if (typeof expected === 'string') {
891 message = expected;
892 expected = null;
893 }
894
895 actual = _tryBlock(block);
896
897 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
898 (message ? ' ' + message : '.');
899
900 if (shouldThrow && !actual) {
901 fail(actual, expected, 'Missing expected exception' + message);
902 }
903
904 var userProvidedMessage = typeof message === 'string';
905 var isUnwantedException = !shouldThrow && util.isError(actual);
906 var isUnexpectedException = !shouldThrow && actual && !expected;
907
908 if ((isUnwantedException &&
909 userProvidedMessage &&
910 expectedException(actual, expected)) ||
911 isUnexpectedException) {
912 fail(actual, expected, 'Got unwanted exception' + message);
913 }
914
915 if ((shouldThrow && actual && expected &&
916 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
917 throw actual;
918 }
919}
920
921// 11. Expected to throw an error:
922// assert.throws(block, Error_opt, message_opt);
923
924assert.throws = function(block, /*optional*/error, /*optional*/message) {
925 _throws(true, block, error, message);
926};
927
928// EXTENSION! This is annoying to write outside this module.
929assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
930 _throws(false, block, error, message);
931};
932
933assert.ifError = function(err) { if (err) throw err; };
934
935// Expose a strict only variant of assert
936function strict(value, message) {
937 if (!value) fail(value, true, message, '==', strict);
938}
939assert.strict = objectAssign(strict, assert, {
940 equal: assert.strictEqual,
941 deepEqual: assert.deepStrictEqual,
942 notEqual: assert.notStrictEqual,
943 notDeepEqual: assert.notDeepStrictEqual
944});
945assert.strict.strict = assert.strict;
946
947var objectKeys = Object.keys || function (obj) {
948 var keys = [];
949 for (var key in obj) {
950 if (hasOwn.call(obj, key)) keys.push(key);
951 }
952 return keys;
953};
954
955}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
956},{"71":71,"9":9}],7:[function(_dereq_,module,exports){
957if (typeof Object.create === 'function') {
958 // implementation from standard node.js 'util' module
959 module.exports = function inherits(ctor, superCtor) {
960 ctor.super_ = superCtor
961 ctor.prototype = Object.create(superCtor.prototype, {
962 constructor: {
963 value: ctor,
964 enumerable: false,
965 writable: true,
966 configurable: true
967 }
968 });
969 };
970} else {
971 // old school shim for old browsers
972 module.exports = function inherits(ctor, superCtor) {
973 ctor.super_ = superCtor
974 var TempCtor = function () {}
975 TempCtor.prototype = superCtor.prototype
976 ctor.prototype = new TempCtor()
977 ctor.prototype.constructor = ctor
978 }
979}
980
981},{}],8:[function(_dereq_,module,exports){
982module.exports = function isBuffer(arg) {
983 return arg && typeof arg === 'object'
984 && typeof arg.copy === 'function'
985 && typeof arg.fill === 'function'
986 && typeof arg.readUInt8 === 'function';
987}
988},{}],9:[function(_dereq_,module,exports){
989(function (process,global){(function (){
990// Copyright Joyent, Inc. and other Node contributors.
991//
992// Permission is hereby granted, free of charge, to any person obtaining a
993// copy of this software and associated documentation files (the
994// "Software"), to deal in the Software without restriction, including
995// without limitation the rights to use, copy, modify, merge, publish,
996// distribute, sublicense, and/or sell copies of the Software, and to permit
997// persons to whom the Software is furnished to do so, subject to the
998// following conditions:
999//
1000// The above copyright notice and this permission notice shall be included
1001// in all copies or substantial portions of the Software.
1002//
1003// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1004// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1005// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
1006// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
1007// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
1008// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
1009// USE OR OTHER DEALINGS IN THE SOFTWARE.
1010
1011var formatRegExp = /%[sdj%]/g;
1012exports.format = function(f) {
1013 if (!isString(f)) {
1014 var objects = [];
1015 for (var i = 0; i < arguments.length; i++) {
1016 objects.push(inspect(arguments[i]));
1017 }
1018 return objects.join(' ');
1019 }
1020
1021 var i = 1;
1022 var args = arguments;
1023 var len = args.length;
1024 var str = String(f).replace(formatRegExp, function(x) {
1025 if (x === '%%') return '%';
1026 if (i >= len) return x;
1027 switch (x) {
1028 case '%s': return String(args[i++]);
1029 case '%d': return Number(args[i++]);
1030 case '%j':
1031 try {
1032 return JSON.stringify(args[i++]);
1033 } catch (_) {
1034 return '[Circular]';
1035 }
1036 default:
1037 return x;
1038 }
1039 });
1040 for (var x = args[i]; i < len; x = args[++i]) {
1041 if (isNull(x) || !isObject(x)) {
1042 str += ' ' + x;
1043 } else {
1044 str += ' ' + inspect(x);
1045 }
1046 }
1047 return str;
1048};
1049
1050
1051// Mark that a method should not be used.
1052// Returns a modified function which warns once by default.
1053// If --no-deprecation is set, then it is a no-op.
1054exports.deprecate = function(fn, msg) {
1055 // Allow for deprecating things in the process of starting up.
1056 if (isUndefined(global.process)) {
1057 return function() {
1058 return exports.deprecate(fn, msg).apply(this, arguments);
1059 };
1060 }
1061
1062 if (process.noDeprecation === true) {
1063 return fn;
1064 }
1065
1066 var warned = false;
1067 function deprecated() {
1068 if (!warned) {
1069 if (process.throwDeprecation) {
1070 throw new Error(msg);
1071 } else if (process.traceDeprecation) {
1072 console.trace(msg);
1073 } else {
1074 console.error(msg);
1075 }
1076 warned = true;
1077 }
1078 return fn.apply(this, arguments);
1079 }
1080
1081 return deprecated;
1082};
1083
1084
1085var debugs = {};
1086var debugEnviron;
1087exports.debuglog = function(set) {
1088 if (isUndefined(debugEnviron))
1089 debugEnviron = process.env.NODE_DEBUG || '';
1090 set = set.toUpperCase();
1091 if (!debugs[set]) {
1092 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
1093 var pid = process.pid;
1094 debugs[set] = function() {
1095 var msg = exports.format.apply(exports, arguments);
1096 console.error('%s %d: %s', set, pid, msg);
1097 };
1098 } else {
1099 debugs[set] = function() {};
1100 }
1101 }
1102 return debugs[set];
1103};
1104
1105
1106/**
1107 * Echos the value of a value. Trys to print the value out
1108 * in the best way possible given the different types.
1109 *
1110 * @param {Object} obj The object to print out.
1111 * @param {Object} opts Optional options object that alters the output.
1112 */
1113/* legacy: obj, showHidden, depth, colors*/
1114function inspect(obj, opts) {
1115 // default options
1116 var ctx = {
1117 seen: [],
1118 stylize: stylizeNoColor
1119 };
1120 // legacy...
1121 if (arguments.length >= 3) ctx.depth = arguments[2];
1122 if (arguments.length >= 4) ctx.colors = arguments[3];
1123 if (isBoolean(opts)) {
1124 // legacy...
1125 ctx.showHidden = opts;
1126 } else if (opts) {
1127 // got an "options" object
1128 exports._extend(ctx, opts);
1129 }
1130 // set default options
1131 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
1132 if (isUndefined(ctx.depth)) ctx.depth = 2;
1133 if (isUndefined(ctx.colors)) ctx.colors = false;
1134 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
1135 if (ctx.colors) ctx.stylize = stylizeWithColor;
1136 return formatValue(ctx, obj, ctx.depth);
1137}
1138exports.inspect = inspect;
1139
1140
1141// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
1142inspect.colors = {
1143 'bold' : [1, 22],
1144 'italic' : [3, 23],
1145 'underline' : [4, 24],
1146 'inverse' : [7, 27],
1147 'white' : [37, 39],
1148 'grey' : [90, 39],
1149 'black' : [30, 39],
1150 'blue' : [34, 39],
1151 'cyan' : [36, 39],
1152 'green' : [32, 39],
1153 'magenta' : [35, 39],
1154 'red' : [31, 39],
1155 'yellow' : [33, 39]
1156};
1157
1158// Don't use 'blue' not visible on cmd.exe
1159inspect.styles = {
1160 'special': 'cyan',
1161 'number': 'yellow',
1162 'boolean': 'yellow',
1163 'undefined': 'grey',
1164 'null': 'bold',
1165 'string': 'green',
1166 'date': 'magenta',
1167 // "name": intentionally not styling
1168 'regexp': 'red'
1169};
1170
1171
1172function stylizeWithColor(str, styleType) {
1173 var style = inspect.styles[styleType];
1174
1175 if (style) {
1176 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
1177 '\u001b[' + inspect.colors[style][1] + 'm';
1178 } else {
1179 return str;
1180 }
1181}
1182
1183
1184function stylizeNoColor(str, styleType) {
1185 return str;
1186}
1187
1188
1189function arrayToHash(array) {
1190 var hash = {};
1191
1192 array.forEach(function(val, idx) {
1193 hash[val] = true;
1194 });
1195
1196 return hash;
1197}
1198
1199
1200function formatValue(ctx, value, recurseTimes) {
1201 // Provide a hook for user-specified inspect functions.
1202 // Check that value is an object with an inspect function on it
1203 if (ctx.customInspect &&
1204 value &&
1205 isFunction(value.inspect) &&
1206 // Filter out the util module, it's inspect function is special
1207 value.inspect !== exports.inspect &&
1208 // Also filter out any prototype objects using the circular check.
1209 !(value.constructor && value.constructor.prototype === value)) {
1210 var ret = value.inspect(recurseTimes, ctx);
1211 if (!isString(ret)) {
1212 ret = formatValue(ctx, ret, recurseTimes);
1213 }
1214 return ret;
1215 }
1216
1217 // Primitive types cannot have properties
1218 var primitive = formatPrimitive(ctx, value);
1219 if (primitive) {
1220 return primitive;
1221 }
1222
1223 // Look up the keys of the object.
1224 var keys = Object.keys(value);
1225 var visibleKeys = arrayToHash(keys);
1226
1227 if (ctx.showHidden) {
1228 keys = Object.getOwnPropertyNames(value);
1229 }
1230
1231 // IE doesn't make error fields non-enumerable
1232 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
1233 if (isError(value)
1234 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
1235 return formatError(value);
1236 }
1237
1238 // Some type of object without properties can be shortcutted.
1239 if (keys.length === 0) {
1240 if (isFunction(value)) {
1241 var name = value.name ? ': ' + value.name : '';
1242 return ctx.stylize('[Function' + name + ']', 'special');
1243 }
1244 if (isRegExp(value)) {
1245 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
1246 }
1247 if (isDate(value)) {
1248 return ctx.stylize(Date.prototype.toString.call(value), 'date');
1249 }
1250 if (isError(value)) {
1251 return formatError(value);
1252 }
1253 }
1254
1255 var base = '', array = false, braces = ['{', '}'];
1256
1257 // Make Array say that they are Array
1258 if (isArray(value)) {
1259 array = true;
1260 braces = ['[', ']'];
1261 }
1262
1263 // Make functions say that they are functions
1264 if (isFunction(value)) {
1265 var n = value.name ? ': ' + value.name : '';
1266 base = ' [Function' + n + ']';
1267 }
1268
1269 // Make RegExps say that they are RegExps
1270 if (isRegExp(value)) {
1271 base = ' ' + RegExp.prototype.toString.call(value);
1272 }
1273
1274 // Make dates with properties first say the date
1275 if (isDate(value)) {
1276 base = ' ' + Date.prototype.toUTCString.call(value);
1277 }
1278
1279 // Make error with message first say the error
1280 if (isError(value)) {
1281 base = ' ' + formatError(value);
1282 }
1283
1284 if (keys.length === 0 && (!array || value.length == 0)) {
1285 return braces[0] + base + braces[1];
1286 }
1287
1288 if (recurseTimes < 0) {
1289 if (isRegExp(value)) {
1290 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
1291 } else {
1292 return ctx.stylize('[Object]', 'special');
1293 }
1294 }
1295
1296 ctx.seen.push(value);
1297
1298 var output;
1299 if (array) {
1300 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
1301 } else {
1302 output = keys.map(function(key) {
1303 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
1304 });
1305 }
1306
1307 ctx.seen.pop();
1308
1309 return reduceToSingleString(output, base, braces);
1310}
1311
1312
1313function formatPrimitive(ctx, value) {
1314 if (isUndefined(value))
1315 return ctx.stylize('undefined', 'undefined');
1316 if (isString(value)) {
1317 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
1318 .replace(/'/g, "\\'")
1319 .replace(/\\"/g, '"') + '\'';
1320 return ctx.stylize(simple, 'string');
1321 }
1322 if (isNumber(value))
1323 return ctx.stylize('' + value, 'number');
1324 if (isBoolean(value))
1325 return ctx.stylize('' + value, 'boolean');
1326 // For some reason typeof null is "object", so special case here.
1327 if (isNull(value))
1328 return ctx.stylize('null', 'null');
1329}
1330
1331
1332function formatError(value) {
1333 return '[' + Error.prototype.toString.call(value) + ']';
1334}
1335
1336
1337function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
1338 var output = [];
1339 for (var i = 0, l = value.length; i < l; ++i) {
1340 if (hasOwnProperty(value, String(i))) {
1341 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
1342 String(i), true));
1343 } else {
1344 output.push('');
1345 }
1346 }
1347 keys.forEach(function(key) {
1348 if (!key.match(/^\d+$/)) {
1349 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
1350 key, true));
1351 }
1352 });
1353 return output;
1354}
1355
1356
1357function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
1358 var name, str, desc;
1359 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
1360 if (desc.get) {
1361 if (desc.set) {
1362 str = ctx.stylize('[Getter/Setter]', 'special');
1363 } else {
1364 str = ctx.stylize('[Getter]', 'special');
1365 }
1366 } else {
1367 if (desc.set) {
1368 str = ctx.stylize('[Setter]', 'special');
1369 }
1370 }
1371 if (!hasOwnProperty(visibleKeys, key)) {
1372 name = '[' + key + ']';
1373 }
1374 if (!str) {
1375 if (ctx.seen.indexOf(desc.value) < 0) {
1376 if (isNull(recurseTimes)) {
1377 str = formatValue(ctx, desc.value, null);
1378 } else {
1379 str = formatValue(ctx, desc.value, recurseTimes - 1);
1380 }
1381 if (str.indexOf('\n') > -1) {
1382 if (array) {
1383 str = str.split('\n').map(function(line) {
1384 return ' ' + line;
1385 }).join('\n').substr(2);
1386 } else {
1387 str = '\n' + str.split('\n').map(function(line) {
1388 return ' ' + line;
1389 }).join('\n');
1390 }
1391 }
1392 } else {
1393 str = ctx.stylize('[Circular]', 'special');
1394 }
1395 }
1396 if (isUndefined(name)) {
1397 if (array && key.match(/^\d+$/)) {
1398 return str;
1399 }
1400 name = JSON.stringify('' + key);
1401 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
1402 name = name.substr(1, name.length - 2);
1403 name = ctx.stylize(name, 'name');
1404 } else {
1405 name = name.replace(/'/g, "\\'")
1406 .replace(/\\"/g, '"')
1407 .replace(/(^"|"$)/g, "'");
1408 name = ctx.stylize(name, 'string');
1409 }
1410 }
1411
1412 return name + ': ' + str;
1413}
1414
1415
1416function reduceToSingleString(output, base, braces) {
1417 var numLinesEst = 0;
1418 var length = output.reduce(function(prev, cur) {
1419 numLinesEst++;
1420 if (cur.indexOf('\n') >= 0) numLinesEst++;
1421 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
1422 }, 0);
1423
1424 if (length > 60) {
1425 return braces[0] +
1426 (base === '' ? '' : base + '\n ') +
1427 ' ' +
1428 output.join(',\n ') +
1429 ' ' +
1430 braces[1];
1431 }
1432
1433 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
1434}
1435
1436
1437// NOTE: These type checking functions intentionally don't use `instanceof`
1438// because it is fragile and can be easily faked with `Object.create()`.
1439function isArray(ar) {
1440 return Array.isArray(ar);
1441}
1442exports.isArray = isArray;
1443
1444function isBoolean(arg) {
1445 return typeof arg === 'boolean';
1446}
1447exports.isBoolean = isBoolean;
1448
1449function isNull(arg) {
1450 return arg === null;
1451}
1452exports.isNull = isNull;
1453
1454function isNullOrUndefined(arg) {
1455 return arg == null;
1456}
1457exports.isNullOrUndefined = isNullOrUndefined;
1458
1459function isNumber(arg) {
1460 return typeof arg === 'number';
1461}
1462exports.isNumber = isNumber;
1463
1464function isString(arg) {
1465 return typeof arg === 'string';
1466}
1467exports.isString = isString;
1468
1469function isSymbol(arg) {
1470 return typeof arg === 'symbol';
1471}
1472exports.isSymbol = isSymbol;
1473
1474function isUndefined(arg) {
1475 return arg === void 0;
1476}
1477exports.isUndefined = isUndefined;
1478
1479function isRegExp(re) {
1480 return isObject(re) && objectToString(re) === '[object RegExp]';
1481}
1482exports.isRegExp = isRegExp;
1483
1484function isObject(arg) {
1485 return typeof arg === 'object' && arg !== null;
1486}
1487exports.isObject = isObject;
1488
1489function isDate(d) {
1490 return isObject(d) && objectToString(d) === '[object Date]';
1491}
1492exports.isDate = isDate;
1493
1494function isError(e) {
1495 return isObject(e) &&
1496 (objectToString(e) === '[object Error]' || e instanceof Error);
1497}
1498exports.isError = isError;
1499
1500function isFunction(arg) {
1501 return typeof arg === 'function';
1502}
1503exports.isFunction = isFunction;
1504
1505function isPrimitive(arg) {
1506 return arg === null ||
1507 typeof arg === 'boolean' ||
1508 typeof arg === 'number' ||
1509 typeof arg === 'string' ||
1510 typeof arg === 'symbol' || // ES6 symbol
1511 typeof arg === 'undefined';
1512}
1513exports.isPrimitive = isPrimitive;
1514
1515exports.isBuffer = _dereq_(8);
1516
1517function objectToString(o) {
1518 return Object.prototype.toString.call(o);
1519}
1520
1521
1522function pad(n) {
1523 return n < 10 ? '0' + n.toString(10) : n.toString(10);
1524}
1525
1526
1527var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
1528 'Oct', 'Nov', 'Dec'];
1529
1530// 26 Feb 16:19:34
1531function timestamp() {
1532 var d = new Date();
1533 var time = [pad(d.getHours()),
1534 pad(d.getMinutes()),
1535 pad(d.getSeconds())].join(':');
1536 return [d.getDate(), months[d.getMonth()], time].join(' ');
1537}
1538
1539
1540// log is just a thin wrapper to console.log that prepends a timestamp
1541exports.log = function() {
1542 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
1543};
1544
1545
1546/**
1547 * Inherit the prototype methods from one constructor into another.
1548 *
1549 * The Function.prototype.inherits from lang.js rewritten as a standalone
1550 * function (not on Function.prototype). NOTE: If this file is to be loaded
1551 * during bootstrapping this function needs to be rewritten using some native
1552 * functions as prototype setup using normal JavaScript does not work as
1553 * expected during bootstrapping (see mirror.js in r114903).
1554 *
1555 * @param {function} ctor Constructor function which needs to inherit the
1556 * prototype.
1557 * @param {function} superCtor Constructor function to inherit prototype from.
1558 */
1559exports.inherits = _dereq_(7);
1560
1561exports._extend = function(origin, add) {
1562 // Don't do anything if add isn't an object
1563 if (!add || !isObject(add)) return origin;
1564
1565 var keys = Object.keys(add);
1566 var i = keys.length;
1567 while (i--) {
1568 origin[keys[i]] = add[keys[i]];
1569 }
1570 return origin;
1571};
1572
1573function hasOwnProperty(obj, prop) {
1574 return Object.prototype.hasOwnProperty.call(obj, prop);
1575}
1576
1577}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1578},{"7":7,"73":73,"8":8}],10:[function(_dereq_,module,exports){
1579'use strict'
1580
1581exports.byteLength = byteLength
1582exports.toByteArray = toByteArray
1583exports.fromByteArray = fromByteArray
1584
1585var lookup = []
1586var revLookup = []
1587var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
1588
1589var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1590for (var i = 0, len = code.length; i < len; ++i) {
1591 lookup[i] = code[i]
1592 revLookup[code.charCodeAt(i)] = i
1593}
1594
1595// Support decoding URL-safe base64 strings, as Node.js does.
1596// See: https://en.wikipedia.org/wiki/Base64#URL_applications
1597revLookup['-'.charCodeAt(0)] = 62
1598revLookup['_'.charCodeAt(0)] = 63
1599
1600function getLens (b64) {
1601 var len = b64.length
1602
1603 if (len % 4 > 0) {
1604 throw new Error('Invalid string. Length must be a multiple of 4')
1605 }
1606
1607 // Trim off extra bytes after placeholder bytes are found
1608 // See: https://github.com/beatgammit/base64-js/issues/42
1609 var validLen = b64.indexOf('=')
1610 if (validLen === -1) validLen = len
1611
1612 var placeHoldersLen = validLen === len
1613 ? 0
1614 : 4 - (validLen % 4)
1615
1616 return [validLen, placeHoldersLen]
1617}
1618
1619// base64 is 4/3 + up to two characters of the original data
1620function byteLength (b64) {
1621 var lens = getLens(b64)
1622 var validLen = lens[0]
1623 var placeHoldersLen = lens[1]
1624 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1625}
1626
1627function _byteLength (b64, validLen, placeHoldersLen) {
1628 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1629}
1630
1631function toByteArray (b64) {
1632 var tmp
1633 var lens = getLens(b64)
1634 var validLen = lens[0]
1635 var placeHoldersLen = lens[1]
1636
1637 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1638
1639 var curByte = 0
1640
1641 // if there are placeholders, only get up to the last complete 4 chars
1642 var len = placeHoldersLen > 0
1643 ? validLen - 4
1644 : validLen
1645
1646 var i
1647 for (i = 0; i < len; i += 4) {
1648 tmp =
1649 (revLookup[b64.charCodeAt(i)] << 18) |
1650 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1651 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1652 revLookup[b64.charCodeAt(i + 3)]
1653 arr[curByte++] = (tmp >> 16) & 0xFF
1654 arr[curByte++] = (tmp >> 8) & 0xFF
1655 arr[curByte++] = tmp & 0xFF
1656 }
1657
1658 if (placeHoldersLen === 2) {
1659 tmp =
1660 (revLookup[b64.charCodeAt(i)] << 2) |
1661 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1662 arr[curByte++] = tmp & 0xFF
1663 }
1664
1665 if (placeHoldersLen === 1) {
1666 tmp =
1667 (revLookup[b64.charCodeAt(i)] << 10) |
1668 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1669 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1670 arr[curByte++] = (tmp >> 8) & 0xFF
1671 arr[curByte++] = tmp & 0xFF
1672 }
1673
1674 return arr
1675}
1676
1677function tripletToBase64 (num) {
1678 return lookup[num >> 18 & 0x3F] +
1679 lookup[num >> 12 & 0x3F] +
1680 lookup[num >> 6 & 0x3F] +
1681 lookup[num & 0x3F]
1682}
1683
1684function encodeChunk (uint8, start, end) {
1685 var tmp
1686 var output = []
1687 for (var i = start; i < end; i += 3) {
1688 tmp =
1689 ((uint8[i] << 16) & 0xFF0000) +
1690 ((uint8[i + 1] << 8) & 0xFF00) +
1691 (uint8[i + 2] & 0xFF)
1692 output.push(tripletToBase64(tmp))
1693 }
1694 return output.join('')
1695}
1696
1697function fromByteArray (uint8) {
1698 var tmp
1699 var len = uint8.length
1700 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1701 var parts = []
1702 var maxChunkLength = 16383 // must be multiple of 3
1703
1704 // go through the array every three bytes, we'll deal with trailing stuff later
1705 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1706 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
1707 }
1708
1709 // pad the end with zeros, but make sure to not forget the extra bytes
1710 if (extraBytes === 1) {
1711 tmp = uint8[len - 1]
1712 parts.push(
1713 lookup[tmp >> 2] +
1714 lookup[(tmp << 4) & 0x3F] +
1715 '=='
1716 )
1717 } else if (extraBytes === 2) {
1718 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1719 parts.push(
1720 lookup[tmp >> 10] +
1721 lookup[(tmp >> 4) & 0x3F] +
1722 lookup[(tmp << 2) & 0x3F] +
1723 '='
1724 )
1725 }
1726
1727 return parts.join('')
1728}
1729
1730},{}],11:[function(_dereq_,module,exports){
1731
1732},{}],12:[function(_dereq_,module,exports){
1733(function (Buffer){(function (){
1734/* eslint-disable node/no-deprecated-api */
1735
1736var toString = Object.prototype.toString
1737
1738var isModern = (
1739 typeof Buffer !== 'undefined' &&
1740 typeof Buffer.alloc === 'function' &&
1741 typeof Buffer.allocUnsafe === 'function' &&
1742 typeof Buffer.from === 'function'
1743)
1744
1745function isArrayBuffer (input) {
1746 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1747}
1748
1749function fromArrayBuffer (obj, byteOffset, length) {
1750 byteOffset >>>= 0
1751
1752 var maxLength = obj.byteLength - byteOffset
1753
1754 if (maxLength < 0) {
1755 throw new RangeError("'offset' is out of bounds")
1756 }
1757
1758 if (length === undefined) {
1759 length = maxLength
1760 } else {
1761 length >>>= 0
1762
1763 if (length > maxLength) {
1764 throw new RangeError("'length' is out of bounds")
1765 }
1766 }
1767
1768 return isModern
1769 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1770 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1771}
1772
1773function fromString (string, encoding) {
1774 if (typeof encoding !== 'string' || encoding === '') {
1775 encoding = 'utf8'
1776 }
1777
1778 if (!Buffer.isEncoding(encoding)) {
1779 throw new TypeError('"encoding" must be a valid string encoding')
1780 }
1781
1782 return isModern
1783 ? Buffer.from(string, encoding)
1784 : new Buffer(string, encoding)
1785}
1786
1787function bufferFrom (value, encodingOrOffset, length) {
1788 if (typeof value === 'number') {
1789 throw new TypeError('"value" argument must not be a number')
1790 }
1791
1792 if (isArrayBuffer(value)) {
1793 return fromArrayBuffer(value, encodingOrOffset, length)
1794 }
1795
1796 if (typeof value === 'string') {
1797 return fromString(value, encodingOrOffset)
1798 }
1799
1800 return isModern
1801 ? Buffer.from(value)
1802 : new Buffer(value)
1803}
1804
1805module.exports = bufferFrom
1806
1807}).call(this)}).call(this,_dereq_(13).Buffer)
1808},{"13":13}],13:[function(_dereq_,module,exports){
1809(function (Buffer){(function (){
1810/*!
1811 * The buffer module from node.js, for the browser.
1812 *
1813 * @author Feross Aboukhadijeh <https://feross.org>
1814 * @license MIT
1815 */
1816/* eslint-disable no-proto */
1817
1818'use strict'
1819
1820var base64 = _dereq_(10)
1821var ieee754 = _dereq_(30)
1822var customInspectSymbol =
1823 (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
1824 ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
1825 : null
1826
1827exports.Buffer = Buffer
1828exports.SlowBuffer = SlowBuffer
1829exports.INSPECT_MAX_BYTES = 50
1830
1831var K_MAX_LENGTH = 0x7fffffff
1832exports.kMaxLength = K_MAX_LENGTH
1833
1834/**
1835 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1836 * === true Use Uint8Array implementation (fastest)
1837 * === false Print warning and recommend using `buffer` v4.x which has an Object
1838 * implementation (most compatible, even IE6)
1839 *
1840 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1841 * Opera 11.6+, iOS 4.2+.
1842 *
1843 * We report that the browser does not support typed arrays if the are not subclassable
1844 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1845 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1846 * for __proto__ and has a buggy typed array implementation.
1847 */
1848Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1849
1850if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1851 typeof console.error === 'function') {
1852 console.error(
1853 'This browser lacks typed array (Uint8Array) support which is required by ' +
1854 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1855 )
1856}
1857
1858function typedArraySupport () {
1859 // Can typed array instances can be augmented?
1860 try {
1861 var arr = new Uint8Array(1)
1862 var proto = { foo: function () { return 42 } }
1863 Object.setPrototypeOf(proto, Uint8Array.prototype)
1864 Object.setPrototypeOf(arr, proto)
1865 return arr.foo() === 42
1866 } catch (e) {
1867 return false
1868 }
1869}
1870
1871Object.defineProperty(Buffer.prototype, 'parent', {
1872 enumerable: true,
1873 get: function () {
1874 if (!Buffer.isBuffer(this)) return undefined
1875 return this.buffer
1876 }
1877})
1878
1879Object.defineProperty(Buffer.prototype, 'offset', {
1880 enumerable: true,
1881 get: function () {
1882 if (!Buffer.isBuffer(this)) return undefined
1883 return this.byteOffset
1884 }
1885})
1886
1887function createBuffer (length) {
1888 if (length > K_MAX_LENGTH) {
1889 throw new RangeError('The value "' + length + '" is invalid for option "size"')
1890 }
1891 // Return an augmented `Uint8Array` instance
1892 var buf = new Uint8Array(length)
1893 Object.setPrototypeOf(buf, Buffer.prototype)
1894 return buf
1895}
1896
1897/**
1898 * The Buffer constructor returns instances of `Uint8Array` that have their
1899 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1900 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1901 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1902 * returns a single octet.
1903 *
1904 * The `Uint8Array` prototype remains unmodified.
1905 */
1906
1907function Buffer (arg, encodingOrOffset, length) {
1908 // Common case.
1909 if (typeof arg === 'number') {
1910 if (typeof encodingOrOffset === 'string') {
1911 throw new TypeError(
1912 'The "string" argument must be of type string. Received type number'
1913 )
1914 }
1915 return allocUnsafe(arg)
1916 }
1917 return from(arg, encodingOrOffset, length)
1918}
1919
1920Buffer.poolSize = 8192 // not used by this implementation
1921
1922function from (value, encodingOrOffset, length) {
1923 if (typeof value === 'string') {
1924 return fromString(value, encodingOrOffset)
1925 }
1926
1927 if (ArrayBuffer.isView(value)) {
1928 return fromArrayView(value)
1929 }
1930
1931 if (value == null) {
1932 throw new TypeError(
1933 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1934 'or Array-like Object. Received type ' + (typeof value)
1935 )
1936 }
1937
1938 if (isInstance(value, ArrayBuffer) ||
1939 (value && isInstance(value.buffer, ArrayBuffer))) {
1940 return fromArrayBuffer(value, encodingOrOffset, length)
1941 }
1942
1943 if (typeof SharedArrayBuffer !== 'undefined' &&
1944 (isInstance(value, SharedArrayBuffer) ||
1945 (value && isInstance(value.buffer, SharedArrayBuffer)))) {
1946 return fromArrayBuffer(value, encodingOrOffset, length)
1947 }
1948
1949 if (typeof value === 'number') {
1950 throw new TypeError(
1951 'The "value" argument must not be of type number. Received type number'
1952 )
1953 }
1954
1955 var valueOf = value.valueOf && value.valueOf()
1956 if (valueOf != null && valueOf !== value) {
1957 return Buffer.from(valueOf, encodingOrOffset, length)
1958 }
1959
1960 var b = fromObject(value)
1961 if (b) return b
1962
1963 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
1964 typeof value[Symbol.toPrimitive] === 'function') {
1965 return Buffer.from(
1966 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
1967 )
1968 }
1969
1970 throw new TypeError(
1971 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1972 'or Array-like Object. Received type ' + (typeof value)
1973 )
1974}
1975
1976/**
1977 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1978 * if value is a number.
1979 * Buffer.from(str[, encoding])
1980 * Buffer.from(array)
1981 * Buffer.from(buffer)
1982 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1983 **/
1984Buffer.from = function (value, encodingOrOffset, length) {
1985 return from(value, encodingOrOffset, length)
1986}
1987
1988// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1989// https://github.com/feross/buffer/pull/148
1990Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
1991Object.setPrototypeOf(Buffer, Uint8Array)
1992
1993function assertSize (size) {
1994 if (typeof size !== 'number') {
1995 throw new TypeError('"size" argument must be of type number')
1996 } else if (size < 0) {
1997 throw new RangeError('The value "' + size + '" is invalid for option "size"')
1998 }
1999}
2000
2001function alloc (size, fill, encoding) {
2002 assertSize(size)
2003 if (size <= 0) {
2004 return createBuffer(size)
2005 }
2006 if (fill !== undefined) {
2007 // Only pay attention to encoding if it's a string. This
2008 // prevents accidentally sending in a number that would
2009 // be interpreted as a start offset.
2010 return typeof encoding === 'string'
2011 ? createBuffer(size).fill(fill, encoding)
2012 : createBuffer(size).fill(fill)
2013 }
2014 return createBuffer(size)
2015}
2016
2017/**
2018 * Creates a new filled Buffer instance.
2019 * alloc(size[, fill[, encoding]])
2020 **/
2021Buffer.alloc = function (size, fill, encoding) {
2022 return alloc(size, fill, encoding)
2023}
2024
2025function allocUnsafe (size) {
2026 assertSize(size)
2027 return createBuffer(size < 0 ? 0 : checked(size) | 0)
2028}
2029
2030/**
2031 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
2032 * */
2033Buffer.allocUnsafe = function (size) {
2034 return allocUnsafe(size)
2035}
2036/**
2037 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
2038 */
2039Buffer.allocUnsafeSlow = function (size) {
2040 return allocUnsafe(size)
2041}
2042
2043function fromString (string, encoding) {
2044 if (typeof encoding !== 'string' || encoding === '') {
2045 encoding = 'utf8'
2046 }
2047
2048 if (!Buffer.isEncoding(encoding)) {
2049 throw new TypeError('Unknown encoding: ' + encoding)
2050 }
2051
2052 var length = byteLength(string, encoding) | 0
2053 var buf = createBuffer(length)
2054
2055 var actual = buf.write(string, encoding)
2056
2057 if (actual !== length) {
2058 // Writing a hex string, for example, that contains invalid characters will
2059 // cause everything after the first invalid character to be ignored. (e.g.
2060 // 'abxxcd' will be treated as 'ab')
2061 buf = buf.slice(0, actual)
2062 }
2063
2064 return buf
2065}
2066
2067function fromArrayLike (array) {
2068 var length = array.length < 0 ? 0 : checked(array.length) | 0
2069 var buf = createBuffer(length)
2070 for (var i = 0; i < length; i += 1) {
2071 buf[i] = array[i] & 255
2072 }
2073 return buf
2074}
2075
2076function fromArrayView (arrayView) {
2077 if (isInstance(arrayView, Uint8Array)) {
2078 var copy = new Uint8Array(arrayView)
2079 return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
2080 }
2081 return fromArrayLike(arrayView)
2082}
2083
2084function fromArrayBuffer (array, byteOffset, length) {
2085 if (byteOffset < 0 || array.byteLength < byteOffset) {
2086 throw new RangeError('"offset" is outside of buffer bounds')
2087 }
2088
2089 if (array.byteLength < byteOffset + (length || 0)) {
2090 throw new RangeError('"length" is outside of buffer bounds')
2091 }
2092
2093 var buf
2094 if (byteOffset === undefined && length === undefined) {
2095 buf = new Uint8Array(array)
2096 } else if (length === undefined) {
2097 buf = new Uint8Array(array, byteOffset)
2098 } else {
2099 buf = new Uint8Array(array, byteOffset, length)
2100 }
2101
2102 // Return an augmented `Uint8Array` instance
2103 Object.setPrototypeOf(buf, Buffer.prototype)
2104
2105 return buf
2106}
2107
2108function fromObject (obj) {
2109 if (Buffer.isBuffer(obj)) {
2110 var len = checked(obj.length) | 0
2111 var buf = createBuffer(len)
2112
2113 if (buf.length === 0) {
2114 return buf
2115 }
2116
2117 obj.copy(buf, 0, 0, len)
2118 return buf
2119 }
2120
2121 if (obj.length !== undefined) {
2122 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
2123 return createBuffer(0)
2124 }
2125 return fromArrayLike(obj)
2126 }
2127
2128 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
2129 return fromArrayLike(obj.data)
2130 }
2131}
2132
2133function checked (length) {
2134 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
2135 // length is NaN (which is otherwise coerced to zero.)
2136 if (length >= K_MAX_LENGTH) {
2137 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
2138 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
2139 }
2140 return length | 0
2141}
2142
2143function SlowBuffer (length) {
2144 if (+length != length) { // eslint-disable-line eqeqeq
2145 length = 0
2146 }
2147 return Buffer.alloc(+length)
2148}
2149
2150Buffer.isBuffer = function isBuffer (b) {
2151 return b != null && b._isBuffer === true &&
2152 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
2153}
2154
2155Buffer.compare = function compare (a, b) {
2156 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
2157 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
2158 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
2159 throw new TypeError(
2160 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
2161 )
2162 }
2163
2164 if (a === b) return 0
2165
2166 var x = a.length
2167 var y = b.length
2168
2169 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2170 if (a[i] !== b[i]) {
2171 x = a[i]
2172 y = b[i]
2173 break
2174 }
2175 }
2176
2177 if (x < y) return -1
2178 if (y < x) return 1
2179 return 0
2180}
2181
2182Buffer.isEncoding = function isEncoding (encoding) {
2183 switch (String(encoding).toLowerCase()) {
2184 case 'hex':
2185 case 'utf8':
2186 case 'utf-8':
2187 case 'ascii':
2188 case 'latin1':
2189 case 'binary':
2190 case 'base64':
2191 case 'ucs2':
2192 case 'ucs-2':
2193 case 'utf16le':
2194 case 'utf-16le':
2195 return true
2196 default:
2197 return false
2198 }
2199}
2200
2201Buffer.concat = function concat (list, length) {
2202 if (!Array.isArray(list)) {
2203 throw new TypeError('"list" argument must be an Array of Buffers')
2204 }
2205
2206 if (list.length === 0) {
2207 return Buffer.alloc(0)
2208 }
2209
2210 var i
2211 if (length === undefined) {
2212 length = 0
2213 for (i = 0; i < list.length; ++i) {
2214 length += list[i].length
2215 }
2216 }
2217
2218 var buffer = Buffer.allocUnsafe(length)
2219 var pos = 0
2220 for (i = 0; i < list.length; ++i) {
2221 var buf = list[i]
2222 if (isInstance(buf, Uint8Array)) {
2223 if (pos + buf.length > buffer.length) {
2224 Buffer.from(buf).copy(buffer, pos)
2225 } else {
2226 Uint8Array.prototype.set.call(
2227 buffer,
2228 buf,
2229 pos
2230 )
2231 }
2232 } else if (!Buffer.isBuffer(buf)) {
2233 throw new TypeError('"list" argument must be an Array of Buffers')
2234 } else {
2235 buf.copy(buffer, pos)
2236 }
2237 pos += buf.length
2238 }
2239 return buffer
2240}
2241
2242function byteLength (string, encoding) {
2243 if (Buffer.isBuffer(string)) {
2244 return string.length
2245 }
2246 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
2247 return string.byteLength
2248 }
2249 if (typeof string !== 'string') {
2250 throw new TypeError(
2251 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
2252 'Received type ' + typeof string
2253 )
2254 }
2255
2256 var len = string.length
2257 var mustMatch = (arguments.length > 2 && arguments[2] === true)
2258 if (!mustMatch && len === 0) return 0
2259
2260 // Use a for loop to avoid recursion
2261 var loweredCase = false
2262 for (;;) {
2263 switch (encoding) {
2264 case 'ascii':
2265 case 'latin1':
2266 case 'binary':
2267 return len
2268 case 'utf8':
2269 case 'utf-8':
2270 return utf8ToBytes(string).length
2271 case 'ucs2':
2272 case 'ucs-2':
2273 case 'utf16le':
2274 case 'utf-16le':
2275 return len * 2
2276 case 'hex':
2277 return len >>> 1
2278 case 'base64':
2279 return base64ToBytes(string).length
2280 default:
2281 if (loweredCase) {
2282 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
2283 }
2284 encoding = ('' + encoding).toLowerCase()
2285 loweredCase = true
2286 }
2287 }
2288}
2289Buffer.byteLength = byteLength
2290
2291function slowToString (encoding, start, end) {
2292 var loweredCase = false
2293
2294 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
2295 // property of a typed array.
2296
2297 // This behaves neither like String nor Uint8Array in that we set start/end
2298 // to their upper/lower bounds if the value passed is out of range.
2299 // undefined is handled specially as per ECMA-262 6th Edition,
2300 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
2301 if (start === undefined || start < 0) {
2302 start = 0
2303 }
2304 // Return early if start > this.length. Done here to prevent potential uint32
2305 // coercion fail below.
2306 if (start > this.length) {
2307 return ''
2308 }
2309
2310 if (end === undefined || end > this.length) {
2311 end = this.length
2312 }
2313
2314 if (end <= 0) {
2315 return ''
2316 }
2317
2318 // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
2319 end >>>= 0
2320 start >>>= 0
2321
2322 if (end <= start) {
2323 return ''
2324 }
2325
2326 if (!encoding) encoding = 'utf8'
2327
2328 while (true) {
2329 switch (encoding) {
2330 case 'hex':
2331 return hexSlice(this, start, end)
2332
2333 case 'utf8':
2334 case 'utf-8':
2335 return utf8Slice(this, start, end)
2336
2337 case 'ascii':
2338 return asciiSlice(this, start, end)
2339
2340 case 'latin1':
2341 case 'binary':
2342 return latin1Slice(this, start, end)
2343
2344 case 'base64':
2345 return base64Slice(this, start, end)
2346
2347 case 'ucs2':
2348 case 'ucs-2':
2349 case 'utf16le':
2350 case 'utf-16le':
2351 return utf16leSlice(this, start, end)
2352
2353 default:
2354 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2355 encoding = (encoding + '').toLowerCase()
2356 loweredCase = true
2357 }
2358 }
2359}
2360
2361// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
2362// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
2363// reliably in a browserify context because there could be multiple different
2364// copies of the 'buffer' package in use. This method works even for Buffer
2365// instances that were created from another copy of the `buffer` package.
2366// See: https://github.com/feross/buffer/issues/154
2367Buffer.prototype._isBuffer = true
2368
2369function swap (b, n, m) {
2370 var i = b[n]
2371 b[n] = b[m]
2372 b[m] = i
2373}
2374
2375Buffer.prototype.swap16 = function swap16 () {
2376 var len = this.length
2377 if (len % 2 !== 0) {
2378 throw new RangeError('Buffer size must be a multiple of 16-bits')
2379 }
2380 for (var i = 0; i < len; i += 2) {
2381 swap(this, i, i + 1)
2382 }
2383 return this
2384}
2385
2386Buffer.prototype.swap32 = function swap32 () {
2387 var len = this.length
2388 if (len % 4 !== 0) {
2389 throw new RangeError('Buffer size must be a multiple of 32-bits')
2390 }
2391 for (var i = 0; i < len; i += 4) {
2392 swap(this, i, i + 3)
2393 swap(this, i + 1, i + 2)
2394 }
2395 return this
2396}
2397
2398Buffer.prototype.swap64 = function swap64 () {
2399 var len = this.length
2400 if (len % 8 !== 0) {
2401 throw new RangeError('Buffer size must be a multiple of 64-bits')
2402 }
2403 for (var i = 0; i < len; i += 8) {
2404 swap(this, i, i + 7)
2405 swap(this, i + 1, i + 6)
2406 swap(this, i + 2, i + 5)
2407 swap(this, i + 3, i + 4)
2408 }
2409 return this
2410}
2411
2412Buffer.prototype.toString = function toString () {
2413 var length = this.length
2414 if (length === 0) return ''
2415 if (arguments.length === 0) return utf8Slice(this, 0, length)
2416 return slowToString.apply(this, arguments)
2417}
2418
2419Buffer.prototype.toLocaleString = Buffer.prototype.toString
2420
2421Buffer.prototype.equals = function equals (b) {
2422 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2423 if (this === b) return true
2424 return Buffer.compare(this, b) === 0
2425}
2426
2427Buffer.prototype.inspect = function inspect () {
2428 var str = ''
2429 var max = exports.INSPECT_MAX_BYTES
2430 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
2431 if (this.length > max) str += ' ... '
2432 return '<Buffer ' + str + '>'
2433}
2434if (customInspectSymbol) {
2435 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
2436}
2437
2438Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2439 if (isInstance(target, Uint8Array)) {
2440 target = Buffer.from(target, target.offset, target.byteLength)
2441 }
2442 if (!Buffer.isBuffer(target)) {
2443 throw new TypeError(
2444 'The "target" argument must be one of type Buffer or Uint8Array. ' +
2445 'Received type ' + (typeof target)
2446 )
2447 }
2448
2449 if (start === undefined) {
2450 start = 0
2451 }
2452 if (end === undefined) {
2453 end = target ? target.length : 0
2454 }
2455 if (thisStart === undefined) {
2456 thisStart = 0
2457 }
2458 if (thisEnd === undefined) {
2459 thisEnd = this.length
2460 }
2461
2462 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2463 throw new RangeError('out of range index')
2464 }
2465
2466 if (thisStart >= thisEnd && start >= end) {
2467 return 0
2468 }
2469 if (thisStart >= thisEnd) {
2470 return -1
2471 }
2472 if (start >= end) {
2473 return 1
2474 }
2475
2476 start >>>= 0
2477 end >>>= 0
2478 thisStart >>>= 0
2479 thisEnd >>>= 0
2480
2481 if (this === target) return 0
2482
2483 var x = thisEnd - thisStart
2484 var y = end - start
2485 var len = Math.min(x, y)
2486
2487 var thisCopy = this.slice(thisStart, thisEnd)
2488 var targetCopy = target.slice(start, end)
2489
2490 for (var i = 0; i < len; ++i) {
2491 if (thisCopy[i] !== targetCopy[i]) {
2492 x = thisCopy[i]
2493 y = targetCopy[i]
2494 break
2495 }
2496 }
2497
2498 if (x < y) return -1
2499 if (y < x) return 1
2500 return 0
2501}
2502
2503// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2504// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2505//
2506// Arguments:
2507// - buffer - a Buffer to search
2508// - val - a string, Buffer, or number
2509// - byteOffset - an index into `buffer`; will be clamped to an int32
2510// - encoding - an optional encoding, relevant is val is a string
2511// - dir - true for indexOf, false for lastIndexOf
2512function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2513 // Empty buffer means no match
2514 if (buffer.length === 0) return -1
2515
2516 // Normalize byteOffset
2517 if (typeof byteOffset === 'string') {
2518 encoding = byteOffset
2519 byteOffset = 0
2520 } else if (byteOffset > 0x7fffffff) {
2521 byteOffset = 0x7fffffff
2522 } else if (byteOffset < -0x80000000) {
2523 byteOffset = -0x80000000
2524 }
2525 byteOffset = +byteOffset // Coerce to Number.
2526 if (numberIsNaN(byteOffset)) {
2527 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2528 byteOffset = dir ? 0 : (buffer.length - 1)
2529 }
2530
2531 // Normalize byteOffset: negative offsets start from the end of the buffer
2532 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2533 if (byteOffset >= buffer.length) {
2534 if (dir) return -1
2535 else byteOffset = buffer.length - 1
2536 } else if (byteOffset < 0) {
2537 if (dir) byteOffset = 0
2538 else return -1
2539 }
2540
2541 // Normalize val
2542 if (typeof val === 'string') {
2543 val = Buffer.from(val, encoding)
2544 }
2545
2546 // Finally, search either indexOf (if dir is true) or lastIndexOf
2547 if (Buffer.isBuffer(val)) {
2548 // Special case: looking for empty string/buffer always fails
2549 if (val.length === 0) {
2550 return -1
2551 }
2552 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2553 } else if (typeof val === 'number') {
2554 val = val & 0xFF // Search for a byte value [0-255]
2555 if (typeof Uint8Array.prototype.indexOf === 'function') {
2556 if (dir) {
2557 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2558 } else {
2559 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2560 }
2561 }
2562 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
2563 }
2564
2565 throw new TypeError('val must be string, number or Buffer')
2566}
2567
2568function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2569 var indexSize = 1
2570 var arrLength = arr.length
2571 var valLength = val.length
2572
2573 if (encoding !== undefined) {
2574 encoding = String(encoding).toLowerCase()
2575 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2576 encoding === 'utf16le' || encoding === 'utf-16le') {
2577 if (arr.length < 2 || val.length < 2) {
2578 return -1
2579 }
2580 indexSize = 2
2581 arrLength /= 2
2582 valLength /= 2
2583 byteOffset /= 2
2584 }
2585 }
2586
2587 function read (buf, i) {
2588 if (indexSize === 1) {
2589 return buf[i]
2590 } else {
2591 return buf.readUInt16BE(i * indexSize)
2592 }
2593 }
2594
2595 var i
2596 if (dir) {
2597 var foundIndex = -1
2598 for (i = byteOffset; i < arrLength; i++) {
2599 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2600 if (foundIndex === -1) foundIndex = i
2601 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2602 } else {
2603 if (foundIndex !== -1) i -= i - foundIndex
2604 foundIndex = -1
2605 }
2606 }
2607 } else {
2608 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2609 for (i = byteOffset; i >= 0; i--) {
2610 var found = true
2611 for (var j = 0; j < valLength; j++) {
2612 if (read(arr, i + j) !== read(val, j)) {
2613 found = false
2614 break
2615 }
2616 }
2617 if (found) return i
2618 }
2619 }
2620
2621 return -1
2622}
2623
2624Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2625 return this.indexOf(val, byteOffset, encoding) !== -1
2626}
2627
2628Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2629 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2630}
2631
2632Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2633 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2634}
2635
2636function hexWrite (buf, string, offset, length) {
2637 offset = Number(offset) || 0
2638 var remaining = buf.length - offset
2639 if (!length) {
2640 length = remaining
2641 } else {
2642 length = Number(length)
2643 if (length > remaining) {
2644 length = remaining
2645 }
2646 }
2647
2648 var strLen = string.length
2649
2650 if (length > strLen / 2) {
2651 length = strLen / 2
2652 }
2653 for (var i = 0; i < length; ++i) {
2654 var parsed = parseInt(string.substr(i * 2, 2), 16)
2655 if (numberIsNaN(parsed)) return i
2656 buf[offset + i] = parsed
2657 }
2658 return i
2659}
2660
2661function utf8Write (buf, string, offset, length) {
2662 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2663}
2664
2665function asciiWrite (buf, string, offset, length) {
2666 return blitBuffer(asciiToBytes(string), buf, offset, length)
2667}
2668
2669function base64Write (buf, string, offset, length) {
2670 return blitBuffer(base64ToBytes(string), buf, offset, length)
2671}
2672
2673function ucs2Write (buf, string, offset, length) {
2674 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2675}
2676
2677Buffer.prototype.write = function write (string, offset, length, encoding) {
2678 // Buffer#write(string)
2679 if (offset === undefined) {
2680 encoding = 'utf8'
2681 length = this.length
2682 offset = 0
2683 // Buffer#write(string, encoding)
2684 } else if (length === undefined && typeof offset === 'string') {
2685 encoding = offset
2686 length = this.length
2687 offset = 0
2688 // Buffer#write(string, offset[, length][, encoding])
2689 } else if (isFinite(offset)) {
2690 offset = offset >>> 0
2691 if (isFinite(length)) {
2692 length = length >>> 0
2693 if (encoding === undefined) encoding = 'utf8'
2694 } else {
2695 encoding = length
2696 length = undefined
2697 }
2698 } else {
2699 throw new Error(
2700 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2701 )
2702 }
2703
2704 var remaining = this.length - offset
2705 if (length === undefined || length > remaining) length = remaining
2706
2707 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2708 throw new RangeError('Attempt to write outside buffer bounds')
2709 }
2710
2711 if (!encoding) encoding = 'utf8'
2712
2713 var loweredCase = false
2714 for (;;) {
2715 switch (encoding) {
2716 case 'hex':
2717 return hexWrite(this, string, offset, length)
2718
2719 case 'utf8':
2720 case 'utf-8':
2721 return utf8Write(this, string, offset, length)
2722
2723 case 'ascii':
2724 case 'latin1':
2725 case 'binary':
2726 return asciiWrite(this, string, offset, length)
2727
2728 case 'base64':
2729 // Warning: maxLength not taken into account in base64Write
2730 return base64Write(this, string, offset, length)
2731
2732 case 'ucs2':
2733 case 'ucs-2':
2734 case 'utf16le':
2735 case 'utf-16le':
2736 return ucs2Write(this, string, offset, length)
2737
2738 default:
2739 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2740 encoding = ('' + encoding).toLowerCase()
2741 loweredCase = true
2742 }
2743 }
2744}
2745
2746Buffer.prototype.toJSON = function toJSON () {
2747 return {
2748 type: 'Buffer',
2749 data: Array.prototype.slice.call(this._arr || this, 0)
2750 }
2751}
2752
2753function base64Slice (buf, start, end) {
2754 if (start === 0 && end === buf.length) {
2755 return base64.fromByteArray(buf)
2756 } else {
2757 return base64.fromByteArray(buf.slice(start, end))
2758 }
2759}
2760
2761function utf8Slice (buf, start, end) {
2762 end = Math.min(buf.length, end)
2763 var res = []
2764
2765 var i = start
2766 while (i < end) {
2767 var firstByte = buf[i]
2768 var codePoint = null
2769 var bytesPerSequence = (firstByte > 0xEF)
2770 ? 4
2771 : (firstByte > 0xDF)
2772 ? 3
2773 : (firstByte > 0xBF)
2774 ? 2
2775 : 1
2776
2777 if (i + bytesPerSequence <= end) {
2778 var secondByte, thirdByte, fourthByte, tempCodePoint
2779
2780 switch (bytesPerSequence) {
2781 case 1:
2782 if (firstByte < 0x80) {
2783 codePoint = firstByte
2784 }
2785 break
2786 case 2:
2787 secondByte = buf[i + 1]
2788 if ((secondByte & 0xC0) === 0x80) {
2789 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2790 if (tempCodePoint > 0x7F) {
2791 codePoint = tempCodePoint
2792 }
2793 }
2794 break
2795 case 3:
2796 secondByte = buf[i + 1]
2797 thirdByte = buf[i + 2]
2798 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2799 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2800 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2801 codePoint = tempCodePoint
2802 }
2803 }
2804 break
2805 case 4:
2806 secondByte = buf[i + 1]
2807 thirdByte = buf[i + 2]
2808 fourthByte = buf[i + 3]
2809 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2810 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2811 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2812 codePoint = tempCodePoint
2813 }
2814 }
2815 }
2816 }
2817
2818 if (codePoint === null) {
2819 // we did not generate a valid codePoint so insert a
2820 // replacement char (U+FFFD) and advance only 1 byte
2821 codePoint = 0xFFFD
2822 bytesPerSequence = 1
2823 } else if (codePoint > 0xFFFF) {
2824 // encode to utf16 (surrogate pair dance)
2825 codePoint -= 0x10000
2826 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2827 codePoint = 0xDC00 | codePoint & 0x3FF
2828 }
2829
2830 res.push(codePoint)
2831 i += bytesPerSequence
2832 }
2833
2834 return decodeCodePointsArray(res)
2835}
2836
2837// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2838// the lowest limit is Chrome, with 0x10000 args.
2839// We go 1 magnitude less, for safety
2840var MAX_ARGUMENTS_LENGTH = 0x1000
2841
2842function decodeCodePointsArray (codePoints) {
2843 var len = codePoints.length
2844 if (len <= MAX_ARGUMENTS_LENGTH) {
2845 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2846 }
2847
2848 // Decode in chunks to avoid "call stack size exceeded".
2849 var res = ''
2850 var i = 0
2851 while (i < len) {
2852 res += String.fromCharCode.apply(
2853 String,
2854 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2855 )
2856 }
2857 return res
2858}
2859
2860function asciiSlice (buf, start, end) {
2861 var ret = ''
2862 end = Math.min(buf.length, end)
2863
2864 for (var i = start; i < end; ++i) {
2865 ret += String.fromCharCode(buf[i] & 0x7F)
2866 }
2867 return ret
2868}
2869
2870function latin1Slice (buf, start, end) {
2871 var ret = ''
2872 end = Math.min(buf.length, end)
2873
2874 for (var i = start; i < end; ++i) {
2875 ret += String.fromCharCode(buf[i])
2876 }
2877 return ret
2878}
2879
2880function hexSlice (buf, start, end) {
2881 var len = buf.length
2882
2883 if (!start || start < 0) start = 0
2884 if (!end || end < 0 || end > len) end = len
2885
2886 var out = ''
2887 for (var i = start; i < end; ++i) {
2888 out += hexSliceLookupTable[buf[i]]
2889 }
2890 return out
2891}
2892
2893function utf16leSlice (buf, start, end) {
2894 var bytes = buf.slice(start, end)
2895 var res = ''
2896 // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
2897 for (var i = 0; i < bytes.length - 1; i += 2) {
2898 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2899 }
2900 return res
2901}
2902
2903Buffer.prototype.slice = function slice (start, end) {
2904 var len = this.length
2905 start = ~~start
2906 end = end === undefined ? len : ~~end
2907
2908 if (start < 0) {
2909 start += len
2910 if (start < 0) start = 0
2911 } else if (start > len) {
2912 start = len
2913 }
2914
2915 if (end < 0) {
2916 end += len
2917 if (end < 0) end = 0
2918 } else if (end > len) {
2919 end = len
2920 }
2921
2922 if (end < start) end = start
2923
2924 var newBuf = this.subarray(start, end)
2925 // Return an augmented `Uint8Array` instance
2926 Object.setPrototypeOf(newBuf, Buffer.prototype)
2927
2928 return newBuf
2929}
2930
2931/*
2932 * Need to make sure that buffer isn't trying to write out of bounds.
2933 */
2934function checkOffset (offset, ext, length) {
2935 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2936 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2937}
2938
2939Buffer.prototype.readUintLE =
2940Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2941 offset = offset >>> 0
2942 byteLength = byteLength >>> 0
2943 if (!noAssert) checkOffset(offset, byteLength, this.length)
2944
2945 var val = this[offset]
2946 var mul = 1
2947 var i = 0
2948 while (++i < byteLength && (mul *= 0x100)) {
2949 val += this[offset + i] * mul
2950 }
2951
2952 return val
2953}
2954
2955Buffer.prototype.readUintBE =
2956Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2957 offset = offset >>> 0
2958 byteLength = byteLength >>> 0
2959 if (!noAssert) {
2960 checkOffset(offset, byteLength, this.length)
2961 }
2962
2963 var val = this[offset + --byteLength]
2964 var mul = 1
2965 while (byteLength > 0 && (mul *= 0x100)) {
2966 val += this[offset + --byteLength] * mul
2967 }
2968
2969 return val
2970}
2971
2972Buffer.prototype.readUint8 =
2973Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2974 offset = offset >>> 0
2975 if (!noAssert) checkOffset(offset, 1, this.length)
2976 return this[offset]
2977}
2978
2979Buffer.prototype.readUint16LE =
2980Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2981 offset = offset >>> 0
2982 if (!noAssert) checkOffset(offset, 2, this.length)
2983 return this[offset] | (this[offset + 1] << 8)
2984}
2985
2986Buffer.prototype.readUint16BE =
2987Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2988 offset = offset >>> 0
2989 if (!noAssert) checkOffset(offset, 2, this.length)
2990 return (this[offset] << 8) | this[offset + 1]
2991}
2992
2993Buffer.prototype.readUint32LE =
2994Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2995 offset = offset >>> 0
2996 if (!noAssert) checkOffset(offset, 4, this.length)
2997
2998 return ((this[offset]) |
2999 (this[offset + 1] << 8) |
3000 (this[offset + 2] << 16)) +
3001 (this[offset + 3] * 0x1000000)
3002}
3003
3004Buffer.prototype.readUint32BE =
3005Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
3006 offset = offset >>> 0
3007 if (!noAssert) checkOffset(offset, 4, this.length)
3008
3009 return (this[offset] * 0x1000000) +
3010 ((this[offset + 1] << 16) |
3011 (this[offset + 2] << 8) |
3012 this[offset + 3])
3013}
3014
3015Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
3016 offset = offset >>> 0
3017 byteLength = byteLength >>> 0
3018 if (!noAssert) checkOffset(offset, byteLength, this.length)
3019
3020 var val = this[offset]
3021 var mul = 1
3022 var i = 0
3023 while (++i < byteLength && (mul *= 0x100)) {
3024 val += this[offset + i] * mul
3025 }
3026 mul *= 0x80
3027
3028 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
3029
3030 return val
3031}
3032
3033Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
3034 offset = offset >>> 0
3035 byteLength = byteLength >>> 0
3036 if (!noAssert) checkOffset(offset, byteLength, this.length)
3037
3038 var i = byteLength
3039 var mul = 1
3040 var val = this[offset + --i]
3041 while (i > 0 && (mul *= 0x100)) {
3042 val += this[offset + --i] * mul
3043 }
3044 mul *= 0x80
3045
3046 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
3047
3048 return val
3049}
3050
3051Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
3052 offset = offset >>> 0
3053 if (!noAssert) checkOffset(offset, 1, this.length)
3054 if (!(this[offset] & 0x80)) return (this[offset])
3055 return ((0xff - this[offset] + 1) * -1)
3056}
3057
3058Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
3059 offset = offset >>> 0
3060 if (!noAssert) checkOffset(offset, 2, this.length)
3061 var val = this[offset] | (this[offset + 1] << 8)
3062 return (val & 0x8000) ? val | 0xFFFF0000 : val
3063}
3064
3065Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
3066 offset = offset >>> 0
3067 if (!noAssert) checkOffset(offset, 2, this.length)
3068 var val = this[offset + 1] | (this[offset] << 8)
3069 return (val & 0x8000) ? val | 0xFFFF0000 : val
3070}
3071
3072Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
3073 offset = offset >>> 0
3074 if (!noAssert) checkOffset(offset, 4, this.length)
3075
3076 return (this[offset]) |
3077 (this[offset + 1] << 8) |
3078 (this[offset + 2] << 16) |
3079 (this[offset + 3] << 24)
3080}
3081
3082Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
3083 offset = offset >>> 0
3084 if (!noAssert) checkOffset(offset, 4, this.length)
3085
3086 return (this[offset] << 24) |
3087 (this[offset + 1] << 16) |
3088 (this[offset + 2] << 8) |
3089 (this[offset + 3])
3090}
3091
3092Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
3093 offset = offset >>> 0
3094 if (!noAssert) checkOffset(offset, 4, this.length)
3095 return ieee754.read(this, offset, true, 23, 4)
3096}
3097
3098Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
3099 offset = offset >>> 0
3100 if (!noAssert) checkOffset(offset, 4, this.length)
3101 return ieee754.read(this, offset, false, 23, 4)
3102}
3103
3104Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
3105 offset = offset >>> 0
3106 if (!noAssert) checkOffset(offset, 8, this.length)
3107 return ieee754.read(this, offset, true, 52, 8)
3108}
3109
3110Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
3111 offset = offset >>> 0
3112 if (!noAssert) checkOffset(offset, 8, this.length)
3113 return ieee754.read(this, offset, false, 52, 8)
3114}
3115
3116function checkInt (buf, value, offset, ext, max, min) {
3117 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
3118 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
3119 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3120}
3121
3122Buffer.prototype.writeUintLE =
3123Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
3124 value = +value
3125 offset = offset >>> 0
3126 byteLength = byteLength >>> 0
3127 if (!noAssert) {
3128 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3129 checkInt(this, value, offset, byteLength, maxBytes, 0)
3130 }
3131
3132 var mul = 1
3133 var i = 0
3134 this[offset] = value & 0xFF
3135 while (++i < byteLength && (mul *= 0x100)) {
3136 this[offset + i] = (value / mul) & 0xFF
3137 }
3138
3139 return offset + byteLength
3140}
3141
3142Buffer.prototype.writeUintBE =
3143Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
3144 value = +value
3145 offset = offset >>> 0
3146 byteLength = byteLength >>> 0
3147 if (!noAssert) {
3148 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3149 checkInt(this, value, offset, byteLength, maxBytes, 0)
3150 }
3151
3152 var i = byteLength - 1
3153 var mul = 1
3154 this[offset + i] = value & 0xFF
3155 while (--i >= 0 && (mul *= 0x100)) {
3156 this[offset + i] = (value / mul) & 0xFF
3157 }
3158
3159 return offset + byteLength
3160}
3161
3162Buffer.prototype.writeUint8 =
3163Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
3164 value = +value
3165 offset = offset >>> 0
3166 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
3167 this[offset] = (value & 0xff)
3168 return offset + 1
3169}
3170
3171Buffer.prototype.writeUint16LE =
3172Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
3173 value = +value
3174 offset = offset >>> 0
3175 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3176 this[offset] = (value & 0xff)
3177 this[offset + 1] = (value >>> 8)
3178 return offset + 2
3179}
3180
3181Buffer.prototype.writeUint16BE =
3182Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
3183 value = +value
3184 offset = offset >>> 0
3185 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3186 this[offset] = (value >>> 8)
3187 this[offset + 1] = (value & 0xff)
3188 return offset + 2
3189}
3190
3191Buffer.prototype.writeUint32LE =
3192Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
3193 value = +value
3194 offset = offset >>> 0
3195 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3196 this[offset + 3] = (value >>> 24)
3197 this[offset + 2] = (value >>> 16)
3198 this[offset + 1] = (value >>> 8)
3199 this[offset] = (value & 0xff)
3200 return offset + 4
3201}
3202
3203Buffer.prototype.writeUint32BE =
3204Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
3205 value = +value
3206 offset = offset >>> 0
3207 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3208 this[offset] = (value >>> 24)
3209 this[offset + 1] = (value >>> 16)
3210 this[offset + 2] = (value >>> 8)
3211 this[offset + 3] = (value & 0xff)
3212 return offset + 4
3213}
3214
3215Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
3216 value = +value
3217 offset = offset >>> 0
3218 if (!noAssert) {
3219 var limit = Math.pow(2, (8 * byteLength) - 1)
3220
3221 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3222 }
3223
3224 var i = 0
3225 var mul = 1
3226 var sub = 0
3227 this[offset] = value & 0xFF
3228 while (++i < byteLength && (mul *= 0x100)) {
3229 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
3230 sub = 1
3231 }
3232 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3233 }
3234
3235 return offset + byteLength
3236}
3237
3238Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
3239 value = +value
3240 offset = offset >>> 0
3241 if (!noAssert) {
3242 var limit = Math.pow(2, (8 * byteLength) - 1)
3243
3244 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3245 }
3246
3247 var i = byteLength - 1
3248 var mul = 1
3249 var sub = 0
3250 this[offset + i] = value & 0xFF
3251 while (--i >= 0 && (mul *= 0x100)) {
3252 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
3253 sub = 1
3254 }
3255 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3256 }
3257
3258 return offset + byteLength
3259}
3260
3261Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
3262 value = +value
3263 offset = offset >>> 0
3264 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
3265 if (value < 0) value = 0xff + value + 1
3266 this[offset] = (value & 0xff)
3267 return offset + 1
3268}
3269
3270Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
3271 value = +value
3272 offset = offset >>> 0
3273 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3274 this[offset] = (value & 0xff)
3275 this[offset + 1] = (value >>> 8)
3276 return offset + 2
3277}
3278
3279Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
3280 value = +value
3281 offset = offset >>> 0
3282 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3283 this[offset] = (value >>> 8)
3284 this[offset + 1] = (value & 0xff)
3285 return offset + 2
3286}
3287
3288Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
3289 value = +value
3290 offset = offset >>> 0
3291 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3292 this[offset] = (value & 0xff)
3293 this[offset + 1] = (value >>> 8)
3294 this[offset + 2] = (value >>> 16)
3295 this[offset + 3] = (value >>> 24)
3296 return offset + 4
3297}
3298
3299Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
3300 value = +value
3301 offset = offset >>> 0
3302 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3303 if (value < 0) value = 0xffffffff + value + 1
3304 this[offset] = (value >>> 24)
3305 this[offset + 1] = (value >>> 16)
3306 this[offset + 2] = (value >>> 8)
3307 this[offset + 3] = (value & 0xff)
3308 return offset + 4
3309}
3310
3311function checkIEEE754 (buf, value, offset, ext, max, min) {
3312 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3313 if (offset < 0) throw new RangeError('Index out of range')
3314}
3315
3316function writeFloat (buf, value, offset, littleEndian, noAssert) {
3317 value = +value
3318 offset = offset >>> 0
3319 if (!noAssert) {
3320 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
3321 }
3322 ieee754.write(buf, value, offset, littleEndian, 23, 4)
3323 return offset + 4
3324}
3325
3326Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
3327 return writeFloat(this, value, offset, true, noAssert)
3328}
3329
3330Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
3331 return writeFloat(this, value, offset, false, noAssert)
3332}
3333
3334function writeDouble (buf, value, offset, littleEndian, noAssert) {
3335 value = +value
3336 offset = offset >>> 0
3337 if (!noAssert) {
3338 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
3339 }
3340 ieee754.write(buf, value, offset, littleEndian, 52, 8)
3341 return offset + 8
3342}
3343
3344Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
3345 return writeDouble(this, value, offset, true, noAssert)
3346}
3347
3348Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
3349 return writeDouble(this, value, offset, false, noAssert)
3350}
3351
3352// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3353Buffer.prototype.copy = function copy (target, targetStart, start, end) {
3354 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
3355 if (!start) start = 0
3356 if (!end && end !== 0) end = this.length
3357 if (targetStart >= target.length) targetStart = target.length
3358 if (!targetStart) targetStart = 0
3359 if (end > 0 && end < start) end = start
3360
3361 // Copy 0 bytes; we're done
3362 if (end === start) return 0
3363 if (target.length === 0 || this.length === 0) return 0
3364
3365 // Fatal error conditions
3366 if (targetStart < 0) {
3367 throw new RangeError('targetStart out of bounds')
3368 }
3369 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
3370 if (end < 0) throw new RangeError('sourceEnd out of bounds')
3371
3372 // Are we oob?
3373 if (end > this.length) end = this.length
3374 if (target.length - targetStart < end - start) {
3375 end = target.length - targetStart + start
3376 }
3377
3378 var len = end - start
3379
3380 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
3381 // Use built-in when available, missing from IE11
3382 this.copyWithin(targetStart, start, end)
3383 } else {
3384 Uint8Array.prototype.set.call(
3385 target,
3386 this.subarray(start, end),
3387 targetStart
3388 )
3389 }
3390
3391 return len
3392}
3393
3394// Usage:
3395// buffer.fill(number[, offset[, end]])
3396// buffer.fill(buffer[, offset[, end]])
3397// buffer.fill(string[, offset[, end]][, encoding])
3398Buffer.prototype.fill = function fill (val, start, end, encoding) {
3399 // Handle string cases:
3400 if (typeof val === 'string') {
3401 if (typeof start === 'string') {
3402 encoding = start
3403 start = 0
3404 end = this.length
3405 } else if (typeof end === 'string') {
3406 encoding = end
3407 end = this.length
3408 }
3409 if (encoding !== undefined && typeof encoding !== 'string') {
3410 throw new TypeError('encoding must be a string')
3411 }
3412 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
3413 throw new TypeError('Unknown encoding: ' + encoding)
3414 }
3415 if (val.length === 1) {
3416 var code = val.charCodeAt(0)
3417 if ((encoding === 'utf8' && code < 128) ||
3418 encoding === 'latin1') {
3419 // Fast path: If `val` fits into a single byte, use that numeric value.
3420 val = code
3421 }
3422 }
3423 } else if (typeof val === 'number') {
3424 val = val & 255
3425 } else if (typeof val === 'boolean') {
3426 val = Number(val)
3427 }
3428
3429 // Invalid ranges are not set to a default, so can range check early.
3430 if (start < 0 || this.length < start || this.length < end) {
3431 throw new RangeError('Out of range index')
3432 }
3433
3434 if (end <= start) {
3435 return this
3436 }
3437
3438 start = start >>> 0
3439 end = end === undefined ? this.length : end >>> 0
3440
3441 if (!val) val = 0
3442
3443 var i
3444 if (typeof val === 'number') {
3445 for (i = start; i < end; ++i) {
3446 this[i] = val
3447 }
3448 } else {
3449 var bytes = Buffer.isBuffer(val)
3450 ? val
3451 : Buffer.from(val, encoding)
3452 var len = bytes.length
3453 if (len === 0) {
3454 throw new TypeError('The value "' + val +
3455 '" is invalid for argument "value"')
3456 }
3457 for (i = 0; i < end - start; ++i) {
3458 this[i + start] = bytes[i % len]
3459 }
3460 }
3461
3462 return this
3463}
3464
3465// HELPER FUNCTIONS
3466// ================
3467
3468var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3469
3470function base64clean (str) {
3471 // Node takes equal signs as end of the Base64 encoding
3472 str = str.split('=')[0]
3473 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3474 str = str.trim().replace(INVALID_BASE64_RE, '')
3475 // Node converts strings with length < 2 to ''
3476 if (str.length < 2) return ''
3477 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3478 while (str.length % 4 !== 0) {
3479 str = str + '='
3480 }
3481 return str
3482}
3483
3484function utf8ToBytes (string, units) {
3485 units = units || Infinity
3486 var codePoint
3487 var length = string.length
3488 var leadSurrogate = null
3489 var bytes = []
3490
3491 for (var i = 0; i < length; ++i) {
3492 codePoint = string.charCodeAt(i)
3493
3494 // is surrogate component
3495 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3496 // last char was a lead
3497 if (!leadSurrogate) {
3498 // no lead yet
3499 if (codePoint > 0xDBFF) {
3500 // unexpected trail
3501 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3502 continue
3503 } else if (i + 1 === length) {
3504 // unpaired lead
3505 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3506 continue
3507 }
3508
3509 // valid lead
3510 leadSurrogate = codePoint
3511
3512 continue
3513 }
3514
3515 // 2 leads in a row
3516 if (codePoint < 0xDC00) {
3517 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3518 leadSurrogate = codePoint
3519 continue
3520 }
3521
3522 // valid surrogate pair
3523 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3524 } else if (leadSurrogate) {
3525 // valid bmp char, but last char was a lead
3526 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3527 }
3528
3529 leadSurrogate = null
3530
3531 // encode utf8
3532 if (codePoint < 0x80) {
3533 if ((units -= 1) < 0) break
3534 bytes.push(codePoint)
3535 } else if (codePoint < 0x800) {
3536 if ((units -= 2) < 0) break
3537 bytes.push(
3538 codePoint >> 0x6 | 0xC0,
3539 codePoint & 0x3F | 0x80
3540 )
3541 } else if (codePoint < 0x10000) {
3542 if ((units -= 3) < 0) break
3543 bytes.push(
3544 codePoint >> 0xC | 0xE0,
3545 codePoint >> 0x6 & 0x3F | 0x80,
3546 codePoint & 0x3F | 0x80
3547 )
3548 } else if (codePoint < 0x110000) {
3549 if ((units -= 4) < 0) break
3550 bytes.push(
3551 codePoint >> 0x12 | 0xF0,
3552 codePoint >> 0xC & 0x3F | 0x80,
3553 codePoint >> 0x6 & 0x3F | 0x80,
3554 codePoint & 0x3F | 0x80
3555 )
3556 } else {
3557 throw new Error('Invalid code point')
3558 }
3559 }
3560
3561 return bytes
3562}
3563
3564function asciiToBytes (str) {
3565 var byteArray = []
3566 for (var i = 0; i < str.length; ++i) {
3567 // Node's code seems to be doing this and not & 0x7F..
3568 byteArray.push(str.charCodeAt(i) & 0xFF)
3569 }
3570 return byteArray
3571}
3572
3573function utf16leToBytes (str, units) {
3574 var c, hi, lo
3575 var byteArray = []
3576 for (var i = 0; i < str.length; ++i) {
3577 if ((units -= 2) < 0) break
3578
3579 c = str.charCodeAt(i)
3580 hi = c >> 8
3581 lo = c % 256
3582 byteArray.push(lo)
3583 byteArray.push(hi)
3584 }
3585
3586 return byteArray
3587}
3588
3589function base64ToBytes (str) {
3590 return base64.toByteArray(base64clean(str))
3591}
3592
3593function blitBuffer (src, dst, offset, length) {
3594 for (var i = 0; i < length; ++i) {
3595 if ((i + offset >= dst.length) || (i >= src.length)) break
3596 dst[i + offset] = src[i]
3597 }
3598 return i
3599}
3600
3601// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
3602// the `instanceof` check but they should be treated as of that type.
3603// See: https://github.com/feross/buffer/issues/166
3604function isInstance (obj, type) {
3605 return obj instanceof type ||
3606 (obj != null && obj.constructor != null && obj.constructor.name != null &&
3607 obj.constructor.name === type.name)
3608}
3609function numberIsNaN (obj) {
3610 // For IE11 support
3611 return obj !== obj // eslint-disable-line no-self-compare
3612}
3613
3614// Create lookup table for `toString('hex')`
3615// See: https://github.com/feross/buffer/issues/219
3616var hexSliceLookupTable = (function () {
3617 var alphabet = '0123456789abcdef'
3618 var table = new Array(256)
3619 for (var i = 0; i < 16; ++i) {
3620 var i16 = i * 16
3621 for (var j = 0; j < 16; ++j) {
3622 table[i16 + j] = alphabet[i] + alphabet[j]
3623 }
3624 }
3625 return table
3626})()
3627
3628}).call(this)}).call(this,_dereq_(13).Buffer)
3629},{"10":10,"13":13,"30":30}],14:[function(_dereq_,module,exports){
3630// Copyright Joyent, Inc. and other Node contributors.
3631//
3632// Permission is hereby granted, free of charge, to any person obtaining a
3633// copy of this software and associated documentation files (the
3634// "Software"), to deal in the Software without restriction, including
3635// without limitation the rights to use, copy, modify, merge, publish,
3636// distribute, sublicense, and/or sell copies of the Software, and to permit
3637// persons to whom the Software is furnished to do so, subject to the
3638// following conditions:
3639//
3640// The above copyright notice and this permission notice shall be included
3641// in all copies or substantial portions of the Software.
3642//
3643// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3644// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3645// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3646// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3647// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3648// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3649// USE OR OTHER DEALINGS IN THE SOFTWARE.
3650
3651// NOTE: These type checking functions intentionally don't use `instanceof`
3652// because it is fragile and can be easily faked with `Object.create()`.
3653
3654function isArray(arg) {
3655 if (Array.isArray) {
3656 return Array.isArray(arg);
3657 }
3658 return objectToString(arg) === '[object Array]';
3659}
3660exports.isArray = isArray;
3661
3662function isBoolean(arg) {
3663 return typeof arg === 'boolean';
3664}
3665exports.isBoolean = isBoolean;
3666
3667function isNull(arg) {
3668 return arg === null;
3669}
3670exports.isNull = isNull;
3671
3672function isNullOrUndefined(arg) {
3673 return arg == null;
3674}
3675exports.isNullOrUndefined = isNullOrUndefined;
3676
3677function isNumber(arg) {
3678 return typeof arg === 'number';
3679}
3680exports.isNumber = isNumber;
3681
3682function isString(arg) {
3683 return typeof arg === 'string';
3684}
3685exports.isString = isString;
3686
3687function isSymbol(arg) {
3688 return typeof arg === 'symbol';
3689}
3690exports.isSymbol = isSymbol;
3691
3692function isUndefined(arg) {
3693 return arg === void 0;
3694}
3695exports.isUndefined = isUndefined;
3696
3697function isRegExp(re) {
3698 return objectToString(re) === '[object RegExp]';
3699}
3700exports.isRegExp = isRegExp;
3701
3702function isObject(arg) {
3703 return typeof arg === 'object' && arg !== null;
3704}
3705exports.isObject = isObject;
3706
3707function isDate(d) {
3708 return objectToString(d) === '[object Date]';
3709}
3710exports.isDate = isDate;
3711
3712function isError(e) {
3713 return (objectToString(e) === '[object Error]' || e instanceof Error);
3714}
3715exports.isError = isError;
3716
3717function isFunction(arg) {
3718 return typeof arg === 'function';
3719}
3720exports.isFunction = isFunction;
3721
3722function isPrimitive(arg) {
3723 return arg === null ||
3724 typeof arg === 'boolean' ||
3725 typeof arg === 'number' ||
3726 typeof arg === 'string' ||
3727 typeof arg === 'symbol' || // ES6 symbol
3728 typeof arg === 'undefined';
3729}
3730exports.isPrimitive = isPrimitive;
3731
3732exports.isBuffer = _dereq_(13).Buffer.isBuffer;
3733
3734function objectToString(o) {
3735 return Object.prototype.toString.call(o);
3736}
3737
3738},{"13":13}],15:[function(_dereq_,module,exports){
3739var Buffer = _dereq_(13).Buffer
3740
3741var CHARS = '.PYFGCRLAOEUIDHTNSQJKXBMWVZ_pyfgcrlaoeuidhtnsqjkxbmwvz1234567890'
3742 .split('').sort().join('')
3743
3744module.exports = function (chars, exports) {
3745 chars = chars || CHARS
3746 exports = exports || {}
3747 if(chars.length !== 64) throw new Error('a base 64 encoding requires 64 chars')
3748
3749 var codeToIndex = new Buffer(128)
3750 codeToIndex.fill()
3751
3752 for(var i = 0; i < 64; i++) {
3753 var code = chars.charCodeAt(i)
3754 codeToIndex[code] = i
3755 }
3756
3757 exports.encode = function (data) {
3758 var s = '', l = data.length, hang = 0
3759 for(var i = 0; i < l; i++) {
3760 var v = data[i]
3761
3762 switch (i % 3) {
3763 case 0:
3764 s += chars[v >> 2]
3765 hang = (v & 3) << 4
3766 break;
3767 case 1:
3768 s += chars[hang | v >> 4]
3769 hang = (v & 0xf) << 2
3770 break;
3771 case 2:
3772 s += chars[hang | v >> 6]
3773 s += chars[v & 0x3f]
3774 hang = 0
3775 break;
3776 }
3777
3778 }
3779 if(l%3) s += chars[hang]
3780 return s
3781 }
3782 exports.decode = function (str) {
3783 var l = str.length, j = 0
3784 var b = new Buffer(~~((l/4)*3)), hang = 0
3785
3786 for(var i = 0; i < l; i++) {
3787 var v = codeToIndex[str.charCodeAt(i)]
3788
3789 switch (i % 4) {
3790 case 0:
3791 hang = v << 2;
3792 break;
3793 case 1:
3794 b[j++] = hang | v >> 4
3795 hang = (v << 4) & 0xff
3796 break;
3797 case 2:
3798 b[j++] = hang | v >> 2
3799 hang = (v << 6) & 0xff
3800 break;
3801 case 3:
3802 b[j++] = hang | v
3803 break;
3804 }
3805
3806 }
3807 return b
3808 }
3809 return exports
3810}
3811
3812module.exports(CHARS, module.exports)
3813
3814
3815},{"13":13}],16:[function(_dereq_,module,exports){
3816var AbstractIterator = _dereq_(21).AbstractIterator
3817var inherits = _dereq_(37)
3818
3819function DeferredIterator (db, options) {
3820 AbstractIterator.call(this, db)
3821
3822 this._options = options
3823 this._iterator = null
3824 this._operations = []
3825}
3826
3827inherits(DeferredIterator, AbstractIterator)
3828
3829DeferredIterator.prototype.setDb = function (db) {
3830 var it = this._iterator = db.iterator(this._options)
3831 this._operations.forEach(function (op) {
3832 it[op.method].apply(it, op.args)
3833 })
3834}
3835
3836DeferredIterator.prototype._operation = function (method, args) {
3837 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
3838 this._operations.push({ method: method, args: args })
3839}
3840
3841'next end'.split(' ').forEach(function (m) {
3842 DeferredIterator.prototype['_' + m] = function () {
3843 this._operation(m, arguments)
3844 }
3845})
3846
3847// Must defer seek() rather than _seek() because it requires db._serializeKey to be available
3848DeferredIterator.prototype.seek = function () {
3849 this._operation('seek', arguments)
3850}
3851
3852module.exports = DeferredIterator
3853
3854},{"21":21,"37":37}],17:[function(_dereq_,module,exports){
3855var AbstractLevelDOWN = _dereq_(21).AbstractLevelDOWN
3856var inherits = _dereq_(37)
3857var DeferredIterator = _dereq_(16)
3858var deferrables = 'put get del batch clear'.split(' ')
3859var optionalDeferrables = 'approximateSize compactRange'.split(' ')
3860
3861function DeferredLevelDOWN (db) {
3862 AbstractLevelDOWN.call(this, db.supports || {})
3863
3864 // TODO (future major): remove this fallback; db must have manifest that
3865 // declares approximateSize and compactRange in additionalMethods.
3866 optionalDeferrables.forEach(function (m) {
3867 if (typeof db[m] === 'function' && !this.supports.additionalMethods[m]) {
3868 this.supports.additionalMethods[m] = true
3869 }
3870 }, this)
3871
3872 this._db = db
3873 this._operations = []
3874 closed(this)
3875}
3876
3877inherits(DeferredLevelDOWN, AbstractLevelDOWN)
3878
3879DeferredLevelDOWN.prototype.type = 'deferred-leveldown'
3880
3881DeferredLevelDOWN.prototype._open = function (options, callback) {
3882 var self = this
3883
3884 this._db.open(options, function (err) {
3885 if (err) return callback(err)
3886
3887 self._operations.forEach(function (op) {
3888 if (op.iterator) {
3889 op.iterator.setDb(self._db)
3890 } else {
3891 self._db[op.method].apply(self._db, op.args)
3892 }
3893 })
3894 self._operations = []
3895
3896 open(self)
3897 callback()
3898 })
3899}
3900
3901DeferredLevelDOWN.prototype._close = function (callback) {
3902 var self = this
3903
3904 this._db.close(function (err) {
3905 if (err) return callback(err)
3906 closed(self)
3907 callback()
3908 })
3909}
3910
3911function open (self) {
3912 deferrables.concat('iterator').forEach(function (m) {
3913 self['_' + m] = function () {
3914 return this._db[m].apply(this._db, arguments)
3915 }
3916 })
3917 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3918 self[m] = function () {
3919 return this._db[m].apply(this._db, arguments)
3920 }
3921 })
3922}
3923
3924function closed (self) {
3925 deferrables.forEach(function (m) {
3926 self['_' + m] = function () {
3927 this._operations.push({ method: m, args: arguments })
3928 }
3929 })
3930 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3931 self[m] = function () {
3932 this._operations.push({ method: m, args: arguments })
3933 }
3934 })
3935 self._iterator = function (options) {
3936 var it = new DeferredIterator(self, options)
3937 this._operations.push({ iterator: it })
3938 return it
3939 }
3940}
3941
3942DeferredLevelDOWN.prototype._serializeKey = function (key) {
3943 return key
3944}
3945
3946DeferredLevelDOWN.prototype._serializeValue = function (value) {
3947 return value
3948}
3949
3950module.exports = DeferredLevelDOWN
3951module.exports.DeferredIterator = DeferredIterator
3952
3953},{"16":16,"21":21,"37":37}],18:[function(_dereq_,module,exports){
3954var nextTick = _dereq_(22)
3955
3956function AbstractChainedBatch (db) {
3957 if (typeof db !== 'object' || db === null) {
3958 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3959 }
3960
3961 this.db = db
3962 this._operations = []
3963 this._written = false
3964}
3965
3966AbstractChainedBatch.prototype._checkWritten = function () {
3967 if (this._written) {
3968 throw new Error('write() already called on this batch')
3969 }
3970}
3971
3972AbstractChainedBatch.prototype.put = function (key, value) {
3973 this._checkWritten()
3974
3975 var err = this.db._checkKey(key) || this.db._checkValue(value)
3976 if (err) throw err
3977
3978 key = this.db._serializeKey(key)
3979 value = this.db._serializeValue(value)
3980
3981 this._put(key, value)
3982
3983 return this
3984}
3985
3986AbstractChainedBatch.prototype._put = function (key, value) {
3987 this._operations.push({ type: 'put', key: key, value: value })
3988}
3989
3990AbstractChainedBatch.prototype.del = function (key) {
3991 this._checkWritten()
3992
3993 var err = this.db._checkKey(key)
3994 if (err) throw err
3995
3996 key = this.db._serializeKey(key)
3997 this._del(key)
3998
3999 return this
4000}
4001
4002AbstractChainedBatch.prototype._del = function (key) {
4003 this._operations.push({ type: 'del', key: key })
4004}
4005
4006AbstractChainedBatch.prototype.clear = function () {
4007 this._checkWritten()
4008 this._clear()
4009
4010 return this
4011}
4012
4013AbstractChainedBatch.prototype._clear = function () {
4014 this._operations = []
4015}
4016
4017AbstractChainedBatch.prototype.write = function (options, callback) {
4018 this._checkWritten()
4019
4020 if (typeof options === 'function') { callback = options }
4021 if (typeof callback !== 'function') {
4022 throw new Error('write() requires a callback argument')
4023 }
4024 if (typeof options !== 'object' || options === null) {
4025 options = {}
4026 }
4027
4028 this._written = true
4029 this._write(options, callback)
4030}
4031
4032AbstractChainedBatch.prototype._write = function (options, callback) {
4033 this.db._batch(this._operations, options, callback)
4034}
4035
4036// Expose browser-compatible nextTick for dependents
4037AbstractChainedBatch.prototype._nextTick = nextTick
4038
4039module.exports = AbstractChainedBatch
4040
4041},{"22":22}],19:[function(_dereq_,module,exports){
4042var nextTick = _dereq_(22)
4043
4044function AbstractIterator (db) {
4045 if (typeof db !== 'object' || db === null) {
4046 throw new TypeError('First argument must be an abstract-leveldown compliant store')
4047 }
4048
4049 this.db = db
4050 this._ended = false
4051 this._nexting = false
4052}
4053
4054AbstractIterator.prototype.next = function (callback) {
4055 var self = this
4056
4057 if (typeof callback !== 'function') {
4058 throw new Error('next() requires a callback argument')
4059 }
4060
4061 if (self._ended) {
4062 nextTick(callback, new Error('cannot call next() after end()'))
4063 return self
4064 }
4065
4066 if (self._nexting) {
4067 nextTick(callback, new Error('cannot call next() before previous next() has completed'))
4068 return self
4069 }
4070
4071 self._nexting = true
4072 self._next(function () {
4073 self._nexting = false
4074 callback.apply(null, arguments)
4075 })
4076
4077 return self
4078}
4079
4080AbstractIterator.prototype._next = function (callback) {
4081 nextTick(callback)
4082}
4083
4084AbstractIterator.prototype.seek = function (target) {
4085 if (this._ended) {
4086 throw new Error('cannot call seek() after end()')
4087 }
4088 if (this._nexting) {
4089 throw new Error('cannot call seek() before next() has completed')
4090 }
4091
4092 target = this.db._serializeKey(target)
4093 this._seek(target)
4094}
4095
4096AbstractIterator.prototype._seek = function (target) {}
4097
4098AbstractIterator.prototype.end = function (callback) {
4099 if (typeof callback !== 'function') {
4100 throw new Error('end() requires a callback argument')
4101 }
4102
4103 if (this._ended) {
4104 return nextTick(callback, new Error('end() already called on iterator'))
4105 }
4106
4107 this._ended = true
4108 this._end(callback)
4109}
4110
4111AbstractIterator.prototype._end = function (callback) {
4112 nextTick(callback)
4113}
4114
4115// Expose browser-compatible nextTick for dependents
4116AbstractIterator.prototype._nextTick = nextTick
4117
4118module.exports = AbstractIterator
4119
4120},{"22":22}],20:[function(_dereq_,module,exports){
4121var xtend = _dereq_(141)
4122var supports = _dereq_(58)
4123var Buffer = _dereq_(13).Buffer
4124var AbstractIterator = _dereq_(19)
4125var AbstractChainedBatch = _dereq_(18)
4126var nextTick = _dereq_(22)
4127var hasOwnProperty = Object.prototype.hasOwnProperty
4128var rangeOptions = 'start end gt gte lt lte'.split(' ')
4129
4130function AbstractLevelDOWN (manifest) {
4131 this.status = 'new'
4132
4133 // TODO (next major): make this mandatory
4134 this.supports = supports(manifest, {
4135 status: true
4136 })
4137}
4138
4139AbstractLevelDOWN.prototype.open = function (options, callback) {
4140 var self = this
4141 var oldStatus = this.status
4142
4143 if (typeof options === 'function') callback = options
4144
4145 if (typeof callback !== 'function') {
4146 throw new Error('open() requires a callback argument')
4147 }
4148
4149 if (typeof options !== 'object' || options === null) options = {}
4150
4151 options.createIfMissing = options.createIfMissing !== false
4152 options.errorIfExists = !!options.errorIfExists
4153
4154 this.status = 'opening'
4155 this._open(options, function (err) {
4156 if (err) {
4157 self.status = oldStatus
4158 return callback(err)
4159 }
4160 self.status = 'open'
4161 callback()
4162 })
4163}
4164
4165AbstractLevelDOWN.prototype._open = function (options, callback) {
4166 nextTick(callback)
4167}
4168
4169AbstractLevelDOWN.prototype.close = function (callback) {
4170 var self = this
4171 var oldStatus = this.status
4172
4173 if (typeof callback !== 'function') {
4174 throw new Error('close() requires a callback argument')
4175 }
4176
4177 this.status = 'closing'
4178 this._close(function (err) {
4179 if (err) {
4180 self.status = oldStatus
4181 return callback(err)
4182 }
4183 self.status = 'closed'
4184 callback()
4185 })
4186}
4187
4188AbstractLevelDOWN.prototype._close = function (callback) {
4189 nextTick(callback)
4190}
4191
4192AbstractLevelDOWN.prototype.get = function (key, options, callback) {
4193 if (typeof options === 'function') callback = options
4194
4195 if (typeof callback !== 'function') {
4196 throw new Error('get() requires a callback argument')
4197 }
4198
4199 var err = this._checkKey(key)
4200 if (err) return nextTick(callback, err)
4201
4202 key = this._serializeKey(key)
4203
4204 if (typeof options !== 'object' || options === null) options = {}
4205
4206 options.asBuffer = options.asBuffer !== false
4207
4208 this._get(key, options, callback)
4209}
4210
4211AbstractLevelDOWN.prototype._get = function (key, options, callback) {
4212 nextTick(function () { callback(new Error('NotFound')) })
4213}
4214
4215AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
4216 if (typeof options === 'function') callback = options
4217
4218 if (typeof callback !== 'function') {
4219 throw new Error('put() requires a callback argument')
4220 }
4221
4222 var err = this._checkKey(key) || this._checkValue(value)
4223 if (err) return nextTick(callback, err)
4224
4225 key = this._serializeKey(key)
4226 value = this._serializeValue(value)
4227
4228 if (typeof options !== 'object' || options === null) options = {}
4229
4230 this._put(key, value, options, callback)
4231}
4232
4233AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
4234 nextTick(callback)
4235}
4236
4237AbstractLevelDOWN.prototype.del = function (key, options, callback) {
4238 if (typeof options === 'function') callback = options
4239
4240 if (typeof callback !== 'function') {
4241 throw new Error('del() requires a callback argument')
4242 }
4243
4244 var err = this._checkKey(key)
4245 if (err) return nextTick(callback, err)
4246
4247 key = this._serializeKey(key)
4248
4249 if (typeof options !== 'object' || options === null) options = {}
4250
4251 this._del(key, options, callback)
4252}
4253
4254AbstractLevelDOWN.prototype._del = function (key, options, callback) {
4255 nextTick(callback)
4256}
4257
4258AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
4259 if (!arguments.length) return this._chainedBatch()
4260
4261 if (typeof options === 'function') callback = options
4262
4263 if (typeof array === 'function') callback = array
4264
4265 if (typeof callback !== 'function') {
4266 throw new Error('batch(array) requires a callback argument')
4267 }
4268
4269 if (!Array.isArray(array)) {
4270 return nextTick(callback, new Error('batch(array) requires an array argument'))
4271 }
4272
4273 if (array.length === 0) {
4274 return nextTick(callback)
4275 }
4276
4277 if (typeof options !== 'object' || options === null) options = {}
4278
4279 var serialized = new Array(array.length)
4280
4281 for (var i = 0; i < array.length; i++) {
4282 if (typeof array[i] !== 'object' || array[i] === null) {
4283 return nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
4284 }
4285
4286 var e = xtend(array[i])
4287
4288 if (e.type !== 'put' && e.type !== 'del') {
4289 return nextTick(callback, new Error("`type` must be 'put' or 'del'"))
4290 }
4291
4292 var err = this._checkKey(e.key)
4293 if (err) return nextTick(callback, err)
4294
4295 e.key = this._serializeKey(e.key)
4296
4297 if (e.type === 'put') {
4298 var valueErr = this._checkValue(e.value)
4299 if (valueErr) return nextTick(callback, valueErr)
4300
4301 e.value = this._serializeValue(e.value)
4302 }
4303
4304 serialized[i] = e
4305 }
4306
4307 this._batch(serialized, options, callback)
4308}
4309
4310AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
4311 nextTick(callback)
4312}
4313
4314AbstractLevelDOWN.prototype.clear = function (options, callback) {
4315 if (typeof options === 'function') {
4316 callback = options
4317 } else if (typeof callback !== 'function') {
4318 throw new Error('clear() requires a callback argument')
4319 }
4320
4321 options = cleanRangeOptions(this, options)
4322 options.reverse = !!options.reverse
4323 options.limit = 'limit' in options ? options.limit : -1
4324
4325 this._clear(options, callback)
4326}
4327
4328AbstractLevelDOWN.prototype._clear = function (options, callback) {
4329 // Avoid setupIteratorOptions, would serialize range options a second time.
4330 options.keys = true
4331 options.values = false
4332 options.keyAsBuffer = true
4333 options.valueAsBuffer = true
4334
4335 var iterator = this._iterator(options)
4336 var emptyOptions = {}
4337 var self = this
4338
4339 var next = function (err) {
4340 if (err) {
4341 return iterator.end(function () {
4342 callback(err)
4343 })
4344 }
4345
4346 iterator.next(function (err, key) {
4347 if (err) return next(err)
4348 if (key === undefined) return iterator.end(callback)
4349
4350 // This could be optimized by using a batch, but the default _clear
4351 // is not meant to be fast. Implementations have more room to optimize
4352 // if they override _clear. Note: using _del bypasses key serialization.
4353 self._del(key, emptyOptions, next)
4354 })
4355 }
4356
4357 next()
4358}
4359
4360AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
4361 options = cleanRangeOptions(this, options)
4362
4363 options.reverse = !!options.reverse
4364 options.keys = options.keys !== false
4365 options.values = options.values !== false
4366 options.limit = 'limit' in options ? options.limit : -1
4367 options.keyAsBuffer = options.keyAsBuffer !== false
4368 options.valueAsBuffer = options.valueAsBuffer !== false
4369
4370 return options
4371}
4372
4373function cleanRangeOptions (db, options) {
4374 var result = {}
4375
4376 for (var k in options) {
4377 if (!hasOwnProperty.call(options, k)) continue
4378
4379 var opt = options[k]
4380
4381 if (isRangeOption(k)) {
4382 // Note that we don't reject nullish and empty options here. While
4383 // those types are invalid as keys, they are valid as range options.
4384 opt = db._serializeKey(opt)
4385 }
4386
4387 result[k] = opt
4388 }
4389
4390 return result
4391}
4392
4393function isRangeOption (k) {
4394 return rangeOptions.indexOf(k) !== -1
4395}
4396
4397AbstractLevelDOWN.prototype.iterator = function (options) {
4398 if (typeof options !== 'object' || options === null) options = {}
4399 options = this._setupIteratorOptions(options)
4400 return this._iterator(options)
4401}
4402
4403AbstractLevelDOWN.prototype._iterator = function (options) {
4404 return new AbstractIterator(this)
4405}
4406
4407AbstractLevelDOWN.prototype._chainedBatch = function () {
4408 return new AbstractChainedBatch(this)
4409}
4410
4411AbstractLevelDOWN.prototype._serializeKey = function (key) {
4412 return key
4413}
4414
4415AbstractLevelDOWN.prototype._serializeValue = function (value) {
4416 return value
4417}
4418
4419AbstractLevelDOWN.prototype._checkKey = function (key) {
4420 if (key === null || key === undefined) {
4421 return new Error('key cannot be `null` or `undefined`')
4422 } else if (Buffer.isBuffer(key) && key.length === 0) {
4423 return new Error('key cannot be an empty Buffer')
4424 } else if (key === '') {
4425 return new Error('key cannot be an empty String')
4426 } else if (Array.isArray(key) && key.length === 0) {
4427 return new Error('key cannot be an empty Array')
4428 }
4429}
4430
4431AbstractLevelDOWN.prototype._checkValue = function (value) {
4432 if (value === null || value === undefined) {
4433 return new Error('value cannot be `null` or `undefined`')
4434 }
4435}
4436
4437// Expose browser-compatible nextTick for dependents
4438AbstractLevelDOWN.prototype._nextTick = nextTick
4439
4440module.exports = AbstractLevelDOWN
4441
4442},{"13":13,"141":141,"18":18,"19":19,"22":22,"58":58}],21:[function(_dereq_,module,exports){
4443exports.AbstractLevelDOWN = _dereq_(20)
4444exports.AbstractIterator = _dereq_(19)
4445exports.AbstractChainedBatch = _dereq_(18)
4446
4447},{"18":18,"19":19,"20":20}],22:[function(_dereq_,module,exports){
4448module.exports = _dereq_(31)
4449
4450},{"31":31}],23:[function(_dereq_,module,exports){
4451/**
4452 * Copyright (c) 2013 Petka Antonov
4453 *
4454 * Permission is hereby granted, free of charge, to any person obtaining a copy
4455 * of this software and associated documentation files (the "Software"), to deal
4456 * in the Software without restriction, including without limitation the rights
4457 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4458 * copies of the Software, and to permit persons to whom the Software is
4459 * furnished to do so, subject to the following conditions:</p>
4460 *
4461 * The above copyright notice and this permission notice shall be included in
4462 * all copies or substantial portions of the Software.
4463 *
4464 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4465 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4466 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4467 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4468 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4469 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4470 * THE SOFTWARE.
4471 */
4472"use strict";
4473function Deque(capacity) {
4474 this._capacity = getCapacity(capacity);
4475 this._length = 0;
4476 this._front = 0;
4477 if (isArray(capacity)) {
4478 var len = capacity.length;
4479 for (var i = 0; i < len; ++i) {
4480 this[i] = capacity[i];
4481 }
4482 this._length = len;
4483 }
4484}
4485
4486Deque.prototype.toArray = function Deque$toArray() {
4487 var len = this._length;
4488 var ret = new Array(len);
4489 var front = this._front;
4490 var capacity = this._capacity;
4491 for (var j = 0; j < len; ++j) {
4492 ret[j] = this[(front + j) & (capacity - 1)];
4493 }
4494 return ret;
4495};
4496
4497Deque.prototype.push = function Deque$push(item) {
4498 var argsLength = arguments.length;
4499 var length = this._length;
4500 if (argsLength > 1) {
4501 var capacity = this._capacity;
4502 if (length + argsLength > capacity) {
4503 for (var i = 0; i < argsLength; ++i) {
4504 this._checkCapacity(length + 1);
4505 var j = (this._front + length) & (this._capacity - 1);
4506 this[j] = arguments[i];
4507 length++;
4508 this._length = length;
4509 }
4510 return length;
4511 }
4512 else {
4513 var j = this._front;
4514 for (var i = 0; i < argsLength; ++i) {
4515 this[(j + length) & (capacity - 1)] = arguments[i];
4516 j++;
4517 }
4518 this._length = length + argsLength;
4519 return length + argsLength;
4520 }
4521
4522 }
4523
4524 if (argsLength === 0) return length;
4525
4526 this._checkCapacity(length + 1);
4527 var i = (this._front + length) & (this._capacity - 1);
4528 this[i] = item;
4529 this._length = length + 1;
4530 return length + 1;
4531};
4532
4533Deque.prototype.pop = function Deque$pop() {
4534 var length = this._length;
4535 if (length === 0) {
4536 return void 0;
4537 }
4538 var i = (this._front + length - 1) & (this._capacity - 1);
4539 var ret = this[i];
4540 this[i] = void 0;
4541 this._length = length - 1;
4542 return ret;
4543};
4544
4545Deque.prototype.shift = function Deque$shift() {
4546 var length = this._length;
4547 if (length === 0) {
4548 return void 0;
4549 }
4550 var front = this._front;
4551 var ret = this[front];
4552 this[front] = void 0;
4553 this._front = (front + 1) & (this._capacity - 1);
4554 this._length = length - 1;
4555 return ret;
4556};
4557
4558Deque.prototype.unshift = function Deque$unshift(item) {
4559 var length = this._length;
4560 var argsLength = arguments.length;
4561
4562
4563 if (argsLength > 1) {
4564 var capacity = this._capacity;
4565 if (length + argsLength > capacity) {
4566 for (var i = argsLength - 1; i >= 0; i--) {
4567 this._checkCapacity(length + 1);
4568 var capacity = this._capacity;
4569 var j = (((( this._front - 1 ) &
4570 ( capacity - 1) ) ^ capacity ) - capacity );
4571 this[j] = arguments[i];
4572 length++;
4573 this._length = length;
4574 this._front = j;
4575 }
4576 return length;
4577 }
4578 else {
4579 var front = this._front;
4580 for (var i = argsLength - 1; i >= 0; i--) {
4581 var j = (((( front - 1 ) &
4582 ( capacity - 1) ) ^ capacity ) - capacity );
4583 this[j] = arguments[i];
4584 front = j;
4585 }
4586 this._front = front;
4587 this._length = length + argsLength;
4588 return length + argsLength;
4589 }
4590 }
4591
4592 if (argsLength === 0) return length;
4593
4594 this._checkCapacity(length + 1);
4595 var capacity = this._capacity;
4596 var i = (((( this._front - 1 ) &
4597 ( capacity - 1) ) ^ capacity ) - capacity );
4598 this[i] = item;
4599 this._length = length + 1;
4600 this._front = i;
4601 return length + 1;
4602};
4603
4604Deque.prototype.peekBack = function Deque$peekBack() {
4605 var length = this._length;
4606 if (length === 0) {
4607 return void 0;
4608 }
4609 var index = (this._front + length - 1) & (this._capacity - 1);
4610 return this[index];
4611};
4612
4613Deque.prototype.peekFront = function Deque$peekFront() {
4614 if (this._length === 0) {
4615 return void 0;
4616 }
4617 return this[this._front];
4618};
4619
4620Deque.prototype.get = function Deque$get(index) {
4621 var i = index;
4622 if ((i !== (i | 0))) {
4623 return void 0;
4624 }
4625 var len = this._length;
4626 if (i < 0) {
4627 i = i + len;
4628 }
4629 if (i < 0 || i >= len) {
4630 return void 0;
4631 }
4632 return this[(this._front + i) & (this._capacity - 1)];
4633};
4634
4635Deque.prototype.isEmpty = function Deque$isEmpty() {
4636 return this._length === 0;
4637};
4638
4639Deque.prototype.clear = function Deque$clear() {
4640 var len = this._length;
4641 var front = this._front;
4642 var capacity = this._capacity;
4643 for (var j = 0; j < len; ++j) {
4644 this[(front + j) & (capacity - 1)] = void 0;
4645 }
4646 this._length = 0;
4647 this._front = 0;
4648};
4649
4650Deque.prototype.toString = function Deque$toString() {
4651 return this.toArray().toString();
4652};
4653
4654Deque.prototype.valueOf = Deque.prototype.toString;
4655Deque.prototype.removeFront = Deque.prototype.shift;
4656Deque.prototype.removeBack = Deque.prototype.pop;
4657Deque.prototype.insertFront = Deque.prototype.unshift;
4658Deque.prototype.insertBack = Deque.prototype.push;
4659Deque.prototype.enqueue = Deque.prototype.push;
4660Deque.prototype.dequeue = Deque.prototype.shift;
4661Deque.prototype.toJSON = Deque.prototype.toArray;
4662
4663Object.defineProperty(Deque.prototype, "length", {
4664 get: function() {
4665 return this._length;
4666 },
4667 set: function() {
4668 throw new RangeError("");
4669 }
4670});
4671
4672Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
4673 if (this._capacity < size) {
4674 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
4675 }
4676};
4677
4678Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
4679 var oldCapacity = this._capacity;
4680 this._capacity = capacity;
4681 var front = this._front;
4682 var length = this._length;
4683 if (front + length > oldCapacity) {
4684 var moveItemsCount = (front + length) & (oldCapacity - 1);
4685 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4686 }
4687};
4688
4689
4690var isArray = Array.isArray;
4691
4692function arrayMove(src, srcIndex, dst, dstIndex, len) {
4693 for (var j = 0; j < len; ++j) {
4694 dst[j + dstIndex] = src[j + srcIndex];
4695 src[j + srcIndex] = void 0;
4696 }
4697}
4698
4699function pow2AtLeast(n) {
4700 n = n >>> 0;
4701 n = n - 1;
4702 n = n | (n >> 1);
4703 n = n | (n >> 2);
4704 n = n | (n >> 4);
4705 n = n | (n >> 8);
4706 n = n | (n >> 16);
4707 return n + 1;
4708}
4709
4710function getCapacity(capacity) {
4711 if (typeof capacity !== "number") {
4712 if (isArray(capacity)) {
4713 capacity = capacity.length;
4714 }
4715 else {
4716 return 16;
4717 }
4718 }
4719 return pow2AtLeast(
4720 Math.min(
4721 Math.max(16, capacity), 1073741824)
4722 );
4723}
4724
4725module.exports = Deque;
4726
4727},{}],24:[function(_dereq_,module,exports){
4728var prr = _dereq_(74)
4729
4730function init (type, message, cause) {
4731 if (!!message && typeof message != 'string') {
4732 message = message.message || message.name
4733 }
4734 prr(this, {
4735 type : type
4736 , name : type
4737 // can be passed just a 'cause'
4738 , cause : typeof message != 'string' ? message : cause
4739 , message : message
4740 }, 'ewr')
4741}
4742
4743// generic prototype, not intended to be actually used - helpful for `instanceof`
4744function CustomError (message, cause) {
4745 Error.call(this)
4746 if (Error.captureStackTrace)
4747 Error.captureStackTrace(this, this.constructor)
4748 init.call(this, 'CustomError', message, cause)
4749}
4750
4751CustomError.prototype = new Error()
4752
4753function createError (errno, type, proto) {
4754 var err = function (message, cause) {
4755 init.call(this, type, message, cause)
4756 //TODO: the specificity here is stupid, errno should be available everywhere
4757 if (type == 'FilesystemError') {
4758 this.code = this.cause.code
4759 this.path = this.cause.path
4760 this.errno = this.cause.errno
4761 this.message =
4762 (errno.errno[this.cause.errno]
4763 ? errno.errno[this.cause.errno].description
4764 : this.cause.message)
4765 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
4766 }
4767 Error.call(this)
4768 if (Error.captureStackTrace)
4769 Error.captureStackTrace(this, err)
4770 }
4771 err.prototype = !!proto ? new proto() : new CustomError()
4772 return err
4773}
4774
4775module.exports = function (errno) {
4776 var ce = function (type, proto) {
4777 return createError(errno, type, proto)
4778 }
4779 return {
4780 CustomError : CustomError
4781 , FilesystemError : ce('FilesystemError')
4782 , createError : ce
4783 }
4784}
4785
4786},{"74":74}],25:[function(_dereq_,module,exports){
4787var all = module.exports.all = [
4788 {
4789 errno: -2,
4790 code: 'ENOENT',
4791 description: 'no such file or directory'
4792 },
4793 {
4794 errno: -1,
4795 code: 'UNKNOWN',
4796 description: 'unknown error'
4797 },
4798 {
4799 errno: 0,
4800 code: 'OK',
4801 description: 'success'
4802 },
4803 {
4804 errno: 1,
4805 code: 'EOF',
4806 description: 'end of file'
4807 },
4808 {
4809 errno: 2,
4810 code: 'EADDRINFO',
4811 description: 'getaddrinfo error'
4812 },
4813 {
4814 errno: 3,
4815 code: 'EACCES',
4816 description: 'permission denied'
4817 },
4818 {
4819 errno: 4,
4820 code: 'EAGAIN',
4821 description: 'resource temporarily unavailable'
4822 },
4823 {
4824 errno: 5,
4825 code: 'EADDRINUSE',
4826 description: 'address already in use'
4827 },
4828 {
4829 errno: 6,
4830 code: 'EADDRNOTAVAIL',
4831 description: 'address not available'
4832 },
4833 {
4834 errno: 7,
4835 code: 'EAFNOSUPPORT',
4836 description: 'address family not supported'
4837 },
4838 {
4839 errno: 8,
4840 code: 'EALREADY',
4841 description: 'connection already in progress'
4842 },
4843 {
4844 errno: 9,
4845 code: 'EBADF',
4846 description: 'bad file descriptor'
4847 },
4848 {
4849 errno: 10,
4850 code: 'EBUSY',
4851 description: 'resource busy or locked'
4852 },
4853 {
4854 errno: 11,
4855 code: 'ECONNABORTED',
4856 description: 'software caused connection abort'
4857 },
4858 {
4859 errno: 12,
4860 code: 'ECONNREFUSED',
4861 description: 'connection refused'
4862 },
4863 {
4864 errno: 13,
4865 code: 'ECONNRESET',
4866 description: 'connection reset by peer'
4867 },
4868 {
4869 errno: 14,
4870 code: 'EDESTADDRREQ',
4871 description: 'destination address required'
4872 },
4873 {
4874 errno: 15,
4875 code: 'EFAULT',
4876 description: 'bad address in system call argument'
4877 },
4878 {
4879 errno: 16,
4880 code: 'EHOSTUNREACH',
4881 description: 'host is unreachable'
4882 },
4883 {
4884 errno: 17,
4885 code: 'EINTR',
4886 description: 'interrupted system call'
4887 },
4888 {
4889 errno: 18,
4890 code: 'EINVAL',
4891 description: 'invalid argument'
4892 },
4893 {
4894 errno: 19,
4895 code: 'EISCONN',
4896 description: 'socket is already connected'
4897 },
4898 {
4899 errno: 20,
4900 code: 'EMFILE',
4901 description: 'too many open files'
4902 },
4903 {
4904 errno: 21,
4905 code: 'EMSGSIZE',
4906 description: 'message too long'
4907 },
4908 {
4909 errno: 22,
4910 code: 'ENETDOWN',
4911 description: 'network is down'
4912 },
4913 {
4914 errno: 23,
4915 code: 'ENETUNREACH',
4916 description: 'network is unreachable'
4917 },
4918 {
4919 errno: 24,
4920 code: 'ENFILE',
4921 description: 'file table overflow'
4922 },
4923 {
4924 errno: 25,
4925 code: 'ENOBUFS',
4926 description: 'no buffer space available'
4927 },
4928 {
4929 errno: 26,
4930 code: 'ENOMEM',
4931 description: 'not enough memory'
4932 },
4933 {
4934 errno: 27,
4935 code: 'ENOTDIR',
4936 description: 'not a directory'
4937 },
4938 {
4939 errno: 28,
4940 code: 'EISDIR',
4941 description: 'illegal operation on a directory'
4942 },
4943 {
4944 errno: 29,
4945 code: 'ENONET',
4946 description: 'machine is not on the network'
4947 },
4948 {
4949 errno: 31,
4950 code: 'ENOTCONN',
4951 description: 'socket is not connected'
4952 },
4953 {
4954 errno: 32,
4955 code: 'ENOTSOCK',
4956 description: 'socket operation on non-socket'
4957 },
4958 {
4959 errno: 33,
4960 code: 'ENOTSUP',
4961 description: 'operation not supported on socket'
4962 },
4963 {
4964 errno: 34,
4965 code: 'ENOENT',
4966 description: 'no such file or directory'
4967 },
4968 {
4969 errno: 35,
4970 code: 'ENOSYS',
4971 description: 'function not implemented'
4972 },
4973 {
4974 errno: 36,
4975 code: 'EPIPE',
4976 description: 'broken pipe'
4977 },
4978 {
4979 errno: 37,
4980 code: 'EPROTO',
4981 description: 'protocol error'
4982 },
4983 {
4984 errno: 38,
4985 code: 'EPROTONOSUPPORT',
4986 description: 'protocol not supported'
4987 },
4988 {
4989 errno: 39,
4990 code: 'EPROTOTYPE',
4991 description: 'protocol wrong type for socket'
4992 },
4993 {
4994 errno: 40,
4995 code: 'ETIMEDOUT',
4996 description: 'connection timed out'
4997 },
4998 {
4999 errno: 41,
5000 code: 'ECHARSET',
5001 description: 'invalid Unicode character'
5002 },
5003 {
5004 errno: 42,
5005 code: 'EAIFAMNOSUPPORT',
5006 description: 'address family for hostname not supported'
5007 },
5008 {
5009 errno: 44,
5010 code: 'EAISERVICE',
5011 description: 'servname not supported for ai_socktype'
5012 },
5013 {
5014 errno: 45,
5015 code: 'EAISOCKTYPE',
5016 description: 'ai_socktype not supported'
5017 },
5018 {
5019 errno: 46,
5020 code: 'ESHUTDOWN',
5021 description: 'cannot send after transport endpoint shutdown'
5022 },
5023 {
5024 errno: 47,
5025 code: 'EEXIST',
5026 description: 'file already exists'
5027 },
5028 {
5029 errno: 48,
5030 code: 'ESRCH',
5031 description: 'no such process'
5032 },
5033 {
5034 errno: 49,
5035 code: 'ENAMETOOLONG',
5036 description: 'name too long'
5037 },
5038 {
5039 errno: 50,
5040 code: 'EPERM',
5041 description: 'operation not permitted'
5042 },
5043 {
5044 errno: 51,
5045 code: 'ELOOP',
5046 description: 'too many symbolic links encountered'
5047 },
5048 {
5049 errno: 52,
5050 code: 'EXDEV',
5051 description: 'cross-device link not permitted'
5052 },
5053 {
5054 errno: 53,
5055 code: 'ENOTEMPTY',
5056 description: 'directory not empty'
5057 },
5058 {
5059 errno: 54,
5060 code: 'ENOSPC',
5061 description: 'no space left on device'
5062 },
5063 {
5064 errno: 55,
5065 code: 'EIO',
5066 description: 'i/o error'
5067 },
5068 {
5069 errno: 56,
5070 code: 'EROFS',
5071 description: 'read-only file system'
5072 },
5073 {
5074 errno: 57,
5075 code: 'ENODEV',
5076 description: 'no such device'
5077 },
5078 {
5079 errno: 58,
5080 code: 'ESPIPE',
5081 description: 'invalid seek'
5082 },
5083 {
5084 errno: 59,
5085 code: 'ECANCELED',
5086 description: 'operation canceled'
5087 }
5088]
5089
5090module.exports.errno = {}
5091module.exports.code = {}
5092
5093all.forEach(function (error) {
5094 module.exports.errno[error.errno] = error
5095 module.exports.code[error.code] = error
5096})
5097
5098module.exports.custom = _dereq_(24)(module.exports)
5099module.exports.create = module.exports.custom.createError
5100
5101},{"24":24}],26:[function(_dereq_,module,exports){
5102// Copyright Joyent, Inc. and other Node contributors.
5103//
5104// Permission is hereby granted, free of charge, to any person obtaining a
5105// copy of this software and associated documentation files (the
5106// "Software"), to deal in the Software without restriction, including
5107// without limitation the rights to use, copy, modify, merge, publish,
5108// distribute, sublicense, and/or sell copies of the Software, and to permit
5109// persons to whom the Software is furnished to do so, subject to the
5110// following conditions:
5111//
5112// The above copyright notice and this permission notice shall be included
5113// in all copies or substantial portions of the Software.
5114//
5115// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5116// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5117// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5118// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5119// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5120// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5121// USE OR OTHER DEALINGS IN THE SOFTWARE.
5122
5123var objectCreate = Object.create || objectCreatePolyfill
5124var objectKeys = Object.keys || objectKeysPolyfill
5125var bind = Function.prototype.bind || functionBindPolyfill
5126
5127function EventEmitter() {
5128 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
5129 this._events = objectCreate(null);
5130 this._eventsCount = 0;
5131 }
5132
5133 this._maxListeners = this._maxListeners || undefined;
5134}
5135module.exports = EventEmitter;
5136
5137// Backwards-compat with node 0.10.x
5138EventEmitter.EventEmitter = EventEmitter;
5139
5140EventEmitter.prototype._events = undefined;
5141EventEmitter.prototype._maxListeners = undefined;
5142
5143// By default EventEmitters will print a warning if more than 10 listeners are
5144// added to it. This is a useful default which helps finding memory leaks.
5145var defaultMaxListeners = 10;
5146
5147var hasDefineProperty;
5148try {
5149 var o = {};
5150 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
5151 hasDefineProperty = o.x === 0;
5152} catch (err) { hasDefineProperty = false }
5153if (hasDefineProperty) {
5154 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
5155 enumerable: true,
5156 get: function() {
5157 return defaultMaxListeners;
5158 },
5159 set: function(arg) {
5160 // check whether the input is a positive number (whose value is zero or
5161 // greater and not a NaN).
5162 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
5163 throw new TypeError('"defaultMaxListeners" must be a positive number');
5164 defaultMaxListeners = arg;
5165 }
5166 });
5167} else {
5168 EventEmitter.defaultMaxListeners = defaultMaxListeners;
5169}
5170
5171// Obviously not all Emitters should be limited to 10. This function allows
5172// that to be increased. Set to zero for unlimited.
5173EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
5174 if (typeof n !== 'number' || n < 0 || isNaN(n))
5175 throw new TypeError('"n" argument must be a positive number');
5176 this._maxListeners = n;
5177 return this;
5178};
5179
5180function $getMaxListeners(that) {
5181 if (that._maxListeners === undefined)
5182 return EventEmitter.defaultMaxListeners;
5183 return that._maxListeners;
5184}
5185
5186EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
5187 return $getMaxListeners(this);
5188};
5189
5190// These standalone emit* functions are used to optimize calling of event
5191// handlers for fast cases because emit() itself often has a variable number of
5192// arguments and can be deoptimized because of that. These functions always have
5193// the same number of arguments and thus do not get deoptimized, so the code
5194// inside them can execute faster.
5195function emitNone(handler, isFn, self) {
5196 if (isFn)
5197 handler.call(self);
5198 else {
5199 var len = handler.length;
5200 var listeners = arrayClone(handler, len);
5201 for (var i = 0; i < len; ++i)
5202 listeners[i].call(self);
5203 }
5204}
5205function emitOne(handler, isFn, self, arg1) {
5206 if (isFn)
5207 handler.call(self, arg1);
5208 else {
5209 var len = handler.length;
5210 var listeners = arrayClone(handler, len);
5211 for (var i = 0; i < len; ++i)
5212 listeners[i].call(self, arg1);
5213 }
5214}
5215function emitTwo(handler, isFn, self, arg1, arg2) {
5216 if (isFn)
5217 handler.call(self, arg1, arg2);
5218 else {
5219 var len = handler.length;
5220 var listeners = arrayClone(handler, len);
5221 for (var i = 0; i < len; ++i)
5222 listeners[i].call(self, arg1, arg2);
5223 }
5224}
5225function emitThree(handler, isFn, self, arg1, arg2, arg3) {
5226 if (isFn)
5227 handler.call(self, arg1, arg2, arg3);
5228 else {
5229 var len = handler.length;
5230 var listeners = arrayClone(handler, len);
5231 for (var i = 0; i < len; ++i)
5232 listeners[i].call(self, arg1, arg2, arg3);
5233 }
5234}
5235
5236function emitMany(handler, isFn, self, args) {
5237 if (isFn)
5238 handler.apply(self, args);
5239 else {
5240 var len = handler.length;
5241 var listeners = arrayClone(handler, len);
5242 for (var i = 0; i < len; ++i)
5243 listeners[i].apply(self, args);
5244 }
5245}
5246
5247EventEmitter.prototype.emit = function emit(type) {
5248 var er, handler, len, args, i, events;
5249 var doError = (type === 'error');
5250
5251 events = this._events;
5252 if (events)
5253 doError = (doError && events.error == null);
5254 else if (!doError)
5255 return false;
5256
5257 // If there is no 'error' event listener then throw.
5258 if (doError) {
5259 if (arguments.length > 1)
5260 er = arguments[1];
5261 if (er instanceof Error) {
5262 throw er; // Unhandled 'error' event
5263 } else {
5264 // At least give some kind of context to the user
5265 var err = new Error('Unhandled "error" event. (' + er + ')');
5266 err.context = er;
5267 throw err;
5268 }
5269 return false;
5270 }
5271
5272 handler = events[type];
5273
5274 if (!handler)
5275 return false;
5276
5277 var isFn = typeof handler === 'function';
5278 len = arguments.length;
5279 switch (len) {
5280 // fast cases
5281 case 1:
5282 emitNone(handler, isFn, this);
5283 break;
5284 case 2:
5285 emitOne(handler, isFn, this, arguments[1]);
5286 break;
5287 case 3:
5288 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
5289 break;
5290 case 4:
5291 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
5292 break;
5293 // slower
5294 default:
5295 args = new Array(len - 1);
5296 for (i = 1; i < len; i++)
5297 args[i - 1] = arguments[i];
5298 emitMany(handler, isFn, this, args);
5299 }
5300
5301 return true;
5302};
5303
5304function _addListener(target, type, listener, prepend) {
5305 var m;
5306 var events;
5307 var existing;
5308
5309 if (typeof listener !== 'function')
5310 throw new TypeError('"listener" argument must be a function');
5311
5312 events = target._events;
5313 if (!events) {
5314 events = target._events = objectCreate(null);
5315 target._eventsCount = 0;
5316 } else {
5317 // To avoid recursion in the case that type === "newListener"! Before
5318 // adding it to the listeners, first emit "newListener".
5319 if (events.newListener) {
5320 target.emit('newListener', type,
5321 listener.listener ? listener.listener : listener);
5322
5323 // Re-assign `events` because a newListener handler could have caused the
5324 // this._events to be assigned to a new object
5325 events = target._events;
5326 }
5327 existing = events[type];
5328 }
5329
5330 if (!existing) {
5331 // Optimize the case of one listener. Don't need the extra array object.
5332 existing = events[type] = listener;
5333 ++target._eventsCount;
5334 } else {
5335 if (typeof existing === 'function') {
5336 // Adding the second element, need to change to array.
5337 existing = events[type] =
5338 prepend ? [listener, existing] : [existing, listener];
5339 } else {
5340 // If we've already got an array, just append.
5341 if (prepend) {
5342 existing.unshift(listener);
5343 } else {
5344 existing.push(listener);
5345 }
5346 }
5347
5348 // Check for listener leak
5349 if (!existing.warned) {
5350 m = $getMaxListeners(target);
5351 if (m && m > 0 && existing.length > m) {
5352 existing.warned = true;
5353 var w = new Error('Possible EventEmitter memory leak detected. ' +
5354 existing.length + ' "' + String(type) + '" listeners ' +
5355 'added. Use emitter.setMaxListeners() to ' +
5356 'increase limit.');
5357 w.name = 'MaxListenersExceededWarning';
5358 w.emitter = target;
5359 w.type = type;
5360 w.count = existing.length;
5361 if (typeof console === 'object' && console.warn) {
5362 console.warn('%s: %s', w.name, w.message);
5363 }
5364 }
5365 }
5366 }
5367
5368 return target;
5369}
5370
5371EventEmitter.prototype.addListener = function addListener(type, listener) {
5372 return _addListener(this, type, listener, false);
5373};
5374
5375EventEmitter.prototype.on = EventEmitter.prototype.addListener;
5376
5377EventEmitter.prototype.prependListener =
5378 function prependListener(type, listener) {
5379 return _addListener(this, type, listener, true);
5380 };
5381
5382function onceWrapper() {
5383 if (!this.fired) {
5384 this.target.removeListener(this.type, this.wrapFn);
5385 this.fired = true;
5386 switch (arguments.length) {
5387 case 0:
5388 return this.listener.call(this.target);
5389 case 1:
5390 return this.listener.call(this.target, arguments[0]);
5391 case 2:
5392 return this.listener.call(this.target, arguments[0], arguments[1]);
5393 case 3:
5394 return this.listener.call(this.target, arguments[0], arguments[1],
5395 arguments[2]);
5396 default:
5397 var args = new Array(arguments.length);
5398 for (var i = 0; i < args.length; ++i)
5399 args[i] = arguments[i];
5400 this.listener.apply(this.target, args);
5401 }
5402 }
5403}
5404
5405function _onceWrap(target, type, listener) {
5406 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
5407 var wrapped = bind.call(onceWrapper, state);
5408 wrapped.listener = listener;
5409 state.wrapFn = wrapped;
5410 return wrapped;
5411}
5412
5413EventEmitter.prototype.once = function once(type, listener) {
5414 if (typeof listener !== 'function')
5415 throw new TypeError('"listener" argument must be a function');
5416 this.on(type, _onceWrap(this, type, listener));
5417 return this;
5418};
5419
5420EventEmitter.prototype.prependOnceListener =
5421 function prependOnceListener(type, listener) {
5422 if (typeof listener !== 'function')
5423 throw new TypeError('"listener" argument must be a function');
5424 this.prependListener(type, _onceWrap(this, type, listener));
5425 return this;
5426 };
5427
5428// Emits a 'removeListener' event if and only if the listener was removed.
5429EventEmitter.prototype.removeListener =
5430 function removeListener(type, listener) {
5431 var list, events, position, i, originalListener;
5432
5433 if (typeof listener !== 'function')
5434 throw new TypeError('"listener" argument must be a function');
5435
5436 events = this._events;
5437 if (!events)
5438 return this;
5439
5440 list = events[type];
5441 if (!list)
5442 return this;
5443
5444 if (list === listener || list.listener === listener) {
5445 if (--this._eventsCount === 0)
5446 this._events = objectCreate(null);
5447 else {
5448 delete events[type];
5449 if (events.removeListener)
5450 this.emit('removeListener', type, list.listener || listener);
5451 }
5452 } else if (typeof list !== 'function') {
5453 position = -1;
5454
5455 for (i = list.length - 1; i >= 0; i--) {
5456 if (list[i] === listener || list[i].listener === listener) {
5457 originalListener = list[i].listener;
5458 position = i;
5459 break;
5460 }
5461 }
5462
5463 if (position < 0)
5464 return this;
5465
5466 if (position === 0)
5467 list.shift();
5468 else
5469 spliceOne(list, position);
5470
5471 if (list.length === 1)
5472 events[type] = list[0];
5473
5474 if (events.removeListener)
5475 this.emit('removeListener', type, originalListener || listener);
5476 }
5477
5478 return this;
5479 };
5480
5481EventEmitter.prototype.removeAllListeners =
5482 function removeAllListeners(type) {
5483 var listeners, events, i;
5484
5485 events = this._events;
5486 if (!events)
5487 return this;
5488
5489 // not listening for removeListener, no need to emit
5490 if (!events.removeListener) {
5491 if (arguments.length === 0) {
5492 this._events = objectCreate(null);
5493 this._eventsCount = 0;
5494 } else if (events[type]) {
5495 if (--this._eventsCount === 0)
5496 this._events = objectCreate(null);
5497 else
5498 delete events[type];
5499 }
5500 return this;
5501 }
5502
5503 // emit removeListener for all listeners on all events
5504 if (arguments.length === 0) {
5505 var keys = objectKeys(events);
5506 var key;
5507 for (i = 0; i < keys.length; ++i) {
5508 key = keys[i];
5509 if (key === 'removeListener') continue;
5510 this.removeAllListeners(key);
5511 }
5512 this.removeAllListeners('removeListener');
5513 this._events = objectCreate(null);
5514 this._eventsCount = 0;
5515 return this;
5516 }
5517
5518 listeners = events[type];
5519
5520 if (typeof listeners === 'function') {
5521 this.removeListener(type, listeners);
5522 } else if (listeners) {
5523 // LIFO order
5524 for (i = listeners.length - 1; i >= 0; i--) {
5525 this.removeListener(type, listeners[i]);
5526 }
5527 }
5528
5529 return this;
5530 };
5531
5532function _listeners(target, type, unwrap) {
5533 var events = target._events;
5534
5535 if (!events)
5536 return [];
5537
5538 var evlistener = events[type];
5539 if (!evlistener)
5540 return [];
5541
5542 if (typeof evlistener === 'function')
5543 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
5544
5545 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
5546}
5547
5548EventEmitter.prototype.listeners = function listeners(type) {
5549 return _listeners(this, type, true);
5550};
5551
5552EventEmitter.prototype.rawListeners = function rawListeners(type) {
5553 return _listeners(this, type, false);
5554};
5555
5556EventEmitter.listenerCount = function(emitter, type) {
5557 if (typeof emitter.listenerCount === 'function') {
5558 return emitter.listenerCount(type);
5559 } else {
5560 return listenerCount.call(emitter, type);
5561 }
5562};
5563
5564EventEmitter.prototype.listenerCount = listenerCount;
5565function listenerCount(type) {
5566 var events = this._events;
5567
5568 if (events) {
5569 var evlistener = events[type];
5570
5571 if (typeof evlistener === 'function') {
5572 return 1;
5573 } else if (evlistener) {
5574 return evlistener.length;
5575 }
5576 }
5577
5578 return 0;
5579}
5580
5581EventEmitter.prototype.eventNames = function eventNames() {
5582 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
5583};
5584
5585// About 1.5x faster than the two-arg version of Array#splice().
5586function spliceOne(list, index) {
5587 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
5588 list[i] = list[k];
5589 list.pop();
5590}
5591
5592function arrayClone(arr, n) {
5593 var copy = new Array(n);
5594 for (var i = 0; i < n; ++i)
5595 copy[i] = arr[i];
5596 return copy;
5597}
5598
5599function unwrapListeners(arr) {
5600 var ret = new Array(arr.length);
5601 for (var i = 0; i < ret.length; ++i) {
5602 ret[i] = arr[i].listener || arr[i];
5603 }
5604 return ret;
5605}
5606
5607function objectCreatePolyfill(proto) {
5608 var F = function() {};
5609 F.prototype = proto;
5610 return new F;
5611}
5612function objectKeysPolyfill(obj) {
5613 var keys = [];
5614 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
5615 keys.push(k);
5616 }
5617 return k;
5618}
5619function functionBindPolyfill(context) {
5620 var fn = this;
5621 return function () {
5622 return fn.apply(context, arguments);
5623 };
5624}
5625
5626},{}],27:[function(_dereq_,module,exports){
5627/**
5628 * # hasLocalStorage()
5629 *
5630 * returns `true` or `false` depending on whether localStorage is supported or not.
5631 * Beware that some browsers like Safari do not support localStorage in private mode.
5632 *
5633 * inspired by this cappuccino commit
5634 * https://github.com/cappuccino/cappuccino/commit/063b05d9643c35b303568a28809e4eb3224f71ec
5635 *
5636 * @returns {Boolean}
5637 */
5638function hasLocalStorage() {
5639 try {
5640
5641 // we've to put this in here. I've seen Firefox throwing `Security error: 1000`
5642 // when cookies have been disabled
5643 if (typeof localStorage === 'undefined') {
5644 return false;
5645 }
5646
5647 // Just because localStorage exists does not mean it works. In particular it might be disabled
5648 // as it is when Safari's private browsing mode is active.
5649 localStorage.setItem('Storage-Test', '1');
5650
5651 // that should not happen ...
5652 if (localStorage.getItem('Storage-Test') !== '1') {
5653 return false;
5654 }
5655
5656 // okay, let's clean up if we got here.
5657 localStorage.removeItem('Storage-Test');
5658 } catch (_error) {
5659
5660 // in case of an error, like Safari's Private Mode, return false
5661 return false;
5662 }
5663
5664 // we're good.
5665 return true;
5666}
5667
5668
5669if (typeof exports === 'object') {
5670 module.exports = hasLocalStorage;
5671}
5672
5673},{}],28:[function(_dereq_,module,exports){
5674(function (global){(function (){
5675var exports = module.exports = {};
5676var localStorageMemory = _dereq_(69);
5677exports.hasLocalStorage = _dereq_(27);
5678
5679/**
5680 * returns localStorage-compatible API, either backed by window.localStorage
5681 * or memory if it's not available or not persistent.
5682 *
5683 * It also adds an object API (`.getObject(key)`,
5684 * `.setObject(key, properties)`) and a `isPresistent` property
5685 *
5686 * @returns {Object}
5687 */
5688exports.create = function () {
5689 var api;
5690
5691 if (!exports.hasLocalStorage()) {
5692 api = localStorageMemory;
5693 api.isPersistent = false;
5694 } else {
5695 api = global.localStorage;
5696 api = {
5697 get length() { return global.localStorage.length; },
5698 getItem: global.localStorage.getItem.bind(global.localStorage),
5699 setItem: global.localStorage.setItem.bind(global.localStorage),
5700 removeItem: global.localStorage.removeItem.bind(global.localStorage),
5701 key: global.localStorage.key.bind(global.localStorage),
5702 clear: global.localStorage.clear.bind(global.localStorage),
5703 };
5704
5705 api.isPersistent = true;
5706 }
5707
5708 api.getObject = exports.getObject.bind(null, api);
5709 api.setObject = exports.setObject.bind(null, api);
5710
5711 return api;
5712};
5713
5714/**
5715 * sets key to passed Object.
5716 *
5717 * @returns undefined
5718 */
5719exports.setObject = function (store, key, object) {
5720 if (typeof object !== 'object') {
5721 return store.setItem(key, object);
5722 }
5723
5724 return store.setItem(key, JSON.stringify(object));
5725};
5726
5727/**
5728 * returns Object for key, or null
5729 *
5730 * @returns {Object|null}
5731 */
5732exports.getObject = function (store, key) {
5733 var item = store.getItem(key);
5734
5735 if (!item) {
5736 return null;
5737 }
5738
5739 try {
5740 return JSON.parse(item);
5741 } catch (e) {
5742 return item;
5743 }
5744};
5745
5746}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5747},{"27":27,"69":69}],29:[function(_dereq_,module,exports){
5748var api = _dereq_(28);
5749module.exports = api.create();
5750
5751},{"28":28}],30:[function(_dereq_,module,exports){
5752/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
5753exports.read = function (buffer, offset, isLE, mLen, nBytes) {
5754 var e, m
5755 var eLen = (nBytes * 8) - mLen - 1
5756 var eMax = (1 << eLen) - 1
5757 var eBias = eMax >> 1
5758 var nBits = -7
5759 var i = isLE ? (nBytes - 1) : 0
5760 var d = isLE ? -1 : 1
5761 var s = buffer[offset + i]
5762
5763 i += d
5764
5765 e = s & ((1 << (-nBits)) - 1)
5766 s >>= (-nBits)
5767 nBits += eLen
5768 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5769
5770 m = e & ((1 << (-nBits)) - 1)
5771 e >>= (-nBits)
5772 nBits += mLen
5773 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5774
5775 if (e === 0) {
5776 e = 1 - eBias
5777 } else if (e === eMax) {
5778 return m ? NaN : ((s ? -1 : 1) * Infinity)
5779 } else {
5780 m = m + Math.pow(2, mLen)
5781 e = e - eBias
5782 }
5783 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
5784}
5785
5786exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
5787 var e, m, c
5788 var eLen = (nBytes * 8) - mLen - 1
5789 var eMax = (1 << eLen) - 1
5790 var eBias = eMax >> 1
5791 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
5792 var i = isLE ? 0 : (nBytes - 1)
5793 var d = isLE ? 1 : -1
5794 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
5795
5796 value = Math.abs(value)
5797
5798 if (isNaN(value) || value === Infinity) {
5799 m = isNaN(value) ? 1 : 0
5800 e = eMax
5801 } else {
5802 e = Math.floor(Math.log(value) / Math.LN2)
5803 if (value * (c = Math.pow(2, -e)) < 1) {
5804 e--
5805 c *= 2
5806 }
5807 if (e + eBias >= 1) {
5808 value += rt / c
5809 } else {
5810 value += rt * Math.pow(2, 1 - eBias)
5811 }
5812 if (value * c >= 2) {
5813 e++
5814 c /= 2
5815 }
5816
5817 if (e + eBias >= eMax) {
5818 m = 0
5819 e = eMax
5820 } else if (e + eBias >= 1) {
5821 m = ((value * c) - 1) * Math.pow(2, mLen)
5822 e = e + eBias
5823 } else {
5824 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
5825 e = 0
5826 }
5827 }
5828
5829 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
5830
5831 e = (e << mLen) | m
5832 eLen += mLen
5833 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
5834
5835 buffer[offset + i - d] |= s * 128
5836}
5837
5838},{}],31:[function(_dereq_,module,exports){
5839'use strict';
5840var types = [
5841 _dereq_(11),
5842 _dereq_(34),
5843 _dereq_(33),
5844 _dereq_(32),
5845 _dereq_(35),
5846 _dereq_(36)
5847];
5848var draining;
5849var currentQueue;
5850var queueIndex = -1;
5851var queue = [];
5852var scheduled = false;
5853function cleanUpNextTick() {
5854 if (!draining || !currentQueue) {
5855 return;
5856 }
5857 draining = false;
5858 if (currentQueue.length) {
5859 queue = currentQueue.concat(queue);
5860 } else {
5861 queueIndex = -1;
5862 }
5863 if (queue.length) {
5864 nextTick();
5865 }
5866}
5867
5868//named nextTick for less confusing stack traces
5869function nextTick() {
5870 if (draining) {
5871 return;
5872 }
5873 scheduled = false;
5874 draining = true;
5875 var len = queue.length;
5876 var timeout = setTimeout(cleanUpNextTick);
5877 while (len) {
5878 currentQueue = queue;
5879 queue = [];
5880 while (currentQueue && ++queueIndex < len) {
5881 currentQueue[queueIndex].run();
5882 }
5883 queueIndex = -1;
5884 len = queue.length;
5885 }
5886 currentQueue = null;
5887 queueIndex = -1;
5888 draining = false;
5889 clearTimeout(timeout);
5890}
5891var scheduleDrain;
5892var i = -1;
5893var len = types.length;
5894while (++i < len) {
5895 if (types[i] && types[i].test && types[i].test()) {
5896 scheduleDrain = types[i].install(nextTick);
5897 break;
5898 }
5899}
5900// v8 likes predictible objects
5901function Item(fun, array) {
5902 this.fun = fun;
5903 this.array = array;
5904}
5905Item.prototype.run = function () {
5906 var fun = this.fun;
5907 var array = this.array;
5908 switch (array.length) {
5909 case 0:
5910 return fun();
5911 case 1:
5912 return fun(array[0]);
5913 case 2:
5914 return fun(array[0], array[1]);
5915 case 3:
5916 return fun(array[0], array[1], array[2]);
5917 default:
5918 return fun.apply(null, array);
5919 }
5920
5921};
5922module.exports = immediate;
5923function immediate(task) {
5924 var args = new Array(arguments.length - 1);
5925 if (arguments.length > 1) {
5926 for (var i = 1; i < arguments.length; i++) {
5927 args[i - 1] = arguments[i];
5928 }
5929 }
5930 queue.push(new Item(task, args));
5931 if (!scheduled && !draining) {
5932 scheduled = true;
5933 scheduleDrain();
5934 }
5935}
5936
5937},{"11":11,"32":32,"33":33,"34":34,"35":35,"36":36}],32:[function(_dereq_,module,exports){
5938(function (global){(function (){
5939'use strict';
5940
5941exports.test = function () {
5942 if (global.setImmediate) {
5943 // we can only get here in IE10
5944 // which doesn't handel postMessage well
5945 return false;
5946 }
5947 return typeof global.MessageChannel !== 'undefined';
5948};
5949
5950exports.install = function (func) {
5951 var channel = new global.MessageChannel();
5952 channel.port1.onmessage = func;
5953 return function () {
5954 channel.port2.postMessage(0);
5955 };
5956};
5957}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5958},{}],33:[function(_dereq_,module,exports){
5959(function (global){(function (){
5960'use strict';
5961//based off rsvp https://github.com/tildeio/rsvp.js
5962//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
5963//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
5964
5965var Mutation = global.MutationObserver || global.WebKitMutationObserver;
5966
5967exports.test = function () {
5968 return Mutation;
5969};
5970
5971exports.install = function (handle) {
5972 var called = 0;
5973 var observer = new Mutation(handle);
5974 var element = global.document.createTextNode('');
5975 observer.observe(element, {
5976 characterData: true
5977 });
5978 return function () {
5979 element.data = (called = ++called % 2);
5980 };
5981};
5982}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5983},{}],34:[function(_dereq_,module,exports){
5984(function (global){(function (){
5985'use strict';
5986exports.test = function () {
5987 return typeof global.queueMicrotask === 'function';
5988};
5989
5990exports.install = function (func) {
5991 return function () {
5992 global.queueMicrotask(func);
5993 };
5994};
5995
5996}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5997},{}],35:[function(_dereq_,module,exports){
5998(function (global){(function (){
5999'use strict';
6000
6001exports.test = function () {
6002 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
6003};
6004
6005exports.install = function (handle) {
6006 return function () {
6007
6008 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
6009 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
6010 var scriptEl = global.document.createElement('script');
6011 scriptEl.onreadystatechange = function () {
6012 handle();
6013
6014 scriptEl.onreadystatechange = null;
6015 scriptEl.parentNode.removeChild(scriptEl);
6016 scriptEl = null;
6017 };
6018 global.document.documentElement.appendChild(scriptEl);
6019
6020 return handle;
6021 };
6022};
6023}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6024},{}],36:[function(_dereq_,module,exports){
6025'use strict';
6026exports.test = function () {
6027 return true;
6028};
6029
6030exports.install = function (t) {
6031 return function () {
6032 setTimeout(t, 0);
6033 };
6034};
6035},{}],37:[function(_dereq_,module,exports){
6036if (typeof Object.create === 'function') {
6037 // implementation from standard node.js 'util' module
6038 module.exports = function inherits(ctor, superCtor) {
6039 if (superCtor) {
6040 ctor.super_ = superCtor
6041 ctor.prototype = Object.create(superCtor.prototype, {
6042 constructor: {
6043 value: ctor,
6044 enumerable: false,
6045 writable: true,
6046 configurable: true
6047 }
6048 })
6049 }
6050 };
6051} else {
6052 // old school shim for old browsers
6053 module.exports = function inherits(ctor, superCtor) {
6054 if (superCtor) {
6055 ctor.super_ = superCtor
6056 var TempCtor = function () {}
6057 TempCtor.prototype = superCtor.prototype
6058 ctor.prototype = new TempCtor()
6059 ctor.prototype.constructor = ctor
6060 }
6061 }
6062}
6063
6064},{}],38:[function(_dereq_,module,exports){
6065/*!
6066 * Determine if an object is a Buffer
6067 *
6068 * @author Feross Aboukhadijeh <https://feross.org>
6069 * @license MIT
6070 */
6071
6072// The _isBuffer check is for Safari 5-7 support, because it's missing
6073// Object.prototype.constructor. Remove this eventually
6074module.exports = function (obj) {
6075 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
6076}
6077
6078function isBuffer (obj) {
6079 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
6080}
6081
6082// For Node v0.10 support. Remove this eventually.
6083function isSlowBuffer (obj) {
6084 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
6085}
6086
6087},{}],39:[function(_dereq_,module,exports){
6088var encodings = _dereq_(40)
6089
6090module.exports = Codec
6091
6092function Codec (opts) {
6093 if (!(this instanceof Codec)) {
6094 return new Codec(opts)
6095 }
6096 this.opts = opts || {}
6097 this.encodings = encodings
6098}
6099
6100Codec.prototype._encoding = function (encoding) {
6101 if (typeof encoding === 'string') encoding = encodings[encoding]
6102 if (!encoding) encoding = encodings.id
6103 return encoding
6104}
6105
6106Codec.prototype._keyEncoding = function (opts, batchOpts) {
6107 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
6108 (opts && opts.keyEncoding) ||
6109 this.opts.keyEncoding)
6110}
6111
6112Codec.prototype._valueEncoding = function (opts, batchOpts) {
6113 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
6114 (opts && (opts.valueEncoding || opts.encoding)) ||
6115 (this.opts.valueEncoding || this.opts.encoding))
6116}
6117
6118Codec.prototype.encodeKey = function (key, opts, batchOpts) {
6119 return this._keyEncoding(opts, batchOpts).encode(key)
6120}
6121
6122Codec.prototype.encodeValue = function (value, opts, batchOpts) {
6123 return this._valueEncoding(opts, batchOpts).encode(value)
6124}
6125
6126Codec.prototype.decodeKey = function (key, opts) {
6127 return this._keyEncoding(opts).decode(key)
6128}
6129
6130Codec.prototype.decodeValue = function (value, opts) {
6131 return this._valueEncoding(opts).decode(value)
6132}
6133
6134Codec.prototype.encodeBatch = function (ops, opts) {
6135 var self = this
6136
6137 return ops.map(function (_op) {
6138 var op = {
6139 type: _op.type,
6140 key: self.encodeKey(_op.key, opts, _op)
6141 }
6142 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
6143 if (_op.prefix) op.prefix = _op.prefix
6144 if ('value' in _op) {
6145 op.value = self.encodeValue(_op.value, opts, _op)
6146 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
6147 }
6148 return op
6149 })
6150}
6151
6152var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
6153
6154Codec.prototype.encodeLtgt = function (ltgt) {
6155 var self = this
6156 var ret = {}
6157 Object.keys(ltgt).forEach(function (key) {
6158 ret[key] = ltgtKeys.indexOf(key) > -1
6159 ? self.encodeKey(ltgt[key], ltgt)
6160 : ltgt[key]
6161 })
6162 return ret
6163}
6164
6165Codec.prototype.createStreamDecoder = function (opts) {
6166 var self = this
6167
6168 if (opts.keys && opts.values) {
6169 return function (key, value) {
6170 return {
6171 key: self.decodeKey(key, opts),
6172 value: self.decodeValue(value, opts)
6173 }
6174 }
6175 } else if (opts.keys) {
6176 return function (key) {
6177 return self.decodeKey(key, opts)
6178 }
6179 } else if (opts.values) {
6180 return function (_, value) {
6181 return self.decodeValue(value, opts)
6182 }
6183 } else {
6184 return function () {}
6185 }
6186}
6187
6188Codec.prototype.keyAsBuffer = function (opts) {
6189 return this._keyEncoding(opts).buffer
6190}
6191
6192Codec.prototype.valueAsBuffer = function (opts) {
6193 return this._valueEncoding(opts).buffer
6194}
6195
6196},{"40":40}],40:[function(_dereq_,module,exports){
6197var Buffer = _dereq_(13).Buffer
6198
6199exports.utf8 = exports['utf-8'] = {
6200 encode: function (data) {
6201 return isBinary(data) ? data : String(data)
6202 },
6203 decode: identity,
6204 buffer: false,
6205 type: 'utf8'
6206}
6207
6208exports.json = {
6209 encode: JSON.stringify,
6210 decode: JSON.parse,
6211 buffer: false,
6212 type: 'json'
6213}
6214
6215exports.binary = {
6216 encode: function (data) {
6217 return isBinary(data) ? data : Buffer.from(data)
6218 },
6219 decode: identity,
6220 buffer: true,
6221 type: 'binary'
6222}
6223
6224exports.none = {
6225 encode: identity,
6226 decode: identity,
6227 buffer: false,
6228 type: 'id'
6229}
6230
6231exports.id = exports.none
6232
6233var bufferEncodings = [
6234 'hex',
6235 'ascii',
6236 'base64',
6237 'ucs2',
6238 'ucs-2',
6239 'utf16le',
6240 'utf-16le'
6241]
6242
6243bufferEncodings.forEach(function (type) {
6244 exports[type] = {
6245 encode: function (data) {
6246 return isBinary(data) ? data : Buffer.from(data, type)
6247 },
6248 decode: function (buffer) {
6249 return buffer.toString(type)
6250 },
6251 buffer: true,
6252 type: type
6253 }
6254})
6255
6256function identity (value) {
6257 return value
6258}
6259
6260function isBinary (data) {
6261 return data === undefined || data === null || Buffer.isBuffer(data)
6262}
6263
6264},{"13":13}],41:[function(_dereq_,module,exports){
6265var createError = _dereq_(25).create
6266var LevelUPError = createError('LevelUPError')
6267var NotFoundError = createError('NotFoundError', LevelUPError)
6268
6269NotFoundError.prototype.notFound = true
6270NotFoundError.prototype.status = 404
6271
6272module.exports = {
6273 LevelUPError: LevelUPError,
6274 InitializationError: createError('InitializationError', LevelUPError),
6275 OpenError: createError('OpenError', LevelUPError),
6276 ReadError: createError('ReadError', LevelUPError),
6277 WriteError: createError('WriteError', LevelUPError),
6278 NotFoundError: NotFoundError,
6279 EncodingError: createError('EncodingError', LevelUPError)
6280}
6281
6282},{"25":25}],42:[function(_dereq_,module,exports){
6283var inherits = _dereq_(37)
6284var Readable = _dereq_(57).Readable
6285var extend = _dereq_(141)
6286
6287module.exports = ReadStream
6288inherits(ReadStream, Readable)
6289
6290function ReadStream (iterator, options) {
6291 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
6292 options = options || {}
6293 Readable.call(this, extend(options, {
6294 objectMode: true
6295 }))
6296 this._iterator = iterator
6297 this._options = options
6298 this.on('end', this.destroy.bind(this, null, null))
6299}
6300
6301ReadStream.prototype._read = function () {
6302 var self = this
6303 var options = this._options
6304 if (this.destroyed) return
6305
6306 this._iterator.next(function (err, key, value) {
6307 if (self.destroyed) return
6308 if (err) return self.destroy(err)
6309
6310 if (key === undefined && value === undefined) {
6311 self.push(null)
6312 } else if (options.keys !== false && options.values === false) {
6313 self.push(key)
6314 } else if (options.keys === false && options.values !== false) {
6315 self.push(value)
6316 } else {
6317 self.push({ key: key, value: value })
6318 }
6319 })
6320}
6321
6322ReadStream.prototype._destroy = function (err, callback) {
6323 this._iterator.end(function (err2) {
6324 callback(err || err2)
6325 })
6326}
6327
6328},{"141":141,"37":37,"57":57}],43:[function(_dereq_,module,exports){
6329'use strict';
6330
6331function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
6332
6333var codes = {};
6334
6335function createErrorType(code, message, Base) {
6336 if (!Base) {
6337 Base = Error;
6338 }
6339
6340 function getMessage(arg1, arg2, arg3) {
6341 if (typeof message === 'string') {
6342 return message;
6343 } else {
6344 return message(arg1, arg2, arg3);
6345 }
6346 }
6347
6348 var NodeError =
6349 /*#__PURE__*/
6350 function (_Base) {
6351 _inheritsLoose(NodeError, _Base);
6352
6353 function NodeError(arg1, arg2, arg3) {
6354 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
6355 }
6356
6357 return NodeError;
6358 }(Base);
6359
6360 NodeError.prototype.name = Base.name;
6361 NodeError.prototype.code = code;
6362 codes[code] = NodeError;
6363} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
6364
6365
6366function oneOf(expected, thing) {
6367 if (Array.isArray(expected)) {
6368 var len = expected.length;
6369 expected = expected.map(function (i) {
6370 return String(i);
6371 });
6372
6373 if (len > 2) {
6374 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
6375 } else if (len === 2) {
6376 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
6377 } else {
6378 return "of ".concat(thing, " ").concat(expected[0]);
6379 }
6380 } else {
6381 return "of ".concat(thing, " ").concat(String(expected));
6382 }
6383} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
6384
6385
6386function startsWith(str, search, pos) {
6387 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
6388} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
6389
6390
6391function endsWith(str, search, this_len) {
6392 if (this_len === undefined || this_len > str.length) {
6393 this_len = str.length;
6394 }
6395
6396 return str.substring(this_len - search.length, this_len) === search;
6397} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
6398
6399
6400function includes(str, search, start) {
6401 if (typeof start !== 'number') {
6402 start = 0;
6403 }
6404
6405 if (start + search.length > str.length) {
6406 return false;
6407 } else {
6408 return str.indexOf(search, start) !== -1;
6409 }
6410}
6411
6412createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
6413 return 'The value "' + value + '" is invalid for option "' + name + '"';
6414}, TypeError);
6415createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
6416 // determiner: 'must be' or 'must not be'
6417 var determiner;
6418
6419 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
6420 determiner = 'must not be';
6421 expected = expected.replace(/^not /, '');
6422 } else {
6423 determiner = 'must be';
6424 }
6425
6426 var msg;
6427
6428 if (endsWith(name, ' argument')) {
6429 // For cases like 'first argument'
6430 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6431 } else {
6432 var type = includes(name, '.') ? 'property' : 'argument';
6433 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6434 }
6435
6436 msg += ". Received type ".concat(typeof actual);
6437 return msg;
6438}, TypeError);
6439createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
6440createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
6441 return 'The ' + name + ' method is not implemented';
6442});
6443createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
6444createErrorType('ERR_STREAM_DESTROYED', function (name) {
6445 return 'Cannot call ' + name + ' after a stream was destroyed';
6446});
6447createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
6448createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
6449createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
6450createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
6451createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
6452 return 'Unknown encoding: ' + arg;
6453}, TypeError);
6454createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
6455module.exports.codes = codes;
6456
6457},{}],44:[function(_dereq_,module,exports){
6458(function (process){(function (){
6459// Copyright Joyent, Inc. and other Node contributors.
6460//
6461// Permission is hereby granted, free of charge, to any person obtaining a
6462// copy of this software and associated documentation files (the
6463// "Software"), to deal in the Software without restriction, including
6464// without limitation the rights to use, copy, modify, merge, publish,
6465// distribute, sublicense, and/or sell copies of the Software, and to permit
6466// persons to whom the Software is furnished to do so, subject to the
6467// following conditions:
6468//
6469// The above copyright notice and this permission notice shall be included
6470// in all copies or substantial portions of the Software.
6471//
6472// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6473// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6474// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6475// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6476// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6477// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6478// USE OR OTHER DEALINGS IN THE SOFTWARE.
6479// a duplex stream is just a stream that is both readable and writable.
6480// Since JS doesn't have multiple prototypal inheritance, this class
6481// prototypally inherits from Readable, and then parasitically from
6482// Writable.
6483'use strict';
6484/*<replacement>*/
6485
6486var objectKeys = Object.keys || function (obj) {
6487 var keys = [];
6488
6489 for (var key in obj) {
6490 keys.push(key);
6491 }
6492
6493 return keys;
6494};
6495/*</replacement>*/
6496
6497
6498module.exports = Duplex;
6499
6500var Readable = _dereq_(46);
6501
6502var Writable = _dereq_(48);
6503
6504_dereq_(37)(Duplex, Readable);
6505
6506{
6507 // Allow the keys array to be GC'ed.
6508 var keys = objectKeys(Writable.prototype);
6509
6510 for (var v = 0; v < keys.length; v++) {
6511 var method = keys[v];
6512 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
6513 }
6514}
6515
6516function Duplex(options) {
6517 if (!(this instanceof Duplex)) return new Duplex(options);
6518 Readable.call(this, options);
6519 Writable.call(this, options);
6520 this.allowHalfOpen = true;
6521
6522 if (options) {
6523 if (options.readable === false) this.readable = false;
6524 if (options.writable === false) this.writable = false;
6525
6526 if (options.allowHalfOpen === false) {
6527 this.allowHalfOpen = false;
6528 this.once('end', onend);
6529 }
6530 }
6531}
6532
6533Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
6534 // making it explicit this property is not enumerable
6535 // because otherwise some prototype manipulation in
6536 // userland will fail
6537 enumerable: false,
6538 get: function get() {
6539 return this._writableState.highWaterMark;
6540 }
6541});
6542Object.defineProperty(Duplex.prototype, 'writableBuffer', {
6543 // making it explicit this property is not enumerable
6544 // because otherwise some prototype manipulation in
6545 // userland will fail
6546 enumerable: false,
6547 get: function get() {
6548 return this._writableState && this._writableState.getBuffer();
6549 }
6550});
6551Object.defineProperty(Duplex.prototype, 'writableLength', {
6552 // making it explicit this property is not enumerable
6553 // because otherwise some prototype manipulation in
6554 // userland will fail
6555 enumerable: false,
6556 get: function get() {
6557 return this._writableState.length;
6558 }
6559}); // the no-half-open enforcer
6560
6561function onend() {
6562 // If the writable side ended, then we're ok.
6563 if (this._writableState.ended) return; // no more data can be written.
6564 // But allow more writes to happen in this tick.
6565
6566 process.nextTick(onEndNT, this);
6567}
6568
6569function onEndNT(self) {
6570 self.end();
6571}
6572
6573Object.defineProperty(Duplex.prototype, 'destroyed', {
6574 // making it explicit this property is not enumerable
6575 // because otherwise some prototype manipulation in
6576 // userland will fail
6577 enumerable: false,
6578 get: function get() {
6579 if (this._readableState === undefined || this._writableState === undefined) {
6580 return false;
6581 }
6582
6583 return this._readableState.destroyed && this._writableState.destroyed;
6584 },
6585 set: function set(value) {
6586 // we ignore the value if the stream
6587 // has not been initialized yet
6588 if (this._readableState === undefined || this._writableState === undefined) {
6589 return;
6590 } // backward compatibility, the user is explicitly
6591 // managing destroyed
6592
6593
6594 this._readableState.destroyed = value;
6595 this._writableState.destroyed = value;
6596 }
6597});
6598}).call(this)}).call(this,_dereq_(73))
6599},{"37":37,"46":46,"48":48,"73":73}],45:[function(_dereq_,module,exports){
6600// Copyright Joyent, Inc. and other Node contributors.
6601//
6602// Permission is hereby granted, free of charge, to any person obtaining a
6603// copy of this software and associated documentation files (the
6604// "Software"), to deal in the Software without restriction, including
6605// without limitation the rights to use, copy, modify, merge, publish,
6606// distribute, sublicense, and/or sell copies of the Software, and to permit
6607// persons to whom the Software is furnished to do so, subject to the
6608// following conditions:
6609//
6610// The above copyright notice and this permission notice shall be included
6611// in all copies or substantial portions of the Software.
6612//
6613// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6614// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6615// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6616// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6617// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6618// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6619// USE OR OTHER DEALINGS IN THE SOFTWARE.
6620// a passthrough stream.
6621// basically just the most minimal sort of Transform stream.
6622// Every written chunk gets output as-is.
6623'use strict';
6624
6625module.exports = PassThrough;
6626
6627var Transform = _dereq_(47);
6628
6629_dereq_(37)(PassThrough, Transform);
6630
6631function PassThrough(options) {
6632 if (!(this instanceof PassThrough)) return new PassThrough(options);
6633 Transform.call(this, options);
6634}
6635
6636PassThrough.prototype._transform = function (chunk, encoding, cb) {
6637 cb(null, chunk);
6638};
6639},{"37":37,"47":47}],46:[function(_dereq_,module,exports){
6640(function (process,global){(function (){
6641// Copyright Joyent, Inc. and other Node contributors.
6642//
6643// Permission is hereby granted, free of charge, to any person obtaining a
6644// copy of this software and associated documentation files (the
6645// "Software"), to deal in the Software without restriction, including
6646// without limitation the rights to use, copy, modify, merge, publish,
6647// distribute, sublicense, and/or sell copies of the Software, and to permit
6648// persons to whom the Software is furnished to do so, subject to the
6649// following conditions:
6650//
6651// The above copyright notice and this permission notice shall be included
6652// in all copies or substantial portions of the Software.
6653//
6654// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6655// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6656// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6657// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6658// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6659// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6660// USE OR OTHER DEALINGS IN THE SOFTWARE.
6661'use strict';
6662
6663module.exports = Readable;
6664/*<replacement>*/
6665
6666var Duplex;
6667/*</replacement>*/
6668
6669Readable.ReadableState = ReadableState;
6670/*<replacement>*/
6671
6672var EE = _dereq_(26).EventEmitter;
6673
6674var EElistenerCount = function EElistenerCount(emitter, type) {
6675 return emitter.listeners(type).length;
6676};
6677/*</replacement>*/
6678
6679/*<replacement>*/
6680
6681
6682var Stream = _dereq_(56);
6683/*</replacement>*/
6684
6685
6686var Buffer = _dereq_(13).Buffer;
6687
6688var OurUint8Array = global.Uint8Array || function () {};
6689
6690function _uint8ArrayToBuffer(chunk) {
6691 return Buffer.from(chunk);
6692}
6693
6694function _isUint8Array(obj) {
6695 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
6696}
6697/*<replacement>*/
6698
6699
6700var debugUtil = _dereq_(11);
6701
6702var debug;
6703
6704if (debugUtil && debugUtil.debuglog) {
6705 debug = debugUtil.debuglog('stream');
6706} else {
6707 debug = function debug() {};
6708}
6709/*</replacement>*/
6710
6711
6712var BufferList = _dereq_(50);
6713
6714var destroyImpl = _dereq_(51);
6715
6716var _require = _dereq_(55),
6717 getHighWaterMark = _require.getHighWaterMark;
6718
6719var _require$codes = _dereq_(43).codes,
6720 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
6721 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
6722 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
6723 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
6724
6725
6726var StringDecoder;
6727var createReadableStreamAsyncIterator;
6728var from;
6729
6730_dereq_(37)(Readable, Stream);
6731
6732var errorOrDestroy = destroyImpl.errorOrDestroy;
6733var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
6734
6735function prependListener(emitter, event, fn) {
6736 // Sadly this is not cacheable as some libraries bundle their own
6737 // event emitter implementation with them.
6738 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
6739 // userland ones. NEVER DO THIS. This is here only because this code needs
6740 // to continue to work with older versions of Node.js that do not include
6741 // the prependListener() method. The goal is to eventually remove this hack.
6742
6743 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
6744}
6745
6746function ReadableState(options, stream, isDuplex) {
6747 Duplex = Duplex || _dereq_(44);
6748 options = options || {}; // Duplex streams are both readable and writable, but share
6749 // the same options object.
6750 // However, some cases require setting options to different
6751 // values for the readable and the writable sides of the duplex stream.
6752 // These options can be provided separately as readableXXX and writableXXX.
6753
6754 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
6755 // make all the buffer merging and length checks go away
6756
6757 this.objectMode = !!options.objectMode;
6758 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
6759 // Note: 0 is a valid value, means "don't call _read preemptively ever"
6760
6761 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
6762 // linked list can remove elements from the beginning faster than
6763 // array.shift()
6764
6765 this.buffer = new BufferList();
6766 this.length = 0;
6767 this.pipes = null;
6768 this.pipesCount = 0;
6769 this.flowing = null;
6770 this.ended = false;
6771 this.endEmitted = false;
6772 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
6773 // immediately, or on a later tick. We set this to true at first, because
6774 // any actions that shouldn't happen until "later" should generally also
6775 // not happen before the first read call.
6776
6777 this.sync = true; // whenever we return null, then we set a flag to say
6778 // that we're awaiting a 'readable' event emission.
6779
6780 this.needReadable = false;
6781 this.emittedReadable = false;
6782 this.readableListening = false;
6783 this.resumeScheduled = false;
6784 this.paused = true; // Should close be emitted on destroy. Defaults to true.
6785
6786 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
6787
6788 this.autoDestroy = !!options.autoDestroy; // has it been destroyed
6789
6790 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
6791 // encoding is 'binary' so we have to make this configurable.
6792 // Everything else in the universe uses 'utf8', though.
6793
6794 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
6795
6796 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
6797
6798 this.readingMore = false;
6799 this.decoder = null;
6800 this.encoding = null;
6801
6802 if (options.encoding) {
6803 if (!StringDecoder) StringDecoder = _dereq_(102).StringDecoder;
6804 this.decoder = new StringDecoder(options.encoding);
6805 this.encoding = options.encoding;
6806 }
6807}
6808
6809function Readable(options) {
6810 Duplex = Duplex || _dereq_(44);
6811 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
6812 // the ReadableState constructor, at least with V8 6.5
6813
6814 var isDuplex = this instanceof Duplex;
6815 this._readableState = new ReadableState(options, this, isDuplex); // legacy
6816
6817 this.readable = true;
6818
6819 if (options) {
6820 if (typeof options.read === 'function') this._read = options.read;
6821 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6822 }
6823
6824 Stream.call(this);
6825}
6826
6827Object.defineProperty(Readable.prototype, 'destroyed', {
6828 // making it explicit this property is not enumerable
6829 // because otherwise some prototype manipulation in
6830 // userland will fail
6831 enumerable: false,
6832 get: function get() {
6833 if (this._readableState === undefined) {
6834 return false;
6835 }
6836
6837 return this._readableState.destroyed;
6838 },
6839 set: function set(value) {
6840 // we ignore the value if the stream
6841 // has not been initialized yet
6842 if (!this._readableState) {
6843 return;
6844 } // backward compatibility, the user is explicitly
6845 // managing destroyed
6846
6847
6848 this._readableState.destroyed = value;
6849 }
6850});
6851Readable.prototype.destroy = destroyImpl.destroy;
6852Readable.prototype._undestroy = destroyImpl.undestroy;
6853
6854Readable.prototype._destroy = function (err, cb) {
6855 cb(err);
6856}; // Manually shove something into the read() buffer.
6857// This returns true if the highWaterMark has not been hit yet,
6858// similar to how Writable.write() returns true if you should
6859// write() some more.
6860
6861
6862Readable.prototype.push = function (chunk, encoding) {
6863 var state = this._readableState;
6864 var skipChunkCheck;
6865
6866 if (!state.objectMode) {
6867 if (typeof chunk === 'string') {
6868 encoding = encoding || state.defaultEncoding;
6869
6870 if (encoding !== state.encoding) {
6871 chunk = Buffer.from(chunk, encoding);
6872 encoding = '';
6873 }
6874
6875 skipChunkCheck = true;
6876 }
6877 } else {
6878 skipChunkCheck = true;
6879 }
6880
6881 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
6882}; // Unshift should *always* be something directly out of read()
6883
6884
6885Readable.prototype.unshift = function (chunk) {
6886 return readableAddChunk(this, chunk, null, true, false);
6887};
6888
6889function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
6890 debug('readableAddChunk', chunk);
6891 var state = stream._readableState;
6892
6893 if (chunk === null) {
6894 state.reading = false;
6895 onEofChunk(stream, state);
6896 } else {
6897 var er;
6898 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
6899
6900 if (er) {
6901 errorOrDestroy(stream, er);
6902 } else if (state.objectMode || chunk && chunk.length > 0) {
6903 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
6904 chunk = _uint8ArrayToBuffer(chunk);
6905 }
6906
6907 if (addToFront) {
6908 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
6909 } else if (state.ended) {
6910 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
6911 } else if (state.destroyed) {
6912 return false;
6913 } else {
6914 state.reading = false;
6915
6916 if (state.decoder && !encoding) {
6917 chunk = state.decoder.write(chunk);
6918 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
6919 } else {
6920 addChunk(stream, state, chunk, false);
6921 }
6922 }
6923 } else if (!addToFront) {
6924 state.reading = false;
6925 maybeReadMore(stream, state);
6926 }
6927 } // We can push more data if we are below the highWaterMark.
6928 // Also, if we have no data yet, we can stand some more bytes.
6929 // This is to work around cases where hwm=0, such as the repl.
6930
6931
6932 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
6933}
6934
6935function addChunk(stream, state, chunk, addToFront) {
6936 if (state.flowing && state.length === 0 && !state.sync) {
6937 state.awaitDrain = 0;
6938 stream.emit('data', chunk);
6939 } else {
6940 // update the buffer info.
6941 state.length += state.objectMode ? 1 : chunk.length;
6942 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
6943 if (state.needReadable) emitReadable(stream);
6944 }
6945
6946 maybeReadMore(stream, state);
6947}
6948
6949function chunkInvalid(state, chunk) {
6950 var er;
6951
6952 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
6953 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
6954 }
6955
6956 return er;
6957}
6958
6959Readable.prototype.isPaused = function () {
6960 return this._readableState.flowing === false;
6961}; // backwards compatibility.
6962
6963
6964Readable.prototype.setEncoding = function (enc) {
6965 if (!StringDecoder) StringDecoder = _dereq_(102).StringDecoder;
6966 var decoder = new StringDecoder(enc);
6967 this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
6968
6969 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
6970
6971 var p = this._readableState.buffer.head;
6972 var content = '';
6973
6974 while (p !== null) {
6975 content += decoder.write(p.data);
6976 p = p.next;
6977 }
6978
6979 this._readableState.buffer.clear();
6980
6981 if (content !== '') this._readableState.buffer.push(content);
6982 this._readableState.length = content.length;
6983 return this;
6984}; // Don't raise the hwm > 1GB
6985
6986
6987var MAX_HWM = 0x40000000;
6988
6989function computeNewHighWaterMark(n) {
6990 if (n >= MAX_HWM) {
6991 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
6992 n = MAX_HWM;
6993 } else {
6994 // Get the next highest power of 2 to prevent increasing hwm excessively in
6995 // tiny amounts
6996 n--;
6997 n |= n >>> 1;
6998 n |= n >>> 2;
6999 n |= n >>> 4;
7000 n |= n >>> 8;
7001 n |= n >>> 16;
7002 n++;
7003 }
7004
7005 return n;
7006} // This function is designed to be inlinable, so please take care when making
7007// changes to the function body.
7008
7009
7010function howMuchToRead(n, state) {
7011 if (n <= 0 || state.length === 0 && state.ended) return 0;
7012 if (state.objectMode) return 1;
7013
7014 if (n !== n) {
7015 // Only flow one buffer at a time
7016 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
7017 } // If we're asking for more than the current hwm, then raise the hwm.
7018
7019
7020 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
7021 if (n <= state.length) return n; // Don't have enough
7022
7023 if (!state.ended) {
7024 state.needReadable = true;
7025 return 0;
7026 }
7027
7028 return state.length;
7029} // you can override either this method, or the async _read(n) below.
7030
7031
7032Readable.prototype.read = function (n) {
7033 debug('read', n);
7034 n = parseInt(n, 10);
7035 var state = this._readableState;
7036 var nOrig = n;
7037 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
7038 // already have a bunch of data in the buffer, then just trigger
7039 // the 'readable' event and move on.
7040
7041 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
7042 debug('read: emitReadable', state.length, state.ended);
7043 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
7044 return null;
7045 }
7046
7047 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
7048
7049 if (n === 0 && state.ended) {
7050 if (state.length === 0) endReadable(this);
7051 return null;
7052 } // All the actual chunk generation logic needs to be
7053 // *below* the call to _read. The reason is that in certain
7054 // synthetic stream cases, such as passthrough streams, _read
7055 // may be a completely synchronous operation which may change
7056 // the state of the read buffer, providing enough data when
7057 // before there was *not* enough.
7058 //
7059 // So, the steps are:
7060 // 1. Figure out what the state of things will be after we do
7061 // a read from the buffer.
7062 //
7063 // 2. If that resulting state will trigger a _read, then call _read.
7064 // Note that this may be asynchronous, or synchronous. Yes, it is
7065 // deeply ugly to write APIs this way, but that still doesn't mean
7066 // that the Readable class should behave improperly, as streams are
7067 // designed to be sync/async agnostic.
7068 // Take note if the _read call is sync or async (ie, if the read call
7069 // has returned yet), so that we know whether or not it's safe to emit
7070 // 'readable' etc.
7071 //
7072 // 3. Actually pull the requested chunks out of the buffer and return.
7073 // if we need a readable event, then we need to do some reading.
7074
7075
7076 var doRead = state.needReadable;
7077 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
7078
7079 if (state.length === 0 || state.length - n < state.highWaterMark) {
7080 doRead = true;
7081 debug('length less than watermark', doRead);
7082 } // however, if we've ended, then there's no point, and if we're already
7083 // reading, then it's unnecessary.
7084
7085
7086 if (state.ended || state.reading) {
7087 doRead = false;
7088 debug('reading or ended', doRead);
7089 } else if (doRead) {
7090 debug('do read');
7091 state.reading = true;
7092 state.sync = true; // if the length is currently zero, then we *need* a readable event.
7093
7094 if (state.length === 0) state.needReadable = true; // call internal read method
7095
7096 this._read(state.highWaterMark);
7097
7098 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
7099 // and we need to re-evaluate how much data we can return to the user.
7100
7101 if (!state.reading) n = howMuchToRead(nOrig, state);
7102 }
7103
7104 var ret;
7105 if (n > 0) ret = fromList(n, state);else ret = null;
7106
7107 if (ret === null) {
7108 state.needReadable = state.length <= state.highWaterMark;
7109 n = 0;
7110 } else {
7111 state.length -= n;
7112 state.awaitDrain = 0;
7113 }
7114
7115 if (state.length === 0) {
7116 // If we have nothing in the buffer, then we want to know
7117 // as soon as we *do* get something into the buffer.
7118 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
7119
7120 if (nOrig !== n && state.ended) endReadable(this);
7121 }
7122
7123 if (ret !== null) this.emit('data', ret);
7124 return ret;
7125};
7126
7127function onEofChunk(stream, state) {
7128 debug('onEofChunk');
7129 if (state.ended) return;
7130
7131 if (state.decoder) {
7132 var chunk = state.decoder.end();
7133
7134 if (chunk && chunk.length) {
7135 state.buffer.push(chunk);
7136 state.length += state.objectMode ? 1 : chunk.length;
7137 }
7138 }
7139
7140 state.ended = true;
7141
7142 if (state.sync) {
7143 // if we are sync, wait until next tick to emit the data.
7144 // Otherwise we risk emitting data in the flow()
7145 // the readable code triggers during a read() call
7146 emitReadable(stream);
7147 } else {
7148 // emit 'readable' now to make sure it gets picked up.
7149 state.needReadable = false;
7150
7151 if (!state.emittedReadable) {
7152 state.emittedReadable = true;
7153 emitReadable_(stream);
7154 }
7155 }
7156} // Don't emit readable right away in sync mode, because this can trigger
7157// another read() call => stack overflow. This way, it might trigger
7158// a nextTick recursion warning, but that's not so bad.
7159
7160
7161function emitReadable(stream) {
7162 var state = stream._readableState;
7163 debug('emitReadable', state.needReadable, state.emittedReadable);
7164 state.needReadable = false;
7165
7166 if (!state.emittedReadable) {
7167 debug('emitReadable', state.flowing);
7168 state.emittedReadable = true;
7169 process.nextTick(emitReadable_, stream);
7170 }
7171}
7172
7173function emitReadable_(stream) {
7174 var state = stream._readableState;
7175 debug('emitReadable_', state.destroyed, state.length, state.ended);
7176
7177 if (!state.destroyed && (state.length || state.ended)) {
7178 stream.emit('readable');
7179 state.emittedReadable = false;
7180 } // The stream needs another readable event if
7181 // 1. It is not flowing, as the flow mechanism will take
7182 // care of it.
7183 // 2. It is not ended.
7184 // 3. It is below the highWaterMark, so we can schedule
7185 // another readable later.
7186
7187
7188 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
7189 flow(stream);
7190} // at this point, the user has presumably seen the 'readable' event,
7191// and called read() to consume some data. that may have triggered
7192// in turn another _read(n) call, in which case reading = true if
7193// it's in progress.
7194// However, if we're not ended, or reading, and the length < hwm,
7195// then go ahead and try to read some more preemptively.
7196
7197
7198function maybeReadMore(stream, state) {
7199 if (!state.readingMore) {
7200 state.readingMore = true;
7201 process.nextTick(maybeReadMore_, stream, state);
7202 }
7203}
7204
7205function maybeReadMore_(stream, state) {
7206 // Attempt to read more data if we should.
7207 //
7208 // The conditions for reading more data are (one of):
7209 // - Not enough data buffered (state.length < state.highWaterMark). The loop
7210 // is responsible for filling the buffer with enough data if such data
7211 // is available. If highWaterMark is 0 and we are not in the flowing mode
7212 // we should _not_ attempt to buffer any extra data. We'll get more data
7213 // when the stream consumer calls read() instead.
7214 // - No data in the buffer, and the stream is in flowing mode. In this mode
7215 // the loop below is responsible for ensuring read() is called. Failing to
7216 // call read here would abort the flow and there's no other mechanism for
7217 // continuing the flow if the stream consumer has just subscribed to the
7218 // 'data' event.
7219 //
7220 // In addition to the above conditions to keep reading data, the following
7221 // conditions prevent the data from being read:
7222 // - The stream has ended (state.ended).
7223 // - There is already a pending 'read' operation (state.reading). This is a
7224 // case where the the stream has called the implementation defined _read()
7225 // method, but they are processing the call asynchronously and have _not_
7226 // called push() with new data. In this case we skip performing more
7227 // read()s. The execution ends in this method again after the _read() ends
7228 // up calling push() with more data.
7229 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
7230 var len = state.length;
7231 debug('maybeReadMore read 0');
7232 stream.read(0);
7233 if (len === state.length) // didn't get any data, stop spinning.
7234 break;
7235 }
7236
7237 state.readingMore = false;
7238} // abstract method. to be overridden in specific implementation classes.
7239// call cb(er, data) where data is <= n in length.
7240// for virtual (non-string, non-buffer) streams, "length" is somewhat
7241// arbitrary, and perhaps not very meaningful.
7242
7243
7244Readable.prototype._read = function (n) {
7245 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
7246};
7247
7248Readable.prototype.pipe = function (dest, pipeOpts) {
7249 var src = this;
7250 var state = this._readableState;
7251
7252 switch (state.pipesCount) {
7253 case 0:
7254 state.pipes = dest;
7255 break;
7256
7257 case 1:
7258 state.pipes = [state.pipes, dest];
7259 break;
7260
7261 default:
7262 state.pipes.push(dest);
7263 break;
7264 }
7265
7266 state.pipesCount += 1;
7267 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
7268 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
7269 var endFn = doEnd ? onend : unpipe;
7270 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
7271 dest.on('unpipe', onunpipe);
7272
7273 function onunpipe(readable, unpipeInfo) {
7274 debug('onunpipe');
7275
7276 if (readable === src) {
7277 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
7278 unpipeInfo.hasUnpiped = true;
7279 cleanup();
7280 }
7281 }
7282 }
7283
7284 function onend() {
7285 debug('onend');
7286 dest.end();
7287 } // when the dest drains, it reduces the awaitDrain counter
7288 // on the source. This would be more elegant with a .once()
7289 // handler in flow(), but adding and removing repeatedly is
7290 // too slow.
7291
7292
7293 var ondrain = pipeOnDrain(src);
7294 dest.on('drain', ondrain);
7295 var cleanedUp = false;
7296
7297 function cleanup() {
7298 debug('cleanup'); // cleanup event handlers once the pipe is broken
7299
7300 dest.removeListener('close', onclose);
7301 dest.removeListener('finish', onfinish);
7302 dest.removeListener('drain', ondrain);
7303 dest.removeListener('error', onerror);
7304 dest.removeListener('unpipe', onunpipe);
7305 src.removeListener('end', onend);
7306 src.removeListener('end', unpipe);
7307 src.removeListener('data', ondata);
7308 cleanedUp = true; // if the reader is waiting for a drain event from this
7309 // specific writer, then it would cause it to never start
7310 // flowing again.
7311 // So, if this is awaiting a drain, then we just call it now.
7312 // If we don't know, then assume that we are waiting for one.
7313
7314 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
7315 }
7316
7317 src.on('data', ondata);
7318
7319 function ondata(chunk) {
7320 debug('ondata');
7321 var ret = dest.write(chunk);
7322 debug('dest.write', ret);
7323
7324 if (ret === false) {
7325 // If the user unpiped during `dest.write()`, it is possible
7326 // to get stuck in a permanently paused state if that write
7327 // also returned false.
7328 // => Check whether `dest` is still a piping destination.
7329 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
7330 debug('false write response, pause', state.awaitDrain);
7331 state.awaitDrain++;
7332 }
7333
7334 src.pause();
7335 }
7336 } // if the dest has an error, then stop piping into it.
7337 // however, don't suppress the throwing behavior for this.
7338
7339
7340 function onerror(er) {
7341 debug('onerror', er);
7342 unpipe();
7343 dest.removeListener('error', onerror);
7344 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
7345 } // Make sure our error handler is attached before userland ones.
7346
7347
7348 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
7349
7350 function onclose() {
7351 dest.removeListener('finish', onfinish);
7352 unpipe();
7353 }
7354
7355 dest.once('close', onclose);
7356
7357 function onfinish() {
7358 debug('onfinish');
7359 dest.removeListener('close', onclose);
7360 unpipe();
7361 }
7362
7363 dest.once('finish', onfinish);
7364
7365 function unpipe() {
7366 debug('unpipe');
7367 src.unpipe(dest);
7368 } // tell the dest that it's being piped to
7369
7370
7371 dest.emit('pipe', src); // start the flow if it hasn't been started already.
7372
7373 if (!state.flowing) {
7374 debug('pipe resume');
7375 src.resume();
7376 }
7377
7378 return dest;
7379};
7380
7381function pipeOnDrain(src) {
7382 return function pipeOnDrainFunctionResult() {
7383 var state = src._readableState;
7384 debug('pipeOnDrain', state.awaitDrain);
7385 if (state.awaitDrain) state.awaitDrain--;
7386
7387 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
7388 state.flowing = true;
7389 flow(src);
7390 }
7391 };
7392}
7393
7394Readable.prototype.unpipe = function (dest) {
7395 var state = this._readableState;
7396 var unpipeInfo = {
7397 hasUnpiped: false
7398 }; // if we're not piping anywhere, then do nothing.
7399
7400 if (state.pipesCount === 0) return this; // just one destination. most common case.
7401
7402 if (state.pipesCount === 1) {
7403 // passed in one, but it's not the right one.
7404 if (dest && dest !== state.pipes) return this;
7405 if (!dest) dest = state.pipes; // got a match.
7406
7407 state.pipes = null;
7408 state.pipesCount = 0;
7409 state.flowing = false;
7410 if (dest) dest.emit('unpipe', this, unpipeInfo);
7411 return this;
7412 } // slow case. multiple pipe destinations.
7413
7414
7415 if (!dest) {
7416 // remove all.
7417 var dests = state.pipes;
7418 var len = state.pipesCount;
7419 state.pipes = null;
7420 state.pipesCount = 0;
7421 state.flowing = false;
7422
7423 for (var i = 0; i < len; i++) {
7424 dests[i].emit('unpipe', this, {
7425 hasUnpiped: false
7426 });
7427 }
7428
7429 return this;
7430 } // try to find the right one.
7431
7432
7433 var index = indexOf(state.pipes, dest);
7434 if (index === -1) return this;
7435 state.pipes.splice(index, 1);
7436 state.pipesCount -= 1;
7437 if (state.pipesCount === 1) state.pipes = state.pipes[0];
7438 dest.emit('unpipe', this, unpipeInfo);
7439 return this;
7440}; // set up data events if they are asked for
7441// Ensure readable listeners eventually get something
7442
7443
7444Readable.prototype.on = function (ev, fn) {
7445 var res = Stream.prototype.on.call(this, ev, fn);
7446 var state = this._readableState;
7447
7448 if (ev === 'data') {
7449 // update readableListening so that resume() may be a no-op
7450 // a few lines down. This is needed to support once('readable').
7451 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
7452
7453 if (state.flowing !== false) this.resume();
7454 } else if (ev === 'readable') {
7455 if (!state.endEmitted && !state.readableListening) {
7456 state.readableListening = state.needReadable = true;
7457 state.flowing = false;
7458 state.emittedReadable = false;
7459 debug('on readable', state.length, state.reading);
7460
7461 if (state.length) {
7462 emitReadable(this);
7463 } else if (!state.reading) {
7464 process.nextTick(nReadingNextTick, this);
7465 }
7466 }
7467 }
7468
7469 return res;
7470};
7471
7472Readable.prototype.addListener = Readable.prototype.on;
7473
7474Readable.prototype.removeListener = function (ev, fn) {
7475 var res = Stream.prototype.removeListener.call(this, ev, fn);
7476
7477 if (ev === 'readable') {
7478 // We need to check if there is someone still listening to
7479 // readable and reset the state. However this needs to happen
7480 // after readable has been emitted but before I/O (nextTick) to
7481 // support once('readable', fn) cycles. This means that calling
7482 // resume within the same tick will have no
7483 // effect.
7484 process.nextTick(updateReadableListening, this);
7485 }
7486
7487 return res;
7488};
7489
7490Readable.prototype.removeAllListeners = function (ev) {
7491 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
7492
7493 if (ev === 'readable' || ev === undefined) {
7494 // We need to check if there is someone still listening to
7495 // readable and reset the state. However this needs to happen
7496 // after readable has been emitted but before I/O (nextTick) to
7497 // support once('readable', fn) cycles. This means that calling
7498 // resume within the same tick will have no
7499 // effect.
7500 process.nextTick(updateReadableListening, this);
7501 }
7502
7503 return res;
7504};
7505
7506function updateReadableListening(self) {
7507 var state = self._readableState;
7508 state.readableListening = self.listenerCount('readable') > 0;
7509
7510 if (state.resumeScheduled && !state.paused) {
7511 // flowing needs to be set to true now, otherwise
7512 // the upcoming resume will not flow.
7513 state.flowing = true; // crude way to check if we should resume
7514 } else if (self.listenerCount('data') > 0) {
7515 self.resume();
7516 }
7517}
7518
7519function nReadingNextTick(self) {
7520 debug('readable nexttick read 0');
7521 self.read(0);
7522} // pause() and resume() are remnants of the legacy readable stream API
7523// If the user uses them, then switch into old mode.
7524
7525
7526Readable.prototype.resume = function () {
7527 var state = this._readableState;
7528
7529 if (!state.flowing) {
7530 debug('resume'); // we flow only if there is no one listening
7531 // for readable, but we still have to call
7532 // resume()
7533
7534 state.flowing = !state.readableListening;
7535 resume(this, state);
7536 }
7537
7538 state.paused = false;
7539 return this;
7540};
7541
7542function resume(stream, state) {
7543 if (!state.resumeScheduled) {
7544 state.resumeScheduled = true;
7545 process.nextTick(resume_, stream, state);
7546 }
7547}
7548
7549function resume_(stream, state) {
7550 debug('resume', state.reading);
7551
7552 if (!state.reading) {
7553 stream.read(0);
7554 }
7555
7556 state.resumeScheduled = false;
7557 stream.emit('resume');
7558 flow(stream);
7559 if (state.flowing && !state.reading) stream.read(0);
7560}
7561
7562Readable.prototype.pause = function () {
7563 debug('call pause flowing=%j', this._readableState.flowing);
7564
7565 if (this._readableState.flowing !== false) {
7566 debug('pause');
7567 this._readableState.flowing = false;
7568 this.emit('pause');
7569 }
7570
7571 this._readableState.paused = true;
7572 return this;
7573};
7574
7575function flow(stream) {
7576 var state = stream._readableState;
7577 debug('flow', state.flowing);
7578
7579 while (state.flowing && stream.read() !== null) {
7580 ;
7581 }
7582} // wrap an old-style stream as the async data source.
7583// This is *not* part of the readable stream interface.
7584// It is an ugly unfortunate mess of history.
7585
7586
7587Readable.prototype.wrap = function (stream) {
7588 var _this = this;
7589
7590 var state = this._readableState;
7591 var paused = false;
7592 stream.on('end', function () {
7593 debug('wrapped end');
7594
7595 if (state.decoder && !state.ended) {
7596 var chunk = state.decoder.end();
7597 if (chunk && chunk.length) _this.push(chunk);
7598 }
7599
7600 _this.push(null);
7601 });
7602 stream.on('data', function (chunk) {
7603 debug('wrapped data');
7604 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
7605
7606 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
7607
7608 var ret = _this.push(chunk);
7609
7610 if (!ret) {
7611 paused = true;
7612 stream.pause();
7613 }
7614 }); // proxy all the other methods.
7615 // important when wrapping filters and duplexes.
7616
7617 for (var i in stream) {
7618 if (this[i] === undefined && typeof stream[i] === 'function') {
7619 this[i] = function methodWrap(method) {
7620 return function methodWrapReturnFunction() {
7621 return stream[method].apply(stream, arguments);
7622 };
7623 }(i);
7624 }
7625 } // proxy certain important events.
7626
7627
7628 for (var n = 0; n < kProxyEvents.length; n++) {
7629 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
7630 } // when we try to consume some more bytes, simply unpause the
7631 // underlying stream.
7632
7633
7634 this._read = function (n) {
7635 debug('wrapped _read', n);
7636
7637 if (paused) {
7638 paused = false;
7639 stream.resume();
7640 }
7641 };
7642
7643 return this;
7644};
7645
7646if (typeof Symbol === 'function') {
7647 Readable.prototype[Symbol.asyncIterator] = function () {
7648 if (createReadableStreamAsyncIterator === undefined) {
7649 createReadableStreamAsyncIterator = _dereq_(49);
7650 }
7651
7652 return createReadableStreamAsyncIterator(this);
7653 };
7654}
7655
7656Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
7657 // making it explicit this property is not enumerable
7658 // because otherwise some prototype manipulation in
7659 // userland will fail
7660 enumerable: false,
7661 get: function get() {
7662 return this._readableState.highWaterMark;
7663 }
7664});
7665Object.defineProperty(Readable.prototype, 'readableBuffer', {
7666 // making it explicit this property is not enumerable
7667 // because otherwise some prototype manipulation in
7668 // userland will fail
7669 enumerable: false,
7670 get: function get() {
7671 return this._readableState && this._readableState.buffer;
7672 }
7673});
7674Object.defineProperty(Readable.prototype, 'readableFlowing', {
7675 // making it explicit this property is not enumerable
7676 // because otherwise some prototype manipulation in
7677 // userland will fail
7678 enumerable: false,
7679 get: function get() {
7680 return this._readableState.flowing;
7681 },
7682 set: function set(state) {
7683 if (this._readableState) {
7684 this._readableState.flowing = state;
7685 }
7686 }
7687}); // exposed for testing purposes only.
7688
7689Readable._fromList = fromList;
7690Object.defineProperty(Readable.prototype, 'readableLength', {
7691 // making it explicit this property is not enumerable
7692 // because otherwise some prototype manipulation in
7693 // userland will fail
7694 enumerable: false,
7695 get: function get() {
7696 return this._readableState.length;
7697 }
7698}); // Pluck off n bytes from an array of buffers.
7699// Length is the combined lengths of all the buffers in the list.
7700// This function is designed to be inlinable, so please take care when making
7701// changes to the function body.
7702
7703function fromList(n, state) {
7704 // nothing buffered
7705 if (state.length === 0) return null;
7706 var ret;
7707 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
7708 // read it all, truncate the list
7709 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
7710 state.buffer.clear();
7711 } else {
7712 // read part of list
7713 ret = state.buffer.consume(n, state.decoder);
7714 }
7715 return ret;
7716}
7717
7718function endReadable(stream) {
7719 var state = stream._readableState;
7720 debug('endReadable', state.endEmitted);
7721
7722 if (!state.endEmitted) {
7723 state.ended = true;
7724 process.nextTick(endReadableNT, state, stream);
7725 }
7726}
7727
7728function endReadableNT(state, stream) {
7729 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
7730
7731 if (!state.endEmitted && state.length === 0) {
7732 state.endEmitted = true;
7733 stream.readable = false;
7734 stream.emit('end');
7735
7736 if (state.autoDestroy) {
7737 // In case of duplex streams we need a way to detect
7738 // if the writable side is ready for autoDestroy as well
7739 var wState = stream._writableState;
7740
7741 if (!wState || wState.autoDestroy && wState.finished) {
7742 stream.destroy();
7743 }
7744 }
7745 }
7746}
7747
7748if (typeof Symbol === 'function') {
7749 Readable.from = function (iterable, opts) {
7750 if (from === undefined) {
7751 from = _dereq_(53);
7752 }
7753
7754 return from(Readable, iterable, opts);
7755 };
7756}
7757
7758function indexOf(xs, x) {
7759 for (var i = 0, l = xs.length; i < l; i++) {
7760 if (xs[i] === x) return i;
7761 }
7762
7763 return -1;
7764}
7765}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7766},{"102":102,"11":11,"13":13,"26":26,"37":37,"43":43,"44":44,"49":49,"50":50,"51":51,"53":53,"55":55,"56":56,"73":73}],47:[function(_dereq_,module,exports){
7767// Copyright Joyent, Inc. and other Node contributors.
7768//
7769// Permission is hereby granted, free of charge, to any person obtaining a
7770// copy of this software and associated documentation files (the
7771// "Software"), to deal in the Software without restriction, including
7772// without limitation the rights to use, copy, modify, merge, publish,
7773// distribute, sublicense, and/or sell copies of the Software, and to permit
7774// persons to whom the Software is furnished to do so, subject to the
7775// following conditions:
7776//
7777// The above copyright notice and this permission notice shall be included
7778// in all copies or substantial portions of the Software.
7779//
7780// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7781// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7782// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7783// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7784// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7785// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7786// USE OR OTHER DEALINGS IN THE SOFTWARE.
7787// a transform stream is a readable/writable stream where you do
7788// something with the data. Sometimes it's called a "filter",
7789// but that's not a great name for it, since that implies a thing where
7790// some bits pass through, and others are simply ignored. (That would
7791// be a valid example of a transform, of course.)
7792//
7793// While the output is causally related to the input, it's not a
7794// necessarily symmetric or synchronous transformation. For example,
7795// a zlib stream might take multiple plain-text writes(), and then
7796// emit a single compressed chunk some time in the future.
7797//
7798// Here's how this works:
7799//
7800// The Transform stream has all the aspects of the readable and writable
7801// stream classes. When you write(chunk), that calls _write(chunk,cb)
7802// internally, and returns false if there's a lot of pending writes
7803// buffered up. When you call read(), that calls _read(n) until
7804// there's enough pending readable data buffered up.
7805//
7806// In a transform stream, the written data is placed in a buffer. When
7807// _read(n) is called, it transforms the queued up data, calling the
7808// buffered _write cb's as it consumes chunks. If consuming a single
7809// written chunk would result in multiple output chunks, then the first
7810// outputted bit calls the readcb, and subsequent chunks just go into
7811// the read buffer, and will cause it to emit 'readable' if necessary.
7812//
7813// This way, back-pressure is actually determined by the reading side,
7814// since _read has to be called to start processing a new chunk. However,
7815// a pathological inflate type of transform can cause excessive buffering
7816// here. For example, imagine a stream where every byte of input is
7817// interpreted as an integer from 0-255, and then results in that many
7818// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
7819// 1kb of data being output. In this case, you could write a very small
7820// amount of input, and end up with a very large amount of output. In
7821// such a pathological inflating mechanism, there'd be no way to tell
7822// the system to stop doing the transform. A single 4MB write could
7823// cause the system to run out of memory.
7824//
7825// However, even in such a pathological case, only a single written chunk
7826// would be consumed, and then the rest would wait (un-transformed) until
7827// the results of the previous transformed chunk were consumed.
7828'use strict';
7829
7830module.exports = Transform;
7831
7832var _require$codes = _dereq_(43).codes,
7833 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7834 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7835 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
7836 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
7837
7838var Duplex = _dereq_(44);
7839
7840_dereq_(37)(Transform, Duplex);
7841
7842function afterTransform(er, data) {
7843 var ts = this._transformState;
7844 ts.transforming = false;
7845 var cb = ts.writecb;
7846
7847 if (cb === null) {
7848 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
7849 }
7850
7851 ts.writechunk = null;
7852 ts.writecb = null;
7853 if (data != null) // single equals check for both `null` and `undefined`
7854 this.push(data);
7855 cb(er);
7856 var rs = this._readableState;
7857 rs.reading = false;
7858
7859 if (rs.needReadable || rs.length < rs.highWaterMark) {
7860 this._read(rs.highWaterMark);
7861 }
7862}
7863
7864function Transform(options) {
7865 if (!(this instanceof Transform)) return new Transform(options);
7866 Duplex.call(this, options);
7867 this._transformState = {
7868 afterTransform: afterTransform.bind(this),
7869 needTransform: false,
7870 transforming: false,
7871 writecb: null,
7872 writechunk: null,
7873 writeencoding: null
7874 }; // start out asking for a readable event once data is transformed.
7875
7876 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
7877 // that Readable wants before the first _read call, so unset the
7878 // sync guard flag.
7879
7880 this._readableState.sync = false;
7881
7882 if (options) {
7883 if (typeof options.transform === 'function') this._transform = options.transform;
7884 if (typeof options.flush === 'function') this._flush = options.flush;
7885 } // When the writable side finishes, then flush out anything remaining.
7886
7887
7888 this.on('prefinish', prefinish);
7889}
7890
7891function prefinish() {
7892 var _this = this;
7893
7894 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
7895 this._flush(function (er, data) {
7896 done(_this, er, data);
7897 });
7898 } else {
7899 done(this, null, null);
7900 }
7901}
7902
7903Transform.prototype.push = function (chunk, encoding) {
7904 this._transformState.needTransform = false;
7905 return Duplex.prototype.push.call(this, chunk, encoding);
7906}; // This is the part where you do stuff!
7907// override this function in implementation classes.
7908// 'chunk' is an input chunk.
7909//
7910// Call `push(newChunk)` to pass along transformed output
7911// to the readable side. You may call 'push' zero or more times.
7912//
7913// Call `cb(err)` when you are done with this chunk. If you pass
7914// an error, then that'll put the hurt on the whole operation. If you
7915// never call cb(), then you'll never get another chunk.
7916
7917
7918Transform.prototype._transform = function (chunk, encoding, cb) {
7919 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
7920};
7921
7922Transform.prototype._write = function (chunk, encoding, cb) {
7923 var ts = this._transformState;
7924 ts.writecb = cb;
7925 ts.writechunk = chunk;
7926 ts.writeencoding = encoding;
7927
7928 if (!ts.transforming) {
7929 var rs = this._readableState;
7930 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
7931 }
7932}; // Doesn't matter what the args are here.
7933// _transform does all the work.
7934// That we got here means that the readable side wants more data.
7935
7936
7937Transform.prototype._read = function (n) {
7938 var ts = this._transformState;
7939
7940 if (ts.writechunk !== null && !ts.transforming) {
7941 ts.transforming = true;
7942
7943 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
7944 } else {
7945 // mark that we need a transform, so that any data that comes in
7946 // will get processed, now that we've asked for it.
7947 ts.needTransform = true;
7948 }
7949};
7950
7951Transform.prototype._destroy = function (err, cb) {
7952 Duplex.prototype._destroy.call(this, err, function (err2) {
7953 cb(err2);
7954 });
7955};
7956
7957function done(stream, er, data) {
7958 if (er) return stream.emit('error', er);
7959 if (data != null) // single equals check for both `null` and `undefined`
7960 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
7961 // if there's nothing in the write buffer, then that means
7962 // that nothing more will ever be provided
7963
7964 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
7965 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
7966 return stream.push(null);
7967}
7968},{"37":37,"43":43,"44":44}],48:[function(_dereq_,module,exports){
7969(function (process,global){(function (){
7970// Copyright Joyent, Inc. and other Node contributors.
7971//
7972// Permission is hereby granted, free of charge, to any person obtaining a
7973// copy of this software and associated documentation files (the
7974// "Software"), to deal in the Software without restriction, including
7975// without limitation the rights to use, copy, modify, merge, publish,
7976// distribute, sublicense, and/or sell copies of the Software, and to permit
7977// persons to whom the Software is furnished to do so, subject to the
7978// following conditions:
7979//
7980// The above copyright notice and this permission notice shall be included
7981// in all copies or substantial portions of the Software.
7982//
7983// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7984// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7985// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7986// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7987// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7988// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7989// USE OR OTHER DEALINGS IN THE SOFTWARE.
7990// A bit simpler than readable streams.
7991// Implement an async ._write(chunk, encoding, cb), and it'll handle all
7992// the drain event emission and buffering.
7993'use strict';
7994
7995module.exports = Writable;
7996/* <replacement> */
7997
7998function WriteReq(chunk, encoding, cb) {
7999 this.chunk = chunk;
8000 this.encoding = encoding;
8001 this.callback = cb;
8002 this.next = null;
8003} // It seems a linked list but it is not
8004// there will be only 2 of these for each stream
8005
8006
8007function CorkedRequest(state) {
8008 var _this = this;
8009
8010 this.next = null;
8011 this.entry = null;
8012
8013 this.finish = function () {
8014 onCorkedFinish(_this, state);
8015 };
8016}
8017/* </replacement> */
8018
8019/*<replacement>*/
8020
8021
8022var Duplex;
8023/*</replacement>*/
8024
8025Writable.WritableState = WritableState;
8026/*<replacement>*/
8027
8028var internalUtil = {
8029 deprecate: _dereq_(121)
8030};
8031/*</replacement>*/
8032
8033/*<replacement>*/
8034
8035var Stream = _dereq_(56);
8036/*</replacement>*/
8037
8038
8039var Buffer = _dereq_(13).Buffer;
8040
8041var OurUint8Array = global.Uint8Array || function () {};
8042
8043function _uint8ArrayToBuffer(chunk) {
8044 return Buffer.from(chunk);
8045}
8046
8047function _isUint8Array(obj) {
8048 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
8049}
8050
8051var destroyImpl = _dereq_(51);
8052
8053var _require = _dereq_(55),
8054 getHighWaterMark = _require.getHighWaterMark;
8055
8056var _require$codes = _dereq_(43).codes,
8057 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
8058 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
8059 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
8060 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
8061 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
8062 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
8063 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
8064 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
8065
8066var errorOrDestroy = destroyImpl.errorOrDestroy;
8067
8068_dereq_(37)(Writable, Stream);
8069
8070function nop() {}
8071
8072function WritableState(options, stream, isDuplex) {
8073 Duplex = Duplex || _dereq_(44);
8074 options = options || {}; // Duplex streams are both readable and writable, but share
8075 // the same options object.
8076 // However, some cases require setting options to different
8077 // values for the readable and the writable sides of the duplex stream,
8078 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
8079
8080 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
8081 // contains buffers or objects.
8082
8083 this.objectMode = !!options.objectMode;
8084 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
8085 // Note: 0 is a valid value, means that we always return false if
8086 // the entire buffer is not flushed immediately on write()
8087
8088 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
8089
8090 this.finalCalled = false; // drain event flag.
8091
8092 this.needDrain = false; // at the start of calling end()
8093
8094 this.ending = false; // when end() has been called, and returned
8095
8096 this.ended = false; // when 'finish' is emitted
8097
8098 this.finished = false; // has it been destroyed
8099
8100 this.destroyed = false; // should we decode strings into buffers before passing to _write?
8101 // this is here so that some node-core streams can optimize string
8102 // handling at a lower level.
8103
8104 var noDecode = options.decodeStrings === false;
8105 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
8106 // encoding is 'binary' so we have to make this configurable.
8107 // Everything else in the universe uses 'utf8', though.
8108
8109 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
8110 // of how much we're waiting to get pushed to some underlying
8111 // socket or file.
8112
8113 this.length = 0; // a flag to see when we're in the middle of a write.
8114
8115 this.writing = false; // when true all writes will be buffered until .uncork() call
8116
8117 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
8118 // or on a later tick. We set this to true at first, because any
8119 // actions that shouldn't happen until "later" should generally also
8120 // not happen before the first write call.
8121
8122 this.sync = true; // a flag to know if we're processing previously buffered items, which
8123 // may call the _write() callback in the same tick, so that we don't
8124 // end up in an overlapped onwrite situation.
8125
8126 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
8127
8128 this.onwrite = function (er) {
8129 onwrite(stream, er);
8130 }; // the callback that the user supplies to write(chunk,encoding,cb)
8131
8132
8133 this.writecb = null; // the amount that is being written when _write is called.
8134
8135 this.writelen = 0;
8136 this.bufferedRequest = null;
8137 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
8138 // this must be 0 before 'finish' can be emitted
8139
8140 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
8141 // This is relevant for synchronous Transform streams
8142
8143 this.prefinished = false; // True if the error was already emitted and should not be thrown again
8144
8145 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
8146
8147 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
8148
8149 this.autoDestroy = !!options.autoDestroy; // count buffered requests
8150
8151 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
8152 // one allocated and free to use, and we maintain at most two
8153
8154 this.corkedRequestsFree = new CorkedRequest(this);
8155}
8156
8157WritableState.prototype.getBuffer = function getBuffer() {
8158 var current = this.bufferedRequest;
8159 var out = [];
8160
8161 while (current) {
8162 out.push(current);
8163 current = current.next;
8164 }
8165
8166 return out;
8167};
8168
8169(function () {
8170 try {
8171 Object.defineProperty(WritableState.prototype, 'buffer', {
8172 get: internalUtil.deprecate(function writableStateBufferGetter() {
8173 return this.getBuffer();
8174 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
8175 });
8176 } catch (_) {}
8177})(); // Test _writableState for inheritance to account for Duplex streams,
8178// whose prototype chain only points to Readable.
8179
8180
8181var realHasInstance;
8182
8183if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
8184 realHasInstance = Function.prototype[Symbol.hasInstance];
8185 Object.defineProperty(Writable, Symbol.hasInstance, {
8186 value: function value(object) {
8187 if (realHasInstance.call(this, object)) return true;
8188 if (this !== Writable) return false;
8189 return object && object._writableState instanceof WritableState;
8190 }
8191 });
8192} else {
8193 realHasInstance = function realHasInstance(object) {
8194 return object instanceof this;
8195 };
8196}
8197
8198function Writable(options) {
8199 Duplex = Duplex || _dereq_(44); // Writable ctor is applied to Duplexes, too.
8200 // `realHasInstance` is necessary because using plain `instanceof`
8201 // would return false, as no `_writableState` property is attached.
8202 // Trying to use the custom `instanceof` for Writable here will also break the
8203 // Node.js LazyTransform implementation, which has a non-trivial getter for
8204 // `_writableState` that would lead to infinite recursion.
8205 // Checking for a Stream.Duplex instance is faster here instead of inside
8206 // the WritableState constructor, at least with V8 6.5
8207
8208 var isDuplex = this instanceof Duplex;
8209 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
8210 this._writableState = new WritableState(options, this, isDuplex); // legacy.
8211
8212 this.writable = true;
8213
8214 if (options) {
8215 if (typeof options.write === 'function') this._write = options.write;
8216 if (typeof options.writev === 'function') this._writev = options.writev;
8217 if (typeof options.destroy === 'function') this._destroy = options.destroy;
8218 if (typeof options.final === 'function') this._final = options.final;
8219 }
8220
8221 Stream.call(this);
8222} // Otherwise people can pipe Writable streams, which is just wrong.
8223
8224
8225Writable.prototype.pipe = function () {
8226 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
8227};
8228
8229function writeAfterEnd(stream, cb) {
8230 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
8231
8232 errorOrDestroy(stream, er);
8233 process.nextTick(cb, er);
8234} // Checks that a user-supplied chunk is valid, especially for the particular
8235// mode the stream is in. Currently this means that `null` is never accepted
8236// and undefined/non-string values are only allowed in object mode.
8237
8238
8239function validChunk(stream, state, chunk, cb) {
8240 var er;
8241
8242 if (chunk === null) {
8243 er = new ERR_STREAM_NULL_VALUES();
8244 } else if (typeof chunk !== 'string' && !state.objectMode) {
8245 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
8246 }
8247
8248 if (er) {
8249 errorOrDestroy(stream, er);
8250 process.nextTick(cb, er);
8251 return false;
8252 }
8253
8254 return true;
8255}
8256
8257Writable.prototype.write = function (chunk, encoding, cb) {
8258 var state = this._writableState;
8259 var ret = false;
8260
8261 var isBuf = !state.objectMode && _isUint8Array(chunk);
8262
8263 if (isBuf && !Buffer.isBuffer(chunk)) {
8264 chunk = _uint8ArrayToBuffer(chunk);
8265 }
8266
8267 if (typeof encoding === 'function') {
8268 cb = encoding;
8269 encoding = null;
8270 }
8271
8272 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
8273 if (typeof cb !== 'function') cb = nop;
8274 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
8275 state.pendingcb++;
8276 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
8277 }
8278 return ret;
8279};
8280
8281Writable.prototype.cork = function () {
8282 this._writableState.corked++;
8283};
8284
8285Writable.prototype.uncork = function () {
8286 var state = this._writableState;
8287
8288 if (state.corked) {
8289 state.corked--;
8290 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
8291 }
8292};
8293
8294Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
8295 // node::ParseEncoding() requires lower case.
8296 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
8297 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
8298 this._writableState.defaultEncoding = encoding;
8299 return this;
8300};
8301
8302Object.defineProperty(Writable.prototype, 'writableBuffer', {
8303 // making it explicit this property is not enumerable
8304 // because otherwise some prototype manipulation in
8305 // userland will fail
8306 enumerable: false,
8307 get: function get() {
8308 return this._writableState && this._writableState.getBuffer();
8309 }
8310});
8311
8312function decodeChunk(state, chunk, encoding) {
8313 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
8314 chunk = Buffer.from(chunk, encoding);
8315 }
8316
8317 return chunk;
8318}
8319
8320Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
8321 // making it explicit this property is not enumerable
8322 // because otherwise some prototype manipulation in
8323 // userland will fail
8324 enumerable: false,
8325 get: function get() {
8326 return this._writableState.highWaterMark;
8327 }
8328}); // if we're already writing something, then just put this
8329// in the queue, and wait our turn. Otherwise, call _write
8330// If we return false, then we need a drain event, so set that flag.
8331
8332function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
8333 if (!isBuf) {
8334 var newChunk = decodeChunk(state, chunk, encoding);
8335
8336 if (chunk !== newChunk) {
8337 isBuf = true;
8338 encoding = 'buffer';
8339 chunk = newChunk;
8340 }
8341 }
8342
8343 var len = state.objectMode ? 1 : chunk.length;
8344 state.length += len;
8345 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
8346
8347 if (!ret) state.needDrain = true;
8348
8349 if (state.writing || state.corked) {
8350 var last = state.lastBufferedRequest;
8351 state.lastBufferedRequest = {
8352 chunk: chunk,
8353 encoding: encoding,
8354 isBuf: isBuf,
8355 callback: cb,
8356 next: null
8357 };
8358
8359 if (last) {
8360 last.next = state.lastBufferedRequest;
8361 } else {
8362 state.bufferedRequest = state.lastBufferedRequest;
8363 }
8364
8365 state.bufferedRequestCount += 1;
8366 } else {
8367 doWrite(stream, state, false, len, chunk, encoding, cb);
8368 }
8369
8370 return ret;
8371}
8372
8373function doWrite(stream, state, writev, len, chunk, encoding, cb) {
8374 state.writelen = len;
8375 state.writecb = cb;
8376 state.writing = true;
8377 state.sync = true;
8378 if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
8379 state.sync = false;
8380}
8381
8382function onwriteError(stream, state, sync, er, cb) {
8383 --state.pendingcb;
8384
8385 if (sync) {
8386 // defer the callback if we are being called synchronously
8387 // to avoid piling up things on the stack
8388 process.nextTick(cb, er); // this can emit finish, and it will always happen
8389 // after error
8390
8391 process.nextTick(finishMaybe, stream, state);
8392 stream._writableState.errorEmitted = true;
8393 errorOrDestroy(stream, er);
8394 } else {
8395 // the caller expect this to happen before if
8396 // it is async
8397 cb(er);
8398 stream._writableState.errorEmitted = true;
8399 errorOrDestroy(stream, er); // this can emit finish, but finish must
8400 // always follow error
8401
8402 finishMaybe(stream, state);
8403 }
8404}
8405
8406function onwriteStateUpdate(state) {
8407 state.writing = false;
8408 state.writecb = null;
8409 state.length -= state.writelen;
8410 state.writelen = 0;
8411}
8412
8413function onwrite(stream, er) {
8414 var state = stream._writableState;
8415 var sync = state.sync;
8416 var cb = state.writecb;
8417 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
8418 onwriteStateUpdate(state);
8419 if (er) onwriteError(stream, state, sync, er, cb);else {
8420 // Check if we're actually ready to finish, but don't emit yet
8421 var finished = needFinish(state) || stream.destroyed;
8422
8423 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
8424 clearBuffer(stream, state);
8425 }
8426
8427 if (sync) {
8428 process.nextTick(afterWrite, stream, state, finished, cb);
8429 } else {
8430 afterWrite(stream, state, finished, cb);
8431 }
8432 }
8433}
8434
8435function afterWrite(stream, state, finished, cb) {
8436 if (!finished) onwriteDrain(stream, state);
8437 state.pendingcb--;
8438 cb();
8439 finishMaybe(stream, state);
8440} // Must force callback to be called on nextTick, so that we don't
8441// emit 'drain' before the write() consumer gets the 'false' return
8442// value, and has a chance to attach a 'drain' listener.
8443
8444
8445function onwriteDrain(stream, state) {
8446 if (state.length === 0 && state.needDrain) {
8447 state.needDrain = false;
8448 stream.emit('drain');
8449 }
8450} // if there's something in the buffer waiting, then process it
8451
8452
8453function clearBuffer(stream, state) {
8454 state.bufferProcessing = true;
8455 var entry = state.bufferedRequest;
8456
8457 if (stream._writev && entry && entry.next) {
8458 // Fast case, write everything using _writev()
8459 var l = state.bufferedRequestCount;
8460 var buffer = new Array(l);
8461 var holder = state.corkedRequestsFree;
8462 holder.entry = entry;
8463 var count = 0;
8464 var allBuffers = true;
8465
8466 while (entry) {
8467 buffer[count] = entry;
8468 if (!entry.isBuf) allBuffers = false;
8469 entry = entry.next;
8470 count += 1;
8471 }
8472
8473 buffer.allBuffers = allBuffers;
8474 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
8475 // as the hot path ends with doWrite
8476
8477 state.pendingcb++;
8478 state.lastBufferedRequest = null;
8479
8480 if (holder.next) {
8481 state.corkedRequestsFree = holder.next;
8482 holder.next = null;
8483 } else {
8484 state.corkedRequestsFree = new CorkedRequest(state);
8485 }
8486
8487 state.bufferedRequestCount = 0;
8488 } else {
8489 // Slow case, write chunks one-by-one
8490 while (entry) {
8491 var chunk = entry.chunk;
8492 var encoding = entry.encoding;
8493 var cb = entry.callback;
8494 var len = state.objectMode ? 1 : chunk.length;
8495 doWrite(stream, state, false, len, chunk, encoding, cb);
8496 entry = entry.next;
8497 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
8498 // it means that we need to wait until it does.
8499 // also, that means that the chunk and cb are currently
8500 // being processed, so move the buffer counter past them.
8501
8502 if (state.writing) {
8503 break;
8504 }
8505 }
8506
8507 if (entry === null) state.lastBufferedRequest = null;
8508 }
8509
8510 state.bufferedRequest = entry;
8511 state.bufferProcessing = false;
8512}
8513
8514Writable.prototype._write = function (chunk, encoding, cb) {
8515 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
8516};
8517
8518Writable.prototype._writev = null;
8519
8520Writable.prototype.end = function (chunk, encoding, cb) {
8521 var state = this._writableState;
8522
8523 if (typeof chunk === 'function') {
8524 cb = chunk;
8525 chunk = null;
8526 encoding = null;
8527 } else if (typeof encoding === 'function') {
8528 cb = encoding;
8529 encoding = null;
8530 }
8531
8532 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
8533
8534 if (state.corked) {
8535 state.corked = 1;
8536 this.uncork();
8537 } // ignore unnecessary end() calls.
8538
8539
8540 if (!state.ending) endWritable(this, state, cb);
8541 return this;
8542};
8543
8544Object.defineProperty(Writable.prototype, 'writableLength', {
8545 // making it explicit this property is not enumerable
8546 // because otherwise some prototype manipulation in
8547 // userland will fail
8548 enumerable: false,
8549 get: function get() {
8550 return this._writableState.length;
8551 }
8552});
8553
8554function needFinish(state) {
8555 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
8556}
8557
8558function callFinal(stream, state) {
8559 stream._final(function (err) {
8560 state.pendingcb--;
8561
8562 if (err) {
8563 errorOrDestroy(stream, err);
8564 }
8565
8566 state.prefinished = true;
8567 stream.emit('prefinish');
8568 finishMaybe(stream, state);
8569 });
8570}
8571
8572function prefinish(stream, state) {
8573 if (!state.prefinished && !state.finalCalled) {
8574 if (typeof stream._final === 'function' && !state.destroyed) {
8575 state.pendingcb++;
8576 state.finalCalled = true;
8577 process.nextTick(callFinal, stream, state);
8578 } else {
8579 state.prefinished = true;
8580 stream.emit('prefinish');
8581 }
8582 }
8583}
8584
8585function finishMaybe(stream, state) {
8586 var need = needFinish(state);
8587
8588 if (need) {
8589 prefinish(stream, state);
8590
8591 if (state.pendingcb === 0) {
8592 state.finished = true;
8593 stream.emit('finish');
8594
8595 if (state.autoDestroy) {
8596 // In case of duplex streams we need a way to detect
8597 // if the readable side is ready for autoDestroy as well
8598 var rState = stream._readableState;
8599
8600 if (!rState || rState.autoDestroy && rState.endEmitted) {
8601 stream.destroy();
8602 }
8603 }
8604 }
8605 }
8606
8607 return need;
8608}
8609
8610function endWritable(stream, state, cb) {
8611 state.ending = true;
8612 finishMaybe(stream, state);
8613
8614 if (cb) {
8615 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
8616 }
8617
8618 state.ended = true;
8619 stream.writable = false;
8620}
8621
8622function onCorkedFinish(corkReq, state, err) {
8623 var entry = corkReq.entry;
8624 corkReq.entry = null;
8625
8626 while (entry) {
8627 var cb = entry.callback;
8628 state.pendingcb--;
8629 cb(err);
8630 entry = entry.next;
8631 } // reuse the free corkReq.
8632
8633
8634 state.corkedRequestsFree.next = corkReq;
8635}
8636
8637Object.defineProperty(Writable.prototype, 'destroyed', {
8638 // making it explicit this property is not enumerable
8639 // because otherwise some prototype manipulation in
8640 // userland will fail
8641 enumerable: false,
8642 get: function get() {
8643 if (this._writableState === undefined) {
8644 return false;
8645 }
8646
8647 return this._writableState.destroyed;
8648 },
8649 set: function set(value) {
8650 // we ignore the value if the stream
8651 // has not been initialized yet
8652 if (!this._writableState) {
8653 return;
8654 } // backward compatibility, the user is explicitly
8655 // managing destroyed
8656
8657
8658 this._writableState.destroyed = value;
8659 }
8660});
8661Writable.prototype.destroy = destroyImpl.destroy;
8662Writable.prototype._undestroy = destroyImpl.undestroy;
8663
8664Writable.prototype._destroy = function (err, cb) {
8665 cb(err);
8666};
8667}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8668},{"121":121,"13":13,"37":37,"43":43,"44":44,"51":51,"55":55,"56":56,"73":73}],49:[function(_dereq_,module,exports){
8669(function (process){(function (){
8670'use strict';
8671
8672var _Object$setPrototypeO;
8673
8674function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
8675
8676var finished = _dereq_(52);
8677
8678var kLastResolve = Symbol('lastResolve');
8679var kLastReject = Symbol('lastReject');
8680var kError = Symbol('error');
8681var kEnded = Symbol('ended');
8682var kLastPromise = Symbol('lastPromise');
8683var kHandlePromise = Symbol('handlePromise');
8684var kStream = Symbol('stream');
8685
8686function createIterResult(value, done) {
8687 return {
8688 value: value,
8689 done: done
8690 };
8691}
8692
8693function readAndResolve(iter) {
8694 var resolve = iter[kLastResolve];
8695
8696 if (resolve !== null) {
8697 var data = iter[kStream].read(); // we defer if data is null
8698 // we can be expecting either 'end' or
8699 // 'error'
8700
8701 if (data !== null) {
8702 iter[kLastPromise] = null;
8703 iter[kLastResolve] = null;
8704 iter[kLastReject] = null;
8705 resolve(createIterResult(data, false));
8706 }
8707 }
8708}
8709
8710function onReadable(iter) {
8711 // we wait for the next tick, because it might
8712 // emit an error with process.nextTick
8713 process.nextTick(readAndResolve, iter);
8714}
8715
8716function wrapForNext(lastPromise, iter) {
8717 return function (resolve, reject) {
8718 lastPromise.then(function () {
8719 if (iter[kEnded]) {
8720 resolve(createIterResult(undefined, true));
8721 return;
8722 }
8723
8724 iter[kHandlePromise](resolve, reject);
8725 }, reject);
8726 };
8727}
8728
8729var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
8730var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
8731 get stream() {
8732 return this[kStream];
8733 },
8734
8735 next: function next() {
8736 var _this = this;
8737
8738 // if we have detected an error in the meanwhile
8739 // reject straight away
8740 var error = this[kError];
8741
8742 if (error !== null) {
8743 return Promise.reject(error);
8744 }
8745
8746 if (this[kEnded]) {
8747 return Promise.resolve(createIterResult(undefined, true));
8748 }
8749
8750 if (this[kStream].destroyed) {
8751 // We need to defer via nextTick because if .destroy(err) is
8752 // called, the error will be emitted via nextTick, and
8753 // we cannot guarantee that there is no error lingering around
8754 // waiting to be emitted.
8755 return new Promise(function (resolve, reject) {
8756 process.nextTick(function () {
8757 if (_this[kError]) {
8758 reject(_this[kError]);
8759 } else {
8760 resolve(createIterResult(undefined, true));
8761 }
8762 });
8763 });
8764 } // if we have multiple next() calls
8765 // we will wait for the previous Promise to finish
8766 // this logic is optimized to support for await loops,
8767 // where next() is only called once at a time
8768
8769
8770 var lastPromise = this[kLastPromise];
8771 var promise;
8772
8773 if (lastPromise) {
8774 promise = new Promise(wrapForNext(lastPromise, this));
8775 } else {
8776 // fast path needed to support multiple this.push()
8777 // without triggering the next() queue
8778 var data = this[kStream].read();
8779
8780 if (data !== null) {
8781 return Promise.resolve(createIterResult(data, false));
8782 }
8783
8784 promise = new Promise(this[kHandlePromise]);
8785 }
8786
8787 this[kLastPromise] = promise;
8788 return promise;
8789 }
8790}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
8791 return this;
8792}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
8793 var _this2 = this;
8794
8795 // destroy(err, cb) is a private API
8796 // we can guarantee we have that here, because we control the
8797 // Readable class this is attached to
8798 return new Promise(function (resolve, reject) {
8799 _this2[kStream].destroy(null, function (err) {
8800 if (err) {
8801 reject(err);
8802 return;
8803 }
8804
8805 resolve(createIterResult(undefined, true));
8806 });
8807 });
8808}), _Object$setPrototypeO), AsyncIteratorPrototype);
8809
8810var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
8811 var _Object$create;
8812
8813 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
8814 value: stream,
8815 writable: true
8816 }), _defineProperty(_Object$create, kLastResolve, {
8817 value: null,
8818 writable: true
8819 }), _defineProperty(_Object$create, kLastReject, {
8820 value: null,
8821 writable: true
8822 }), _defineProperty(_Object$create, kError, {
8823 value: null,
8824 writable: true
8825 }), _defineProperty(_Object$create, kEnded, {
8826 value: stream._readableState.endEmitted,
8827 writable: true
8828 }), _defineProperty(_Object$create, kHandlePromise, {
8829 value: function value(resolve, reject) {
8830 var data = iterator[kStream].read();
8831
8832 if (data) {
8833 iterator[kLastPromise] = null;
8834 iterator[kLastResolve] = null;
8835 iterator[kLastReject] = null;
8836 resolve(createIterResult(data, false));
8837 } else {
8838 iterator[kLastResolve] = resolve;
8839 iterator[kLastReject] = reject;
8840 }
8841 },
8842 writable: true
8843 }), _Object$create));
8844 iterator[kLastPromise] = null;
8845 finished(stream, function (err) {
8846 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
8847 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
8848 // returned by next() and store the error
8849
8850 if (reject !== null) {
8851 iterator[kLastPromise] = null;
8852 iterator[kLastResolve] = null;
8853 iterator[kLastReject] = null;
8854 reject(err);
8855 }
8856
8857 iterator[kError] = err;
8858 return;
8859 }
8860
8861 var resolve = iterator[kLastResolve];
8862
8863 if (resolve !== null) {
8864 iterator[kLastPromise] = null;
8865 iterator[kLastResolve] = null;
8866 iterator[kLastReject] = null;
8867 resolve(createIterResult(undefined, true));
8868 }
8869
8870 iterator[kEnded] = true;
8871 });
8872 stream.on('readable', onReadable.bind(null, iterator));
8873 return iterator;
8874};
8875
8876module.exports = createReadableStreamAsyncIterator;
8877}).call(this)}).call(this,_dereq_(73))
8878},{"52":52,"73":73}],50:[function(_dereq_,module,exports){
8879'use strict';
8880
8881function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
8882
8883function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
8884
8885function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
8886
8887function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8888
8889function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
8890
8891function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
8892
8893var _require = _dereq_(13),
8894 Buffer = _require.Buffer;
8895
8896var _require2 = _dereq_(11),
8897 inspect = _require2.inspect;
8898
8899var custom = inspect && inspect.custom || 'inspect';
8900
8901function copyBuffer(src, target, offset) {
8902 Buffer.prototype.copy.call(src, target, offset);
8903}
8904
8905module.exports =
8906/*#__PURE__*/
8907function () {
8908 function BufferList() {
8909 _classCallCheck(this, BufferList);
8910
8911 this.head = null;
8912 this.tail = null;
8913 this.length = 0;
8914 }
8915
8916 _createClass(BufferList, [{
8917 key: "push",
8918 value: function push(v) {
8919 var entry = {
8920 data: v,
8921 next: null
8922 };
8923 if (this.length > 0) this.tail.next = entry;else this.head = entry;
8924 this.tail = entry;
8925 ++this.length;
8926 }
8927 }, {
8928 key: "unshift",
8929 value: function unshift(v) {
8930 var entry = {
8931 data: v,
8932 next: this.head
8933 };
8934 if (this.length === 0) this.tail = entry;
8935 this.head = entry;
8936 ++this.length;
8937 }
8938 }, {
8939 key: "shift",
8940 value: function shift() {
8941 if (this.length === 0) return;
8942 var ret = this.head.data;
8943 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
8944 --this.length;
8945 return ret;
8946 }
8947 }, {
8948 key: "clear",
8949 value: function clear() {
8950 this.head = this.tail = null;
8951 this.length = 0;
8952 }
8953 }, {
8954 key: "join",
8955 value: function join(s) {
8956 if (this.length === 0) return '';
8957 var p = this.head;
8958 var ret = '' + p.data;
8959
8960 while (p = p.next) {
8961 ret += s + p.data;
8962 }
8963
8964 return ret;
8965 }
8966 }, {
8967 key: "concat",
8968 value: function concat(n) {
8969 if (this.length === 0) return Buffer.alloc(0);
8970 var ret = Buffer.allocUnsafe(n >>> 0);
8971 var p = this.head;
8972 var i = 0;
8973
8974 while (p) {
8975 copyBuffer(p.data, ret, i);
8976 i += p.data.length;
8977 p = p.next;
8978 }
8979
8980 return ret;
8981 } // Consumes a specified amount of bytes or characters from the buffered data.
8982
8983 }, {
8984 key: "consume",
8985 value: function consume(n, hasStrings) {
8986 var ret;
8987
8988 if (n < this.head.data.length) {
8989 // `slice` is the same for buffers and strings.
8990 ret = this.head.data.slice(0, n);
8991 this.head.data = this.head.data.slice(n);
8992 } else if (n === this.head.data.length) {
8993 // First chunk is a perfect match.
8994 ret = this.shift();
8995 } else {
8996 // Result spans more than one buffer.
8997 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
8998 }
8999
9000 return ret;
9001 }
9002 }, {
9003 key: "first",
9004 value: function first() {
9005 return this.head.data;
9006 } // Consumes a specified amount of characters from the buffered data.
9007
9008 }, {
9009 key: "_getString",
9010 value: function _getString(n) {
9011 var p = this.head;
9012 var c = 1;
9013 var ret = p.data;
9014 n -= ret.length;
9015
9016 while (p = p.next) {
9017 var str = p.data;
9018 var nb = n > str.length ? str.length : n;
9019 if (nb === str.length) ret += str;else ret += str.slice(0, n);
9020 n -= nb;
9021
9022 if (n === 0) {
9023 if (nb === str.length) {
9024 ++c;
9025 if (p.next) this.head = p.next;else this.head = this.tail = null;
9026 } else {
9027 this.head = p;
9028 p.data = str.slice(nb);
9029 }
9030
9031 break;
9032 }
9033
9034 ++c;
9035 }
9036
9037 this.length -= c;
9038 return ret;
9039 } // Consumes a specified amount of bytes from the buffered data.
9040
9041 }, {
9042 key: "_getBuffer",
9043 value: function _getBuffer(n) {
9044 var ret = Buffer.allocUnsafe(n);
9045 var p = this.head;
9046 var c = 1;
9047 p.data.copy(ret);
9048 n -= p.data.length;
9049
9050 while (p = p.next) {
9051 var buf = p.data;
9052 var nb = n > buf.length ? buf.length : n;
9053 buf.copy(ret, ret.length - n, 0, nb);
9054 n -= nb;
9055
9056 if (n === 0) {
9057 if (nb === buf.length) {
9058 ++c;
9059 if (p.next) this.head = p.next;else this.head = this.tail = null;
9060 } else {
9061 this.head = p;
9062 p.data = buf.slice(nb);
9063 }
9064
9065 break;
9066 }
9067
9068 ++c;
9069 }
9070
9071 this.length -= c;
9072 return ret;
9073 } // Make sure the linked list only shows the minimal necessary information.
9074
9075 }, {
9076 key: custom,
9077 value: function value(_, options) {
9078 return inspect(this, _objectSpread({}, options, {
9079 // Only inspect one level.
9080 depth: 0,
9081 // It should not recurse.
9082 customInspect: false
9083 }));
9084 }
9085 }]);
9086
9087 return BufferList;
9088}();
9089},{"11":11,"13":13}],51:[function(_dereq_,module,exports){
9090(function (process){(function (){
9091'use strict'; // undocumented cb() API, needed for core, not for public API
9092
9093function destroy(err, cb) {
9094 var _this = this;
9095
9096 var readableDestroyed = this._readableState && this._readableState.destroyed;
9097 var writableDestroyed = this._writableState && this._writableState.destroyed;
9098
9099 if (readableDestroyed || writableDestroyed) {
9100 if (cb) {
9101 cb(err);
9102 } else if (err) {
9103 if (!this._writableState) {
9104 process.nextTick(emitErrorNT, this, err);
9105 } else if (!this._writableState.errorEmitted) {
9106 this._writableState.errorEmitted = true;
9107 process.nextTick(emitErrorNT, this, err);
9108 }
9109 }
9110
9111 return this;
9112 } // we set destroyed to true before firing error callbacks in order
9113 // to make it re-entrance safe in case destroy() is called within callbacks
9114
9115
9116 if (this._readableState) {
9117 this._readableState.destroyed = true;
9118 } // if this is a duplex stream mark the writable part as destroyed as well
9119
9120
9121 if (this._writableState) {
9122 this._writableState.destroyed = true;
9123 }
9124
9125 this._destroy(err || null, function (err) {
9126 if (!cb && err) {
9127 if (!_this._writableState) {
9128 process.nextTick(emitErrorAndCloseNT, _this, err);
9129 } else if (!_this._writableState.errorEmitted) {
9130 _this._writableState.errorEmitted = true;
9131 process.nextTick(emitErrorAndCloseNT, _this, err);
9132 } else {
9133 process.nextTick(emitCloseNT, _this);
9134 }
9135 } else if (cb) {
9136 process.nextTick(emitCloseNT, _this);
9137 cb(err);
9138 } else {
9139 process.nextTick(emitCloseNT, _this);
9140 }
9141 });
9142
9143 return this;
9144}
9145
9146function emitErrorAndCloseNT(self, err) {
9147 emitErrorNT(self, err);
9148 emitCloseNT(self);
9149}
9150
9151function emitCloseNT(self) {
9152 if (self._writableState && !self._writableState.emitClose) return;
9153 if (self._readableState && !self._readableState.emitClose) return;
9154 self.emit('close');
9155}
9156
9157function undestroy() {
9158 if (this._readableState) {
9159 this._readableState.destroyed = false;
9160 this._readableState.reading = false;
9161 this._readableState.ended = false;
9162 this._readableState.endEmitted = false;
9163 }
9164
9165 if (this._writableState) {
9166 this._writableState.destroyed = false;
9167 this._writableState.ended = false;
9168 this._writableState.ending = false;
9169 this._writableState.finalCalled = false;
9170 this._writableState.prefinished = false;
9171 this._writableState.finished = false;
9172 this._writableState.errorEmitted = false;
9173 }
9174}
9175
9176function emitErrorNT(self, err) {
9177 self.emit('error', err);
9178}
9179
9180function errorOrDestroy(stream, err) {
9181 // We have tests that rely on errors being emitted
9182 // in the same tick, so changing this is semver major.
9183 // For now when you opt-in to autoDestroy we allow
9184 // the error to be emitted nextTick. In a future
9185 // semver major update we should change the default to this.
9186 var rState = stream._readableState;
9187 var wState = stream._writableState;
9188 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
9189}
9190
9191module.exports = {
9192 destroy: destroy,
9193 undestroy: undestroy,
9194 errorOrDestroy: errorOrDestroy
9195};
9196}).call(this)}).call(this,_dereq_(73))
9197},{"73":73}],52:[function(_dereq_,module,exports){
9198// Ported from https://github.com/mafintosh/end-of-stream with
9199// permission from the author, Mathias Buus (@mafintosh).
9200'use strict';
9201
9202var ERR_STREAM_PREMATURE_CLOSE = _dereq_(43).codes.ERR_STREAM_PREMATURE_CLOSE;
9203
9204function once(callback) {
9205 var called = false;
9206 return function () {
9207 if (called) return;
9208 called = true;
9209
9210 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9211 args[_key] = arguments[_key];
9212 }
9213
9214 callback.apply(this, args);
9215 };
9216}
9217
9218function noop() {}
9219
9220function isRequest(stream) {
9221 return stream.setHeader && typeof stream.abort === 'function';
9222}
9223
9224function eos(stream, opts, callback) {
9225 if (typeof opts === 'function') return eos(stream, null, opts);
9226 if (!opts) opts = {};
9227 callback = once(callback || noop);
9228 var readable = opts.readable || opts.readable !== false && stream.readable;
9229 var writable = opts.writable || opts.writable !== false && stream.writable;
9230
9231 var onlegacyfinish = function onlegacyfinish() {
9232 if (!stream.writable) onfinish();
9233 };
9234
9235 var writableEnded = stream._writableState && stream._writableState.finished;
9236
9237 var onfinish = function onfinish() {
9238 writable = false;
9239 writableEnded = true;
9240 if (!readable) callback.call(stream);
9241 };
9242
9243 var readableEnded = stream._readableState && stream._readableState.endEmitted;
9244
9245 var onend = function onend() {
9246 readable = false;
9247 readableEnded = true;
9248 if (!writable) callback.call(stream);
9249 };
9250
9251 var onerror = function onerror(err) {
9252 callback.call(stream, err);
9253 };
9254
9255 var onclose = function onclose() {
9256 var err;
9257
9258 if (readable && !readableEnded) {
9259 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9260 return callback.call(stream, err);
9261 }
9262
9263 if (writable && !writableEnded) {
9264 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9265 return callback.call(stream, err);
9266 }
9267 };
9268
9269 var onrequest = function onrequest() {
9270 stream.req.on('finish', onfinish);
9271 };
9272
9273 if (isRequest(stream)) {
9274 stream.on('complete', onfinish);
9275 stream.on('abort', onclose);
9276 if (stream.req) onrequest();else stream.on('request', onrequest);
9277 } else if (writable && !stream._writableState) {
9278 // legacy streams
9279 stream.on('end', onlegacyfinish);
9280 stream.on('close', onlegacyfinish);
9281 }
9282
9283 stream.on('end', onend);
9284 stream.on('finish', onfinish);
9285 if (opts.error !== false) stream.on('error', onerror);
9286 stream.on('close', onclose);
9287 return function () {
9288 stream.removeListener('complete', onfinish);
9289 stream.removeListener('abort', onclose);
9290 stream.removeListener('request', onrequest);
9291 if (stream.req) stream.req.removeListener('finish', onfinish);
9292 stream.removeListener('end', onlegacyfinish);
9293 stream.removeListener('close', onlegacyfinish);
9294 stream.removeListener('finish', onfinish);
9295 stream.removeListener('end', onend);
9296 stream.removeListener('error', onerror);
9297 stream.removeListener('close', onclose);
9298 };
9299}
9300
9301module.exports = eos;
9302},{"43":43}],53:[function(_dereq_,module,exports){
9303module.exports = function () {
9304 throw new Error('Readable.from is not available in the browser')
9305};
9306
9307},{}],54:[function(_dereq_,module,exports){
9308// Ported from https://github.com/mafintosh/pump with
9309// permission from the author, Mathias Buus (@mafintosh).
9310'use strict';
9311
9312var eos;
9313
9314function once(callback) {
9315 var called = false;
9316 return function () {
9317 if (called) return;
9318 called = true;
9319 callback.apply(void 0, arguments);
9320 };
9321}
9322
9323var _require$codes = _dereq_(43).codes,
9324 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
9325 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
9326
9327function noop(err) {
9328 // Rethrow the error if it exists to avoid swallowing it
9329 if (err) throw err;
9330}
9331
9332function isRequest(stream) {
9333 return stream.setHeader && typeof stream.abort === 'function';
9334}
9335
9336function destroyer(stream, reading, writing, callback) {
9337 callback = once(callback);
9338 var closed = false;
9339 stream.on('close', function () {
9340 closed = true;
9341 });
9342 if (eos === undefined) eos = _dereq_(52);
9343 eos(stream, {
9344 readable: reading,
9345 writable: writing
9346 }, function (err) {
9347 if (err) return callback(err);
9348 closed = true;
9349 callback();
9350 });
9351 var destroyed = false;
9352 return function (err) {
9353 if (closed) return;
9354 if (destroyed) return;
9355 destroyed = true; // request.destroy just do .end - .abort is what we want
9356
9357 if (isRequest(stream)) return stream.abort();
9358 if (typeof stream.destroy === 'function') return stream.destroy();
9359 callback(err || new ERR_STREAM_DESTROYED('pipe'));
9360 };
9361}
9362
9363function call(fn) {
9364 fn();
9365}
9366
9367function pipe(from, to) {
9368 return from.pipe(to);
9369}
9370
9371function popCallback(streams) {
9372 if (!streams.length) return noop;
9373 if (typeof streams[streams.length - 1] !== 'function') return noop;
9374 return streams.pop();
9375}
9376
9377function pipeline() {
9378 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
9379 streams[_key] = arguments[_key];
9380 }
9381
9382 var callback = popCallback(streams);
9383 if (Array.isArray(streams[0])) streams = streams[0];
9384
9385 if (streams.length < 2) {
9386 throw new ERR_MISSING_ARGS('streams');
9387 }
9388
9389 var error;
9390 var destroys = streams.map(function (stream, i) {
9391 var reading = i < streams.length - 1;
9392 var writing = i > 0;
9393 return destroyer(stream, reading, writing, function (err) {
9394 if (!error) error = err;
9395 if (err) destroys.forEach(call);
9396 if (reading) return;
9397 destroys.forEach(call);
9398 callback(error);
9399 });
9400 });
9401 return streams.reduce(pipe);
9402}
9403
9404module.exports = pipeline;
9405},{"43":43,"52":52}],55:[function(_dereq_,module,exports){
9406'use strict';
9407
9408var ERR_INVALID_OPT_VALUE = _dereq_(43).codes.ERR_INVALID_OPT_VALUE;
9409
9410function highWaterMarkFrom(options, isDuplex, duplexKey) {
9411 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
9412}
9413
9414function getHighWaterMark(state, options, duplexKey, isDuplex) {
9415 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
9416
9417 if (hwm != null) {
9418 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
9419 var name = isDuplex ? duplexKey : 'highWaterMark';
9420 throw new ERR_INVALID_OPT_VALUE(name, hwm);
9421 }
9422
9423 return Math.floor(hwm);
9424 } // Default value
9425
9426
9427 return state.objectMode ? 16 : 16 * 1024;
9428}
9429
9430module.exports = {
9431 getHighWaterMark: getHighWaterMark
9432};
9433},{"43":43}],56:[function(_dereq_,module,exports){
9434module.exports = _dereq_(26).EventEmitter;
9435
9436},{"26":26}],57:[function(_dereq_,module,exports){
9437exports = module.exports = _dereq_(46);
9438exports.Stream = exports;
9439exports.Readable = exports;
9440exports.Writable = _dereq_(48);
9441exports.Duplex = _dereq_(44);
9442exports.Transform = _dereq_(47);
9443exports.PassThrough = _dereq_(45);
9444exports.finished = _dereq_(52);
9445exports.pipeline = _dereq_(54);
9446
9447},{"44":44,"45":45,"46":46,"47":47,"48":48,"52":52,"54":54}],58:[function(_dereq_,module,exports){
9448'use strict'
9449
9450// For (old) browser support
9451var xtend = _dereq_(141)
9452var assign = _dereq_(142)
9453
9454module.exports = function supports () {
9455 var manifest = xtend.apply(null, arguments)
9456
9457 return assign(manifest, {
9458 // Features of abstract-leveldown
9459 bufferKeys: manifest.bufferKeys || false,
9460 snapshots: manifest.snapshots || false,
9461 permanence: manifest.permanence || false,
9462 seek: manifest.seek || false,
9463 clear: manifest.clear || false,
9464
9465 // Features of abstract-leveldown that levelup doesn't have
9466 status: manifest.status || false,
9467
9468 // Features of disk-based implementations
9469 createIfMissing: manifest.createIfMissing || false,
9470 errorIfExists: manifest.errorIfExists || false,
9471
9472 // Features of level(up) that abstract-leveldown doesn't have yet
9473 deferredOpen: manifest.deferredOpen || false,
9474 openCallback: manifest.openCallback || false,
9475 promises: manifest.promises || false,
9476 streams: manifest.streams || false,
9477 encodings: manifest.encodings || false,
9478
9479 // Methods that are not part of abstract-leveldown or levelup
9480 additionalMethods: xtend(manifest.additionalMethods)
9481 })
9482}
9483
9484},{"141":141,"142":142}],59:[function(_dereq_,module,exports){
9485var WriteError = _dereq_(41).WriteError
9486var promisify = _dereq_(62)
9487var getCallback = _dereq_(60).getCallback
9488var getOptions = _dereq_(60).getOptions
9489
9490function Batch (levelup) {
9491 // TODO (next major): remove this._levelup alias
9492 this.db = this._levelup = levelup
9493 this.batch = levelup.db.batch()
9494 this.ops = []
9495 this.length = 0
9496}
9497
9498Batch.prototype.put = function (key, value) {
9499 try {
9500 this.batch.put(key, value)
9501 } catch (e) {
9502 throw new WriteError(e)
9503 }
9504
9505 this.ops.push({ type: 'put', key: key, value: value })
9506 this.length++
9507
9508 return this
9509}
9510
9511Batch.prototype.del = function (key) {
9512 try {
9513 this.batch.del(key)
9514 } catch (err) {
9515 throw new WriteError(err)
9516 }
9517
9518 this.ops.push({ type: 'del', key: key })
9519 this.length++
9520
9521 return this
9522}
9523
9524Batch.prototype.clear = function () {
9525 try {
9526 this.batch.clear()
9527 } catch (err) {
9528 throw new WriteError(err)
9529 }
9530
9531 this.ops = []
9532 this.length = 0
9533
9534 return this
9535}
9536
9537Batch.prototype.write = function (options, callback) {
9538 var levelup = this._levelup
9539 var ops = this.ops
9540 var promise
9541
9542 callback = getCallback(options, callback)
9543
9544 if (!callback) {
9545 callback = promisify()
9546 promise = callback.promise
9547 }
9548
9549 options = getOptions(options)
9550
9551 try {
9552 this.batch.write(options, function (err) {
9553 if (err) { return callback(new WriteError(err)) }
9554 levelup.emit('batch', ops)
9555 callback()
9556 })
9557 } catch (err) {
9558 throw new WriteError(err)
9559 }
9560
9561 return promise
9562}
9563
9564module.exports = Batch
9565
9566},{"41":41,"60":60,"62":62}],60:[function(_dereq_,module,exports){
9567exports.getCallback = function (options, callback) {
9568 return typeof options === 'function' ? options : callback
9569}
9570
9571exports.getOptions = function (options) {
9572 return typeof options === 'object' && options !== null ? options : {}
9573}
9574
9575},{}],61:[function(_dereq_,module,exports){
9576(function (process){(function (){
9577var EventEmitter = _dereq_(26).EventEmitter
9578var inherits = _dereq_(124).inherits
9579var extend = _dereq_(141)
9580var DeferredLevelDOWN = _dereq_(17)
9581var IteratorStream = _dereq_(42)
9582var Batch = _dereq_(59)
9583var errors = _dereq_(41)
9584var supports = _dereq_(58)
9585var assert = _dereq_(6)
9586var promisify = _dereq_(62)
9587var getCallback = _dereq_(60).getCallback
9588var getOptions = _dereq_(60).getOptions
9589
9590var WriteError = errors.WriteError
9591var ReadError = errors.ReadError
9592var NotFoundError = errors.NotFoundError
9593var OpenError = errors.OpenError
9594var InitializationError = errors.InitializationError
9595
9596// Possible AbstractLevelDOWN#status values:
9597// - 'new' - newly created, not opened or closed
9598// - 'opening' - waiting for the database to be opened, post open()
9599// - 'open' - successfully opened the database, available for use
9600// - 'closing' - waiting for the database to be closed, post close()
9601// - 'closed' - database has been successfully closed, should not be
9602// used except for another open() operation
9603
9604function LevelUP (db, options, callback) {
9605 if (!(this instanceof LevelUP)) {
9606 return new LevelUP(db, options, callback)
9607 }
9608
9609 var error
9610 var self = this
9611
9612 EventEmitter.call(this)
9613 this.setMaxListeners(Infinity)
9614
9615 if (typeof options === 'function') {
9616 callback = options
9617 options = {}
9618 }
9619
9620 options = options || {}
9621
9622 if (!db || typeof db !== 'object') {
9623 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
9624 if (typeof callback === 'function') {
9625 return process.nextTick(callback, error)
9626 }
9627 throw error
9628 }
9629
9630 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
9631
9632 this.options = getOptions(options)
9633 this._db = db
9634 this.db = new DeferredLevelDOWN(db)
9635 this.open(callback || function (err) {
9636 if (err) self.emit('error', err)
9637 })
9638
9639 // Create manifest based on deferred-leveldown's
9640 this.supports = supports(this.db.supports, {
9641 status: false,
9642 deferredOpen: true,
9643 openCallback: true,
9644 promises: true,
9645 streams: true
9646 })
9647
9648 // Experimental: enrich levelup interface
9649 Object.keys(this.supports.additionalMethods).forEach(function (method) {
9650 if (this[method] != null) return
9651
9652 // Don't do this.db[method].bind() because this.db is dynamic.
9653 this[method] = function () {
9654 return this.db[method].apply(this.db, arguments)
9655 }
9656 }, this)
9657}
9658
9659LevelUP.prototype.emit = EventEmitter.prototype.emit
9660LevelUP.prototype.once = EventEmitter.prototype.once
9661inherits(LevelUP, EventEmitter)
9662
9663LevelUP.prototype.open = function (opts, callback) {
9664 var self = this
9665 var promise
9666
9667 if (typeof opts === 'function') {
9668 callback = opts
9669 opts = null
9670 }
9671
9672 if (!callback) {
9673 callback = promisify()
9674 promise = callback.promise
9675 }
9676
9677 if (!opts) {
9678 opts = this.options
9679 }
9680
9681 if (this.isOpen()) {
9682 process.nextTick(callback, null, self)
9683 return promise
9684 }
9685
9686 if (this._isOpening()) {
9687 this.once('open', function () { callback(null, self) })
9688 return promise
9689 }
9690
9691 this.emit('opening')
9692
9693 this.db.open(opts, function (err) {
9694 if (err) {
9695 return callback(new OpenError(err))
9696 }
9697 self.db = self._db
9698 callback(null, self)
9699 self.emit('open')
9700 self.emit('ready')
9701 })
9702
9703 return promise
9704}
9705
9706LevelUP.prototype.close = function (callback) {
9707 var self = this
9708 var promise
9709
9710 if (!callback) {
9711 callback = promisify()
9712 promise = callback.promise
9713 }
9714
9715 if (this.isOpen()) {
9716 this.db.close(function () {
9717 self.emit('closed')
9718 callback.apply(null, arguments)
9719 })
9720 this.emit('closing')
9721 this.db = new DeferredLevelDOWN(this._db)
9722 } else if (this.isClosed()) {
9723 process.nextTick(callback)
9724 } else if (this.db.status === 'closing') {
9725 this.once('closed', callback)
9726 } else if (this._isOpening()) {
9727 this.once('open', function () {
9728 self.close(callback)
9729 })
9730 }
9731
9732 return promise
9733}
9734
9735LevelUP.prototype.isOpen = function () {
9736 return this.db.status === 'open'
9737}
9738
9739LevelUP.prototype._isOpening = function () {
9740 return this.db.status === 'opening'
9741}
9742
9743LevelUP.prototype.isClosed = function () {
9744 return (/^clos|new/).test(this.db.status)
9745}
9746
9747LevelUP.prototype.get = function (key, options, callback) {
9748 var promise
9749
9750 callback = getCallback(options, callback)
9751
9752 if (!callback) {
9753 callback = promisify()
9754 promise = callback.promise
9755 }
9756
9757 if (maybeError(this, callback)) { return promise }
9758
9759 options = getOptions(options)
9760
9761 this.db.get(key, options, function (err, value) {
9762 if (err) {
9763 if ((/notfound/i).test(err) || err.notFound) {
9764 err = new NotFoundError('Key not found in database [' + key + ']', err)
9765 } else {
9766 err = new ReadError(err)
9767 }
9768 return callback(err)
9769 }
9770 callback(null, value)
9771 })
9772
9773 return promise
9774}
9775
9776LevelUP.prototype.put = function (key, value, options, callback) {
9777 var self = this
9778 var promise
9779
9780 callback = getCallback(options, callback)
9781
9782 if (!callback) {
9783 callback = promisify()
9784 promise = callback.promise
9785 }
9786
9787 if (maybeError(this, callback)) { return promise }
9788
9789 options = getOptions(options)
9790
9791 this.db.put(key, value, options, function (err) {
9792 if (err) {
9793 return callback(new WriteError(err))
9794 }
9795 self.emit('put', key, value)
9796 callback()
9797 })
9798
9799 return promise
9800}
9801
9802LevelUP.prototype.del = function (key, options, callback) {
9803 var self = this
9804 var promise
9805
9806 callback = getCallback(options, callback)
9807
9808 if (!callback) {
9809 callback = promisify()
9810 promise = callback.promise
9811 }
9812
9813 if (maybeError(this, callback)) { return promise }
9814
9815 options = getOptions(options)
9816
9817 this.db.del(key, options, function (err) {
9818 if (err) {
9819 return callback(new WriteError(err))
9820 }
9821 self.emit('del', key)
9822 callback()
9823 })
9824
9825 return promise
9826}
9827
9828LevelUP.prototype.batch = function (arr, options, callback) {
9829 if (!arguments.length) {
9830 return new Batch(this)
9831 }
9832
9833 var self = this
9834 var promise
9835
9836 if (typeof arr === 'function') callback = arr
9837 else callback = getCallback(options, callback)
9838
9839 if (!callback) {
9840 callback = promisify()
9841 promise = callback.promise
9842 }
9843
9844 if (maybeError(this, callback)) { return promise }
9845
9846 options = getOptions(options)
9847
9848 this.db.batch(arr, options, function (err) {
9849 if (err) {
9850 return callback(new WriteError(err))
9851 }
9852 self.emit('batch', arr)
9853 callback()
9854 })
9855
9856 return promise
9857}
9858
9859LevelUP.prototype.iterator = function (options) {
9860 return this.db.iterator(options)
9861}
9862
9863LevelUP.prototype.clear = function (options, callback) {
9864 var self = this
9865 var promise
9866
9867 callback = getCallback(options, callback)
9868 options = getOptions(options)
9869
9870 if (!callback) {
9871 callback = promisify()
9872 promise = callback.promise
9873 }
9874
9875 if (maybeError(this, callback)) {
9876 return promise
9877 }
9878
9879 this.db.clear(options, function (err) {
9880 if (err) {
9881 return callback(new WriteError(err))
9882 }
9883 self.emit('clear', options)
9884 callback()
9885 })
9886
9887 return promise
9888}
9889
9890LevelUP.prototype.readStream =
9891LevelUP.prototype.createReadStream = function (options) {
9892 options = extend({ keys: true, values: true }, options)
9893 if (typeof options.limit !== 'number') { options.limit = -1 }
9894 return new IteratorStream(this.db.iterator(options), options)
9895}
9896
9897LevelUP.prototype.keyStream =
9898LevelUP.prototype.createKeyStream = function (options) {
9899 return this.createReadStream(extend(options, { keys: true, values: false }))
9900}
9901
9902LevelUP.prototype.valueStream =
9903LevelUP.prototype.createValueStream = function (options) {
9904 return this.createReadStream(extend(options, { keys: false, values: true }))
9905}
9906
9907LevelUP.prototype.toString = function () {
9908 return 'LevelUP'
9909}
9910
9911LevelUP.prototype.type = 'levelup'
9912
9913function maybeError (db, callback) {
9914 if (!db._isOpening() && !db.isOpen()) {
9915 process.nextTick(callback, new ReadError('Database is not open'))
9916 return true
9917 }
9918}
9919
9920LevelUP.errors = errors
9921module.exports = LevelUP.default = LevelUP
9922
9923}).call(this)}).call(this,_dereq_(73))
9924},{"124":124,"141":141,"17":17,"26":26,"41":41,"42":42,"58":58,"59":59,"6":6,"60":60,"62":62,"73":73}],62:[function(_dereq_,module,exports){
9925function promisify () {
9926 var callback
9927 var promise = new Promise(function (resolve, reject) {
9928 callback = function callback (err, value) {
9929 if (err) reject(err)
9930 else resolve(value)
9931 }
9932 })
9933 callback.promise = promise
9934 return callback
9935}
9936
9937module.exports = promisify
9938
9939},{}],63:[function(_dereq_,module,exports){
9940(function (Buffer,process,global){(function (){
9941'use strict';
9942
9943var inherits = _dereq_(37);
9944var bufferFrom = _dereq_(68);
9945var AbstractLevelDOWN = _dereq_(3).AbstractLevelDOWN;
9946var AbstractIterator = _dereq_(3).AbstractIterator;
9947
9948var LocalStorage = _dereq_(65).LocalStorage;
9949var LocalStorageCore = _dereq_(64);
9950var utils = _dereq_(67);
9951
9952// see http://stackoverflow.com/a/15349865/680742
9953var nextTick = global.setImmediate || process.nextTick;
9954
9955function LDIterator(db, options) {
9956
9957 AbstractIterator.call(this, db);
9958
9959 this._reverse = !!options.reverse;
9960 this._endkey = options.end;
9961 this._startkey = options.start;
9962 this._gt = options.gt;
9963 this._gte = options.gte;
9964 this._lt = options.lt;
9965 this._lte = options.lte;
9966 this._exclusiveStart = options.exclusiveStart;
9967 this._keysOnly = options.values === false;
9968 this._limit = options.limit;
9969 this._count = 0;
9970
9971 this.onInitCompleteListeners = [];
9972}
9973
9974inherits(LDIterator, AbstractIterator);
9975
9976LDIterator.prototype._init = function (callback) {
9977 nextTick(function () {
9978 callback();
9979 });
9980};
9981
9982LDIterator.prototype._next = function (callback) {
9983 var self = this;
9984
9985 function onInitComplete() {
9986 if (self._pos === self._keys.length || self._pos < 0) { // done reading
9987 return callback();
9988 }
9989
9990 var key = self._keys[self._pos];
9991
9992 if (!!self._endkey && (self._reverse ? key < self._endkey : key > self._endkey)) {
9993 return callback();
9994 }
9995
9996 if (!!self._limit && self._limit > 0 && self._count++ >= self._limit) {
9997 return callback();
9998 }
9999
10000 if ((self._lt && key >= self._lt) ||
10001 (self._lte && key > self._lte) ||
10002 (self._gt && key <= self._gt) ||
10003 (self._gte && key < self._gte)) {
10004 return callback();
10005 }
10006
10007 self._pos += self._reverse ? -1 : 1;
10008 if (self._keysOnly) {
10009 return callback(null, key);
10010 }
10011
10012 self.db.container.getItem(key, function (err, value) {
10013 if (err) {
10014 if (err.message === 'NotFound') {
10015 return nextTick(function () {
10016 self._next(callback);
10017 });
10018 }
10019 return callback(err);
10020 }
10021 callback(null, key, value);
10022 });
10023 }
10024 if (!self.initStarted) {
10025 process.nextTick(function () {
10026 self.initStarted = true;
10027 self._init(function (err) {
10028 if (err) {
10029 return callback(err);
10030 }
10031 self.db.container.keys(function (err, keys) {
10032 if (err) {
10033 return callback(err);
10034 }
10035 self._keys = keys;
10036 if (self._startkey) {
10037 var index = utils.sortedIndexOf(self._keys, self._startkey);
10038 var startkey = (index >= self._keys.length || index < 0) ?
10039 undefined : self._keys[index];
10040 self._pos = index;
10041 if (self._reverse) {
10042 if (self._exclusiveStart || startkey !== self._startkey) {
10043 self._pos--;
10044 }
10045 } else if (self._exclusiveStart && startkey === self._startkey) {
10046 self._pos++;
10047 }
10048 } else {
10049 self._pos = self._reverse ? self._keys.length - 1 : 0;
10050 }
10051 onInitComplete();
10052
10053 self.initCompleted = true;
10054 var i = -1;
10055 while (++i < self.onInitCompleteListeners.length) {
10056 nextTick(self.onInitCompleteListeners[i]);
10057 }
10058 });
10059 });
10060 });
10061 } else if (!self.initCompleted) {
10062 self.onInitCompleteListeners.push(onInitComplete);
10063 } else {
10064 process.nextTick(onInitComplete);
10065 }
10066};
10067
10068function LD(location) {
10069 if (!(this instanceof LD)) {
10070 return new LD(location);
10071 }
10072 AbstractLevelDOWN.call(this, location);
10073 this.container = new LocalStorage(location);
10074}
10075
10076inherits(LD, AbstractLevelDOWN);
10077
10078LD.prototype._open = function (options, callback) {
10079 this.container.init(callback);
10080};
10081
10082LD.prototype._put = function (key, value, options, callback) {
10083
10084 var err = checkKeyValue(key, 'key');
10085
10086 if (err) {
10087 return nextTick(function () {
10088 callback(err);
10089 });
10090 }
10091
10092 err = checkKeyValue(value, 'value');
10093
10094 if (err) {
10095 return nextTick(function () {
10096 callback(err);
10097 });
10098 }
10099
10100 if (typeof value === 'object' && !Buffer.isBuffer(value) && value.buffer === undefined) {
10101 var obj = {};
10102 obj.storetype = "json";
10103 obj.data = value;
10104 value = JSON.stringify(obj);
10105 }
10106
10107 this.container.setItem(key, value, callback);
10108};
10109
10110LD.prototype._get = function (key, options, callback) {
10111
10112 var err = checkKeyValue(key, 'key');
10113
10114 if (err) {
10115 return nextTick(function () {
10116 callback(err);
10117 });
10118 }
10119
10120 if (!Buffer.isBuffer(key)) {
10121 key = String(key);
10122 }
10123 this.container.getItem(key, function (err, value) {
10124
10125 if (err) {
10126 return callback(err);
10127 }
10128
10129 if (options.asBuffer !== false && !Buffer.isBuffer(value)) {
10130 value = bufferFrom(value);
10131 }
10132
10133
10134 if (options.asBuffer === false) {
10135 if (value.indexOf("{\"storetype\":\"json\",\"data\"") > -1) {
10136 var res = JSON.parse(value);
10137 value = res.data;
10138 }
10139 }
10140 callback(null, value);
10141 });
10142};
10143
10144LD.prototype._del = function (key, options, callback) {
10145
10146 var err = checkKeyValue(key, 'key');
10147
10148 if (err) {
10149 return nextTick(function () {
10150 callback(err);
10151 });
10152 }
10153 if (!Buffer.isBuffer(key)) {
10154 key = String(key);
10155 }
10156
10157 this.container.removeItem(key, callback);
10158};
10159
10160LD.prototype._batch = function (array, options, callback) {
10161 var self = this;
10162 nextTick(function () {
10163 var err;
10164 var key;
10165 var value;
10166
10167 var numDone = 0;
10168 var overallErr;
10169 function checkDone() {
10170 if (++numDone === array.length) {
10171 callback(overallErr);
10172 }
10173 }
10174
10175 if (Array.isArray(array) && array.length) {
10176 for (var i = 0; i < array.length; i++) {
10177 var task = array[i];
10178 if (task) {
10179 key = Buffer.isBuffer(task.key) ? task.key : String(task.key);
10180 err = checkKeyValue(key, 'key');
10181 if (err) {
10182 overallErr = err;
10183 checkDone();
10184 } else if (task.type === 'del') {
10185 self._del(task.key, options, checkDone);
10186 } else if (task.type === 'put') {
10187 value = Buffer.isBuffer(task.value) ? task.value : String(task.value);
10188 err = checkKeyValue(value, 'value');
10189 if (err) {
10190 overallErr = err;
10191 checkDone();
10192 } else {
10193 self._put(key, value, options, checkDone);
10194 }
10195 }
10196 } else {
10197 checkDone();
10198 }
10199 }
10200 } else {
10201 callback();
10202 }
10203 });
10204};
10205
10206LD.prototype._iterator = function (options) {
10207 return new LDIterator(this, options);
10208};
10209
10210LD.destroy = function (name, callback) {
10211 LocalStorageCore.destroy(name, callback);
10212};
10213
10214function checkKeyValue(obj, type) {
10215 if (obj === null || obj === undefined) {
10216 return new Error(type + ' cannot be `null` or `undefined`');
10217 }
10218 if (obj === null || obj === undefined) {
10219 return new Error(type + ' cannot be `null` or `undefined`');
10220 }
10221
10222 if (type === 'key') {
10223
10224 if (obj instanceof Boolean) {
10225 return new Error(type + ' cannot be `null` or `undefined`');
10226 }
10227 if (obj === '') {
10228 return new Error(type + ' cannot be empty');
10229 }
10230 }
10231 if (obj.toString().indexOf("[object ArrayBuffer]") === 0) {
10232 if (obj.byteLength === 0 || obj.byteLength === undefined) {
10233 return new Error(type + ' cannot be an empty Buffer');
10234 }
10235 }
10236
10237 if (Buffer.isBuffer(obj)) {
10238 if (obj.length === 0) {
10239 return new Error(type + ' cannot be an empty Buffer');
10240 }
10241 } else if (String(obj) === '') {
10242 return new Error(type + ' cannot be an empty String');
10243 }
10244}
10245
10246module.exports = LD;
10247
10248}).call(this)}).call(this,{"isBuffer":_dereq_(38)},_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10249},{"3":3,"37":37,"38":38,"64":64,"65":65,"67":67,"68":68,"73":73}],64:[function(_dereq_,module,exports){
10250(function (process,global){(function (){
10251'use strict';
10252
10253//
10254// Class that should contain everything necessary to interact
10255// with localStorage as a generic key-value store.
10256// The idea is that authors who want to create an AbstractKeyValueDOWN
10257// module (e.g. on lawnchair, S3, whatever) will only have to
10258// reimplement this file.
10259//
10260
10261// see http://stackoverflow.com/a/15349865/680742
10262var nextTick = global.setImmediate || process.nextTick;
10263
10264// We use humble-localstorage as a wrapper for localStorage because
10265// it falls back to an in-memory implementation in environments without
10266// localStorage, like Node or Safari private browsing.
10267var storage = _dereq_(29);
10268
10269function callbackify(callback, fun) {
10270 var val;
10271 var err;
10272 try {
10273 val = fun();
10274 } catch (e) {
10275 err = e;
10276 }
10277 nextTick(function () {
10278 callback(err, val);
10279 });
10280}
10281
10282function createPrefix(dbname) {
10283 return dbname.replace(/!/g, '!!') + '!'; // escape bangs in dbname;
10284}
10285
10286function LocalStorageCore(dbname) {
10287 this._prefix = createPrefix(dbname);
10288}
10289
10290LocalStorageCore.prototype.getKeys = function (callback) {
10291 var self = this;
10292 callbackify(callback, function () {
10293 var keys = [];
10294 var prefixLen = self._prefix.length;
10295 var i = -1;
10296 var len = storage.length;
10297 while (++i < len) {
10298 var fullKey = storage.key(i);
10299 if (fullKey.substring(0, prefixLen) === self._prefix) {
10300 keys.push(fullKey.substring(prefixLen));
10301 }
10302 }
10303 keys.sort();
10304 return keys;
10305 });
10306};
10307
10308LocalStorageCore.prototype.put = function (key, value, callback) {
10309 var self = this;
10310 callbackify(callback, function () {
10311 storage.setItem(self._prefix + key, value);
10312 });
10313};
10314
10315LocalStorageCore.prototype.get = function (key, callback) {
10316 var self = this;
10317 callbackify(callback, function () {
10318 return storage.getItem(self._prefix + key);
10319 });
10320};
10321
10322LocalStorageCore.prototype.remove = function (key, callback) {
10323 var self = this;
10324 callbackify(callback, function () {
10325 storage.removeItem(self._prefix + key);
10326 });
10327};
10328
10329LocalStorageCore.destroy = function (dbname, callback) {
10330 var prefix = createPrefix(dbname);
10331 callbackify(callback, function () {
10332 var keysToDelete = [];
10333 var i = -1;
10334 var len = storage.length;
10335 while (++i < len) {
10336 var key = storage.key(i);
10337 if (key.substring(0, prefix.length) === prefix) {
10338 keysToDelete.push(key);
10339 }
10340 }
10341 keysToDelete.forEach(function (key) {
10342 storage.removeItem(key);
10343 });
10344 });
10345};
10346
10347module.exports = LocalStorageCore;
10348}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10349},{"29":29,"73":73}],65:[function(_dereq_,module,exports){
10350(function (Buffer){(function (){
10351'use strict';
10352
10353// ArrayBuffer/Uint8Array are old formats that date back to before we
10354// had a proper browserified buffer type. they may be removed later
10355var arrayBuffPrefix = 'ArrayBuffer:';
10356var arrayBuffRegex = new RegExp('^' + arrayBuffPrefix);
10357var uintPrefix = 'Uint8Array:';
10358var uintRegex = new RegExp('^' + uintPrefix);
10359
10360// this is the new encoding format used going forward
10361var bufferPrefix = 'Buff:';
10362var bufferRegex = new RegExp('^' + bufferPrefix);
10363
10364var utils = _dereq_(67);
10365var LocalStorageCore = _dereq_(64);
10366var TaskQueue = _dereq_(66);
10367var d64 = _dereq_(15);
10368
10369function LocalStorage(dbname) {
10370 this._store = new LocalStorageCore(dbname);
10371 this._queue = new TaskQueue();
10372}
10373
10374LocalStorage.prototype.sequentialize = function (callback, fun) {
10375 this._queue.add(fun, callback);
10376};
10377
10378LocalStorage.prototype.init = function (callback) {
10379 var self = this;
10380 self.sequentialize(callback, function (callback) {
10381 self._store.getKeys(function (err, keys) {
10382 if (err) {
10383 return callback(err);
10384 }
10385 self._keys = keys;
10386 return callback();
10387 });
10388 });
10389};
10390
10391LocalStorage.prototype.keys = function (callback) {
10392 var self = this;
10393 self.sequentialize(callback, function (callback) {
10394 self._store.getKeys(function (err, keys) {
10395 callback(null, keys.slice());
10396 });
10397 });
10398};
10399
10400//setItem: Saves and item at the key provided.
10401LocalStorage.prototype.setItem = function (key, value, callback) {
10402 var self = this;
10403 self.sequentialize(callback, function (callback) {
10404 if (Buffer.isBuffer(value)) {
10405 value = bufferPrefix + d64.encode(value);
10406 }
10407
10408 var idx = utils.sortedIndexOf(self._keys, key);
10409 if (self._keys[idx] !== key) {
10410 self._keys.splice(idx, 0, key);
10411 }
10412 self._store.put(key, value, callback);
10413 });
10414};
10415
10416//getItem: Returns the item identified by it's key.
10417LocalStorage.prototype.getItem = function (key, callback) {
10418 var self = this;
10419 self.sequentialize(callback, function (callback) {
10420 self._store.get(key, function (err, retval) {
10421 if (err) {
10422 return callback(err);
10423 }
10424 if (typeof retval === 'undefined' || retval === null) {
10425 // 'NotFound' error, consistent with LevelDOWN API
10426 return callback(new Error('NotFound'));
10427 }
10428 if (typeof retval !== 'undefined') {
10429 if (bufferRegex.test(retval)) {
10430 retval = d64.decode(retval.substring(bufferPrefix.length));
10431 } else if (arrayBuffRegex.test(retval)) {
10432 // this type is kept for backwards
10433 // compatibility with older databases, but may be removed
10434 // after a major version bump
10435 retval = retval.substring(arrayBuffPrefix.length);
10436 retval = new ArrayBuffer(atob(retval).split('').map(function (c) {
10437 return c.charCodeAt(0);
10438 }));
10439 } else if (uintRegex.test(retval)) {
10440 // ditto
10441 retval = retval.substring(uintPrefix.length);
10442 retval = new Uint8Array(atob(retval).split('').map(function (c) {
10443 return c.charCodeAt(0);
10444 }));
10445 }
10446 }
10447 callback(null, retval);
10448 });
10449 });
10450};
10451
10452//removeItem: Removes the item identified by it's key.
10453LocalStorage.prototype.removeItem = function (key, callback) {
10454 var self = this;
10455 self.sequentialize(callback, function (callback) {
10456 var idx = utils.sortedIndexOf(self._keys, key);
10457 if (self._keys[idx] === key) {
10458 self._keys.splice(idx, 1);
10459 self._store.remove(key, function (err) {
10460 if (err) {
10461 return callback(err);
10462 }
10463 callback();
10464 });
10465 } else {
10466 callback();
10467 }
10468 });
10469};
10470
10471LocalStorage.prototype.length = function (callback) {
10472 var self = this;
10473 self.sequentialize(callback, function (callback) {
10474 callback(null, self._keys.length);
10475 });
10476};
10477
10478exports.LocalStorage = LocalStorage;
10479
10480}).call(this)}).call(this,{"isBuffer":_dereq_(38)})
10481},{"15":15,"38":38,"64":64,"66":66,"67":67}],66:[function(_dereq_,module,exports){
10482(function (process,global){(function (){
10483'use strict';
10484
10485var argsarray = _dereq_(5);
10486var Queue = _dereq_(120);
10487
10488// see http://stackoverflow.com/a/15349865/680742
10489var nextTick = global.setImmediate || process.nextTick;
10490
10491function TaskQueue() {
10492 this.queue = new Queue();
10493 this.running = false;
10494}
10495
10496TaskQueue.prototype.add = function (fun, callback) {
10497 this.queue.push({fun: fun, callback: callback});
10498 this.processNext();
10499};
10500
10501TaskQueue.prototype.processNext = function () {
10502 var self = this;
10503 if (self.running || !self.queue.length) {
10504 return;
10505 }
10506 self.running = true;
10507
10508 var task = self.queue.shift();
10509 nextTick(function () {
10510 task.fun(argsarray(function (args) {
10511 task.callback.apply(null, args);
10512 self.running = false;
10513 self.processNext();
10514 }));
10515 });
10516};
10517
10518module.exports = TaskQueue;
10519
10520}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10521},{"120":120,"5":5,"73":73}],67:[function(_dereq_,module,exports){
10522'use strict';
10523// taken from rvagg/memdown commit 2078b40
10524exports.sortedIndexOf = function(arr, item) {
10525 var low = 0;
10526 var high = arr.length;
10527 var mid;
10528 while (low < high) {
10529 mid = (low + high) >>> 1;
10530 if (arr[mid] < item) {
10531 low = mid + 1;
10532 } else {
10533 high = mid;
10534 }
10535 }
10536 return low;
10537};
10538
10539},{}],68:[function(_dereq_,module,exports){
10540(function (Buffer){(function (){
10541var toString = Object.prototype.toString
10542
10543var isModern = (
10544 typeof Buffer.alloc === 'function' &&
10545 typeof Buffer.allocUnsafe === 'function' &&
10546 typeof Buffer.from === 'function'
10547)
10548
10549function isArrayBuffer (input) {
10550 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
10551}
10552
10553function fromArrayBuffer (obj, byteOffset, length) {
10554 byteOffset >>>= 0
10555
10556 var maxLength = obj.byteLength - byteOffset
10557
10558 if (maxLength < 0) {
10559 throw new RangeError("'offset' is out of bounds")
10560 }
10561
10562 if (length === undefined) {
10563 length = maxLength
10564 } else {
10565 length >>>= 0
10566
10567 if (length > maxLength) {
10568 throw new RangeError("'length' is out of bounds")
10569 }
10570 }
10571
10572 return isModern
10573 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
10574 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
10575}
10576
10577function fromString (string, encoding) {
10578 if (typeof encoding !== 'string' || encoding === '') {
10579 encoding = 'utf8'
10580 }
10581
10582 if (!Buffer.isEncoding(encoding)) {
10583 throw new TypeError('"encoding" must be a valid string encoding')
10584 }
10585
10586 return isModern
10587 ? Buffer.from(string, encoding)
10588 : new Buffer(string, encoding)
10589}
10590
10591function bufferFrom (value, encodingOrOffset, length) {
10592 if (typeof value === 'number') {
10593 throw new TypeError('"value" argument must not be a number')
10594 }
10595
10596 if (isArrayBuffer(value)) {
10597 return fromArrayBuffer(value, encodingOrOffset, length)
10598 }
10599
10600 if (typeof value === 'string') {
10601 return fromString(value, encodingOrOffset)
10602 }
10603
10604 return isModern
10605 ? Buffer.from(value)
10606 : new Buffer(value)
10607}
10608
10609module.exports = bufferFrom
10610
10611}).call(this)}).call(this,_dereq_(13).Buffer)
10612},{"13":13}],69:[function(_dereq_,module,exports){
10613(function (root) {
10614 var localStorageMemory = {}
10615 var cache = {}
10616
10617 /**
10618 * number of stored items.
10619 */
10620 localStorageMemory.length = 0
10621
10622 /**
10623 * returns item for passed key, or null
10624 *
10625 * @para {String} key
10626 * name of item to be returned
10627 * @returns {String|null}
10628 */
10629 localStorageMemory.getItem = function (key) {
10630 if (key in cache) {
10631 return cache[key]
10632 }
10633
10634 return null
10635 }
10636
10637 /**
10638 * sets item for key to passed value, as String
10639 *
10640 * @para {String} key
10641 * name of item to be set
10642 * @para {String} value
10643 * value, will always be turned into a String
10644 * @returns {undefined}
10645 */
10646 localStorageMemory.setItem = function (key, value) {
10647 if (typeof value === 'undefined') {
10648 localStorageMemory.removeItem(key)
10649 } else {
10650 if (!(cache.hasOwnProperty(key))) {
10651 localStorageMemory.length++
10652 }
10653
10654 cache[key] = '' + value
10655 }
10656 }
10657
10658 /**
10659 * removes item for passed key
10660 *
10661 * @para {String} key
10662 * name of item to be removed
10663 * @returns {undefined}
10664 */
10665 localStorageMemory.removeItem = function (key) {
10666 if (cache.hasOwnProperty(key)) {
10667 delete cache[key]
10668 localStorageMemory.length--
10669 }
10670 }
10671
10672 /**
10673 * returns name of key at passed index
10674 *
10675 * @para {Number} index
10676 * Position for key to be returned (starts at 0)
10677 * @returns {String|null}
10678 */
10679 localStorageMemory.key = function (index) {
10680 return Object.keys(cache)[index] || null
10681 }
10682
10683 /**
10684 * removes all stored items and sets length to 0
10685 *
10686 * @returns {undefined}
10687 */
10688 localStorageMemory.clear = function () {
10689 cache = {}
10690 localStorageMemory.length = 0
10691 }
10692
10693 if (typeof exports === 'object') {
10694 module.exports = localStorageMemory
10695 } else {
10696 root.localStorageMemory = localStorageMemory
10697 }
10698})(this)
10699
10700},{}],70:[function(_dereq_,module,exports){
10701(function (Buffer){(function (){
10702
10703exports.compare = function (a, b) {
10704
10705 if(Buffer.isBuffer(a)) {
10706 var l = Math.min(a.length, b.length)
10707 for(var i = 0; i < l; i++) {
10708 var cmp = a[i] - b[i]
10709 if(cmp) return cmp
10710 }
10711 return a.length - b.length
10712 }
10713
10714 return a < b ? -1 : a > b ? 1 : 0
10715}
10716
10717// to be compatible with the current abstract-leveldown tests
10718// nullish or empty strings.
10719// I could use !!val but I want to permit numbers and booleans,
10720// if possible.
10721
10722function isDef (val) {
10723 return val !== undefined && val !== ''
10724}
10725
10726function has (range, name) {
10727 return Object.hasOwnProperty.call(range, name)
10728}
10729
10730function hasKey(range, name) {
10731 return Object.hasOwnProperty.call(range, name) && name
10732}
10733
10734var lowerBoundKey = exports.lowerBoundKey = function (range) {
10735 return (
10736 hasKey(range, 'gt')
10737 || hasKey(range, 'gte')
10738 || hasKey(range, 'min')
10739 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10740 || undefined
10741 )
10742}
10743
10744var lowerBound = exports.lowerBound = function (range, def) {
10745 var k = lowerBoundKey(range)
10746 return k ? range[k] : def
10747}
10748
10749var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10750 return has(range, 'gt') ? false : true
10751}
10752
10753var upperBoundInclusive = exports.upperBoundInclusive =
10754 function (range) {
10755 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10756 }
10757
10758var lowerBoundExclusive = exports.lowerBoundExclusive =
10759 function (range) {
10760 return !lowerBoundInclusive(range)
10761 }
10762
10763var upperBoundExclusive = exports.upperBoundExclusive =
10764 function (range) {
10765 return !upperBoundInclusive(range)
10766 }
10767
10768var upperBoundKey = exports.upperBoundKey = function (range) {
10769 return (
10770 hasKey(range, 'lt')
10771 || hasKey(range, 'lte')
10772 || hasKey(range, 'max')
10773 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10774 || undefined
10775 )
10776}
10777
10778var upperBound = exports.upperBound = function (range, def) {
10779 var k = upperBoundKey(range)
10780 return k ? range[k] : def
10781}
10782
10783exports.start = function (range, def) {
10784 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
10785}
10786exports.end = function (range, def) {
10787 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10788}
10789exports.startInclusive = function (range) {
10790 return (
10791 range.reverse
10792 ? upperBoundInclusive(range)
10793 : lowerBoundInclusive(range)
10794 )
10795}
10796exports.endInclusive = function (range) {
10797 return (
10798 range.reverse
10799 ? lowerBoundInclusive(range)
10800 : upperBoundInclusive(range)
10801 )
10802}
10803
10804function id (e) { return e }
10805
10806exports.toLtgt = function (range, _range, map, lower, upper) {
10807 _range = _range || {}
10808 map = map || id
10809 var defaults = arguments.length > 3
10810 var lb = exports.lowerBoundKey(range)
10811 var ub = exports.upperBoundKey(range)
10812 if(lb) {
10813 if(lb === 'gt') _range.gt = map(range.gt, false)
10814 else _range.gte = map(range[lb], false)
10815 }
10816 else if(defaults)
10817 _range.gte = map(lower, false)
10818
10819 if(ub) {
10820 if(ub === 'lt') _range.lt = map(range.lt, true)
10821 else _range.lte = map(range[ub], true)
10822 }
10823 else if(defaults)
10824 _range.lte = map(upper, true)
10825
10826 if(range.reverse != null)
10827 _range.reverse = !!range.reverse
10828
10829 //if range was used mutably
10830 //(in level-sublevel it's part of an options object
10831 //that has more properties on it.)
10832 if(has(_range, 'max')) delete _range.max
10833 if(has(_range, 'min')) delete _range.min
10834 if(has(_range, 'start')) delete _range.start
10835 if(has(_range, 'end')) delete _range.end
10836
10837 return _range
10838}
10839
10840exports.contains = function (range, key, compare) {
10841 compare = compare || exports.compare
10842
10843 var lb = lowerBound(range)
10844 if(isDef(lb)) {
10845 var cmp = compare(key, lb)
10846 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10847 return false
10848 }
10849
10850 var ub = upperBound(range)
10851 if(isDef(ub)) {
10852 var cmp = compare(key, ub)
10853 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10854 return false
10855 }
10856
10857 return true
10858}
10859
10860exports.filter = function (range, compare) {
10861 return function (key) {
10862 return exports.contains(range, key, compare)
10863 }
10864}
10865
10866
10867
10868}).call(this)}).call(this,{"isBuffer":_dereq_(38)})
10869},{"38":38}],71:[function(_dereq_,module,exports){
10870/*
10871object-assign
10872(c) Sindre Sorhus
10873@license MIT
10874*/
10875
10876'use strict';
10877/* eslint-disable no-unused-vars */
10878var getOwnPropertySymbols = Object.getOwnPropertySymbols;
10879var hasOwnProperty = Object.prototype.hasOwnProperty;
10880var propIsEnumerable = Object.prototype.propertyIsEnumerable;
10881
10882function toObject(val) {
10883 if (val === null || val === undefined) {
10884 throw new TypeError('Object.assign cannot be called with null or undefined');
10885 }
10886
10887 return Object(val);
10888}
10889
10890function shouldUseNative() {
10891 try {
10892 if (!Object.assign) {
10893 return false;
10894 }
10895
10896 // Detect buggy property enumeration order in older V8 versions.
10897
10898 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
10899 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
10900 test1[5] = 'de';
10901 if (Object.getOwnPropertyNames(test1)[0] === '5') {
10902 return false;
10903 }
10904
10905 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
10906 var test2 = {};
10907 for (var i = 0; i < 10; i++) {
10908 test2['_' + String.fromCharCode(i)] = i;
10909 }
10910 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
10911 return test2[n];
10912 });
10913 if (order2.join('') !== '0123456789') {
10914 return false;
10915 }
10916
10917 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
10918 var test3 = {};
10919 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
10920 test3[letter] = letter;
10921 });
10922 if (Object.keys(Object.assign({}, test3)).join('') !==
10923 'abcdefghijklmnopqrst') {
10924 return false;
10925 }
10926
10927 return true;
10928 } catch (err) {
10929 // We don't expect any of the above to throw, but better to be safe.
10930 return false;
10931 }
10932}
10933
10934module.exports = shouldUseNative() ? Object.assign : function (target, source) {
10935 var from;
10936 var to = toObject(target);
10937 var symbols;
10938
10939 for (var s = 1; s < arguments.length; s++) {
10940 from = Object(arguments[s]);
10941
10942 for (var key in from) {
10943 if (hasOwnProperty.call(from, key)) {
10944 to[key] = from[key];
10945 }
10946 }
10947
10948 if (getOwnPropertySymbols) {
10949 symbols = getOwnPropertySymbols(from);
10950 for (var i = 0; i < symbols.length; i++) {
10951 if (propIsEnumerable.call(from, symbols[i])) {
10952 to[symbols[i]] = from[symbols[i]];
10953 }
10954 }
10955 }
10956 }
10957
10958 return to;
10959};
10960
10961},{}],72:[function(_dereq_,module,exports){
10962(function (process){(function (){
10963'use strict';
10964
10965if (typeof process === 'undefined' ||
10966 !process.version ||
10967 process.version.indexOf('v0.') === 0 ||
10968 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
10969 module.exports = { nextTick: nextTick };
10970} else {
10971 module.exports = process
10972}
10973
10974function nextTick(fn, arg1, arg2, arg3) {
10975 if (typeof fn !== 'function') {
10976 throw new TypeError('"callback" argument must be a function');
10977 }
10978 var len = arguments.length;
10979 var args, i;
10980 switch (len) {
10981 case 0:
10982 case 1:
10983 return process.nextTick(fn);
10984 case 2:
10985 return process.nextTick(function afterTickOne() {
10986 fn.call(null, arg1);
10987 });
10988 case 3:
10989 return process.nextTick(function afterTickTwo() {
10990 fn.call(null, arg1, arg2);
10991 });
10992 case 4:
10993 return process.nextTick(function afterTickThree() {
10994 fn.call(null, arg1, arg2, arg3);
10995 });
10996 default:
10997 args = new Array(len - 1);
10998 i = 0;
10999 while (i < args.length) {
11000 args[i++] = arguments[i];
11001 }
11002 return process.nextTick(function afterTick() {
11003 fn.apply(null, args);
11004 });
11005 }
11006}
11007
11008
11009}).call(this)}).call(this,_dereq_(73))
11010},{"73":73}],73:[function(_dereq_,module,exports){
11011// shim for using process in browser
11012var process = module.exports = {};
11013
11014// cached from whatever global is present so that test runners that stub it
11015// don't break things. But we need to wrap it in a try catch in case it is
11016// wrapped in strict mode code which doesn't define any globals. It's inside a
11017// function because try/catches deoptimize in certain engines.
11018
11019var cachedSetTimeout;
11020var cachedClearTimeout;
11021
11022function defaultSetTimout() {
11023 throw new Error('setTimeout has not been defined');
11024}
11025function defaultClearTimeout () {
11026 throw new Error('clearTimeout has not been defined');
11027}
11028(function () {
11029 try {
11030 if (typeof setTimeout === 'function') {
11031 cachedSetTimeout = setTimeout;
11032 } else {
11033 cachedSetTimeout = defaultSetTimout;
11034 }
11035 } catch (e) {
11036 cachedSetTimeout = defaultSetTimout;
11037 }
11038 try {
11039 if (typeof clearTimeout === 'function') {
11040 cachedClearTimeout = clearTimeout;
11041 } else {
11042 cachedClearTimeout = defaultClearTimeout;
11043 }
11044 } catch (e) {
11045 cachedClearTimeout = defaultClearTimeout;
11046 }
11047} ())
11048function runTimeout(fun) {
11049 if (cachedSetTimeout === setTimeout) {
11050 //normal enviroments in sane situations
11051 return setTimeout(fun, 0);
11052 }
11053 // if setTimeout wasn't available but was latter defined
11054 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
11055 cachedSetTimeout = setTimeout;
11056 return setTimeout(fun, 0);
11057 }
11058 try {
11059 // when when somebody has screwed with setTimeout but no I.E. maddness
11060 return cachedSetTimeout(fun, 0);
11061 } catch(e){
11062 try {
11063 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11064 return cachedSetTimeout.call(null, fun, 0);
11065 } catch(e){
11066 // 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
11067 return cachedSetTimeout.call(this, fun, 0);
11068 }
11069 }
11070
11071
11072}
11073function runClearTimeout(marker) {
11074 if (cachedClearTimeout === clearTimeout) {
11075 //normal enviroments in sane situations
11076 return clearTimeout(marker);
11077 }
11078 // if clearTimeout wasn't available but was latter defined
11079 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
11080 cachedClearTimeout = clearTimeout;
11081 return clearTimeout(marker);
11082 }
11083 try {
11084 // when when somebody has screwed with setTimeout but no I.E. maddness
11085 return cachedClearTimeout(marker);
11086 } catch (e){
11087 try {
11088 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11089 return cachedClearTimeout.call(null, marker);
11090 } catch (e){
11091 // 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.
11092 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
11093 return cachedClearTimeout.call(this, marker);
11094 }
11095 }
11096
11097
11098
11099}
11100var queue = [];
11101var draining = false;
11102var currentQueue;
11103var queueIndex = -1;
11104
11105function cleanUpNextTick() {
11106 if (!draining || !currentQueue) {
11107 return;
11108 }
11109 draining = false;
11110 if (currentQueue.length) {
11111 queue = currentQueue.concat(queue);
11112 } else {
11113 queueIndex = -1;
11114 }
11115 if (queue.length) {
11116 drainQueue();
11117 }
11118}
11119
11120function drainQueue() {
11121 if (draining) {
11122 return;
11123 }
11124 var timeout = runTimeout(cleanUpNextTick);
11125 draining = true;
11126
11127 var len = queue.length;
11128 while(len) {
11129 currentQueue = queue;
11130 queue = [];
11131 while (++queueIndex < len) {
11132 if (currentQueue) {
11133 currentQueue[queueIndex].run();
11134 }
11135 }
11136 queueIndex = -1;
11137 len = queue.length;
11138 }
11139 currentQueue = null;
11140 draining = false;
11141 runClearTimeout(timeout);
11142}
11143
11144process.nextTick = function (fun) {
11145 var args = new Array(arguments.length - 1);
11146 if (arguments.length > 1) {
11147 for (var i = 1; i < arguments.length; i++) {
11148 args[i - 1] = arguments[i];
11149 }
11150 }
11151 queue.push(new Item(fun, args));
11152 if (queue.length === 1 && !draining) {
11153 runTimeout(drainQueue);
11154 }
11155};
11156
11157// v8 likes predictible objects
11158function Item(fun, array) {
11159 this.fun = fun;
11160 this.array = array;
11161}
11162Item.prototype.run = function () {
11163 this.fun.apply(null, this.array);
11164};
11165process.title = 'browser';
11166process.browser = true;
11167process.env = {};
11168process.argv = [];
11169process.version = ''; // empty string to avoid regexp issues
11170process.versions = {};
11171
11172function noop() {}
11173
11174process.on = noop;
11175process.addListener = noop;
11176process.once = noop;
11177process.off = noop;
11178process.removeListener = noop;
11179process.removeAllListeners = noop;
11180process.emit = noop;
11181process.prependListener = noop;
11182process.prependOnceListener = noop;
11183
11184process.listeners = function (name) { return [] }
11185
11186process.binding = function (name) {
11187 throw new Error('process.binding is not supported');
11188};
11189
11190process.cwd = function () { return '/' };
11191process.chdir = function (dir) {
11192 throw new Error('process.chdir is not supported');
11193};
11194process.umask = function() { return 0; };
11195
11196},{}],74:[function(_dereq_,module,exports){
11197/*!
11198 * prr
11199 * (c) 2013 Rod Vagg <rod@vagg.org>
11200 * https://github.com/rvagg/prr
11201 * License: MIT
11202 */
11203
11204(function (name, context, definition) {
11205 if (typeof module != 'undefined' && module.exports)
11206 module.exports = definition()
11207 else
11208 context[name] = definition()
11209})('prr', this, function() {
11210
11211 var setProperty = typeof Object.defineProperty == 'function'
11212 ? function (obj, key, options) {
11213 Object.defineProperty(obj, key, options)
11214 return obj
11215 }
11216 : function (obj, key, options) { // < es5
11217 obj[key] = options.value
11218 return obj
11219 }
11220
11221 , makeOptions = function (value, options) {
11222 var oo = typeof options == 'object'
11223 , os = !oo && typeof options == 'string'
11224 , op = function (p) {
11225 return oo
11226 ? !!options[p]
11227 : os
11228 ? options.indexOf(p[0]) > -1
11229 : false
11230 }
11231
11232 return {
11233 enumerable : op('enumerable')
11234 , configurable : op('configurable')
11235 , writable : op('writable')
11236 , value : value
11237 }
11238 }
11239
11240 , prr = function (obj, key, value, options) {
11241 var k
11242
11243 options = makeOptions(value, options)
11244
11245 if (typeof key == 'object') {
11246 for (k in key) {
11247 if (Object.hasOwnProperty.call(key, k)) {
11248 options.value = key[k]
11249 setProperty(obj, k, options)
11250 }
11251 }
11252 return obj
11253 }
11254
11255 return setProperty(obj, key, options)
11256 }
11257
11258 return prr
11259})
11260},{}],75:[function(_dereq_,module,exports){
11261(function (process){(function (){
11262// Copyright Joyent, Inc. and other Node contributors.
11263//
11264// Permission is hereby granted, free of charge, to any person obtaining a
11265// copy of this software and associated documentation files (the
11266// "Software"), to deal in the Software without restriction, including
11267// without limitation the rights to use, copy, modify, merge, publish,
11268// distribute, sublicense, and/or sell copies of the Software, and to permit
11269// persons to whom the Software is furnished to do so, subject to the
11270// following conditions:
11271//
11272// The above copyright notice and this permission notice shall be included
11273// in all copies or substantial portions of the Software.
11274//
11275// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11276// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11277// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11278// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11279// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11280// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11281// USE OR OTHER DEALINGS IN THE SOFTWARE.
11282
11283// a duplex stream is just a stream that is both readable and writable.
11284// Since JS doesn't have multiple prototypal inheritance, this class
11285// prototypally inherits from Readable, and then parasitically from
11286// Writable.
11287
11288module.exports = Duplex;
11289
11290/*<replacement>*/
11291var objectKeys = Object.keys || function (obj) {
11292 var keys = [];
11293 for (var key in obj) keys.push(key);
11294 return keys;
11295}
11296/*</replacement>*/
11297
11298
11299/*<replacement>*/
11300var util = _dereq_(14);
11301util.inherits = _dereq_(37);
11302/*</replacement>*/
11303
11304var Readable = _dereq_(77);
11305var Writable = _dereq_(79);
11306
11307util.inherits(Duplex, Readable);
11308
11309forEach(objectKeys(Writable.prototype), function(method) {
11310 if (!Duplex.prototype[method])
11311 Duplex.prototype[method] = Writable.prototype[method];
11312});
11313
11314function Duplex(options) {
11315 if (!(this instanceof Duplex))
11316 return new Duplex(options);
11317
11318 Readable.call(this, options);
11319 Writable.call(this, options);
11320
11321 if (options && options.readable === false)
11322 this.readable = false;
11323
11324 if (options && options.writable === false)
11325 this.writable = false;
11326
11327 this.allowHalfOpen = true;
11328 if (options && options.allowHalfOpen === false)
11329 this.allowHalfOpen = false;
11330
11331 this.once('end', onend);
11332}
11333
11334// the no-half-open enforcer
11335function onend() {
11336 // if we allow half-open state, or if the writable side ended,
11337 // then we're ok.
11338 if (this.allowHalfOpen || this._writableState.ended)
11339 return;
11340
11341 // no more data can be written.
11342 // But allow more writes to happen in this tick.
11343 process.nextTick(this.end.bind(this));
11344}
11345
11346function forEach (xs, f) {
11347 for (var i = 0, l = xs.length; i < l; i++) {
11348 f(xs[i], i);
11349 }
11350}
11351
11352}).call(this)}).call(this,_dereq_(73))
11353},{"14":14,"37":37,"73":73,"77":77,"79":79}],76:[function(_dereq_,module,exports){
11354// Copyright Joyent, Inc. and other Node contributors.
11355//
11356// Permission is hereby granted, free of charge, to any person obtaining a
11357// copy of this software and associated documentation files (the
11358// "Software"), to deal in the Software without restriction, including
11359// without limitation the rights to use, copy, modify, merge, publish,
11360// distribute, sublicense, and/or sell copies of the Software, and to permit
11361// persons to whom the Software is furnished to do so, subject to the
11362// following conditions:
11363//
11364// The above copyright notice and this permission notice shall be included
11365// in all copies or substantial portions of the Software.
11366//
11367// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11368// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11369// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11370// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11371// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11372// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11373// USE OR OTHER DEALINGS IN THE SOFTWARE.
11374
11375// a passthrough stream.
11376// basically just the most minimal sort of Transform stream.
11377// Every written chunk gets output as-is.
11378
11379module.exports = PassThrough;
11380
11381var Transform = _dereq_(78);
11382
11383/*<replacement>*/
11384var util = _dereq_(14);
11385util.inherits = _dereq_(37);
11386/*</replacement>*/
11387
11388util.inherits(PassThrough, Transform);
11389
11390function PassThrough(options) {
11391 if (!(this instanceof PassThrough))
11392 return new PassThrough(options);
11393
11394 Transform.call(this, options);
11395}
11396
11397PassThrough.prototype._transform = function(chunk, encoding, cb) {
11398 cb(null, chunk);
11399};
11400
11401},{"14":14,"37":37,"78":78}],77:[function(_dereq_,module,exports){
11402(function (process){(function (){
11403// Copyright Joyent, Inc. and other Node contributors.
11404//
11405// Permission is hereby granted, free of charge, to any person obtaining a
11406// copy of this software and associated documentation files (the
11407// "Software"), to deal in the Software without restriction, including
11408// without limitation the rights to use, copy, modify, merge, publish,
11409// distribute, sublicense, and/or sell copies of the Software, and to permit
11410// persons to whom the Software is furnished to do so, subject to the
11411// following conditions:
11412//
11413// The above copyright notice and this permission notice shall be included
11414// in all copies or substantial portions of the Software.
11415//
11416// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11417// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11418// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11419// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11420// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11421// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11422// USE OR OTHER DEALINGS IN THE SOFTWARE.
11423
11424module.exports = Readable;
11425
11426/*<replacement>*/
11427var isArray = _dereq_(80);
11428/*</replacement>*/
11429
11430
11431/*<replacement>*/
11432var Buffer = _dereq_(13).Buffer;
11433/*</replacement>*/
11434
11435Readable.ReadableState = ReadableState;
11436
11437var EE = _dereq_(26).EventEmitter;
11438
11439/*<replacement>*/
11440if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11441 return emitter.listeners(type).length;
11442};
11443/*</replacement>*/
11444
11445var Stream = _dereq_(85);
11446
11447/*<replacement>*/
11448var util = _dereq_(14);
11449util.inherits = _dereq_(37);
11450/*</replacement>*/
11451
11452var StringDecoder;
11453
11454
11455/*<replacement>*/
11456var debug = _dereq_(11);
11457if (debug && debug.debuglog) {
11458 debug = debug.debuglog('stream');
11459} else {
11460 debug = function () {};
11461}
11462/*</replacement>*/
11463
11464
11465util.inherits(Readable, Stream);
11466
11467function ReadableState(options, stream) {
11468 var Duplex = _dereq_(75);
11469
11470 options = options || {};
11471
11472 // the point at which it stops calling _read() to fill the buffer
11473 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11474 var hwm = options.highWaterMark;
11475 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
11476 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
11477
11478 // cast to ints.
11479 this.highWaterMark = ~~this.highWaterMark;
11480
11481 this.buffer = [];
11482 this.length = 0;
11483 this.pipes = null;
11484 this.pipesCount = 0;
11485 this.flowing = null;
11486 this.ended = false;
11487 this.endEmitted = false;
11488 this.reading = false;
11489
11490 // a flag to be able to tell if the onwrite cb is called immediately,
11491 // or on a later tick. We set this to true at first, because any
11492 // actions that shouldn't happen until "later" should generally also
11493 // not happen before the first write call.
11494 this.sync = true;
11495
11496 // whenever we return null, then we set a flag to say
11497 // that we're awaiting a 'readable' event emission.
11498 this.needReadable = false;
11499 this.emittedReadable = false;
11500 this.readableListening = false;
11501
11502
11503 // object stream flag. Used to make read(n) ignore n and to
11504 // make all the buffer merging and length checks go away
11505 this.objectMode = !!options.objectMode;
11506
11507 if (stream instanceof Duplex)
11508 this.objectMode = this.objectMode || !!options.readableObjectMode;
11509
11510 // Crypto is kind of old and crusty. Historically, its default string
11511 // encoding is 'binary' so we have to make this configurable.
11512 // Everything else in the universe uses 'utf8', though.
11513 this.defaultEncoding = options.defaultEncoding || 'utf8';
11514
11515 // when piping, we only care about 'readable' events that happen
11516 // after read()ing all the bytes and not getting any pushback.
11517 this.ranOut = false;
11518
11519 // the number of writers that are awaiting a drain event in .pipe()s
11520 this.awaitDrain = 0;
11521
11522 // if true, a maybeReadMore has been scheduled
11523 this.readingMore = false;
11524
11525 this.decoder = null;
11526 this.encoding = null;
11527 if (options.encoding) {
11528 if (!StringDecoder)
11529 StringDecoder = _dereq_(81).StringDecoder;
11530 this.decoder = new StringDecoder(options.encoding);
11531 this.encoding = options.encoding;
11532 }
11533}
11534
11535function Readable(options) {
11536 var Duplex = _dereq_(75);
11537
11538 if (!(this instanceof Readable))
11539 return new Readable(options);
11540
11541 this._readableState = new ReadableState(options, this);
11542
11543 // legacy
11544 this.readable = true;
11545
11546 Stream.call(this);
11547}
11548
11549// Manually shove something into the read() buffer.
11550// This returns true if the highWaterMark has not been hit yet,
11551// similar to how Writable.write() returns true if you should
11552// write() some more.
11553Readable.prototype.push = function(chunk, encoding) {
11554 var state = this._readableState;
11555
11556 if (util.isString(chunk) && !state.objectMode) {
11557 encoding = encoding || state.defaultEncoding;
11558 if (encoding !== state.encoding) {
11559 chunk = new Buffer(chunk, encoding);
11560 encoding = '';
11561 }
11562 }
11563
11564 return readableAddChunk(this, state, chunk, encoding, false);
11565};
11566
11567// Unshift should *always* be something directly out of read()
11568Readable.prototype.unshift = function(chunk) {
11569 var state = this._readableState;
11570 return readableAddChunk(this, state, chunk, '', true);
11571};
11572
11573function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11574 var er = chunkInvalid(state, chunk);
11575 if (er) {
11576 stream.emit('error', er);
11577 } else if (util.isNullOrUndefined(chunk)) {
11578 state.reading = false;
11579 if (!state.ended)
11580 onEofChunk(stream, state);
11581 } else if (state.objectMode || chunk && chunk.length > 0) {
11582 if (state.ended && !addToFront) {
11583 var e = new Error('stream.push() after EOF');
11584 stream.emit('error', e);
11585 } else if (state.endEmitted && addToFront) {
11586 var e = new Error('stream.unshift() after end event');
11587 stream.emit('error', e);
11588 } else {
11589 if (state.decoder && !addToFront && !encoding)
11590 chunk = state.decoder.write(chunk);
11591
11592 if (!addToFront)
11593 state.reading = false;
11594
11595 // if we want the data now, just emit it.
11596 if (state.flowing && state.length === 0 && !state.sync) {
11597 stream.emit('data', chunk);
11598 stream.read(0);
11599 } else {
11600 // update the buffer info.
11601 state.length += state.objectMode ? 1 : chunk.length;
11602 if (addToFront)
11603 state.buffer.unshift(chunk);
11604 else
11605 state.buffer.push(chunk);
11606
11607 if (state.needReadable)
11608 emitReadable(stream);
11609 }
11610
11611 maybeReadMore(stream, state);
11612 }
11613 } else if (!addToFront) {
11614 state.reading = false;
11615 }
11616
11617 return needMoreData(state);
11618}
11619
11620
11621
11622// if it's past the high water mark, we can push in some more.
11623// Also, if we have no data yet, we can stand some
11624// more bytes. This is to work around cases where hwm=0,
11625// such as the repl. Also, if the push() triggered a
11626// readable event, and the user called read(largeNumber) such that
11627// needReadable was set, then we ought to push more, so that another
11628// 'readable' event will be triggered.
11629function needMoreData(state) {
11630 return !state.ended &&
11631 (state.needReadable ||
11632 state.length < state.highWaterMark ||
11633 state.length === 0);
11634}
11635
11636// backwards compatibility.
11637Readable.prototype.setEncoding = function(enc) {
11638 if (!StringDecoder)
11639 StringDecoder = _dereq_(81).StringDecoder;
11640 this._readableState.decoder = new StringDecoder(enc);
11641 this._readableState.encoding = enc;
11642 return this;
11643};
11644
11645// Don't raise the hwm > 128MB
11646var MAX_HWM = 0x800000;
11647function roundUpToNextPowerOf2(n) {
11648 if (n >= MAX_HWM) {
11649 n = MAX_HWM;
11650 } else {
11651 // Get the next highest power of 2
11652 n--;
11653 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
11654 n++;
11655 }
11656 return n;
11657}
11658
11659function howMuchToRead(n, state) {
11660 if (state.length === 0 && state.ended)
11661 return 0;
11662
11663 if (state.objectMode)
11664 return n === 0 ? 0 : 1;
11665
11666 if (isNaN(n) || util.isNull(n)) {
11667 // only flow one buffer at a time
11668 if (state.flowing && state.buffer.length)
11669 return state.buffer[0].length;
11670 else
11671 return state.length;
11672 }
11673
11674 if (n <= 0)
11675 return 0;
11676
11677 // If we're asking for more than the target buffer level,
11678 // then raise the water mark. Bump up to the next highest
11679 // power of 2, to prevent increasing it excessively in tiny
11680 // amounts.
11681 if (n > state.highWaterMark)
11682 state.highWaterMark = roundUpToNextPowerOf2(n);
11683
11684 // don't have that much. return null, unless we've ended.
11685 if (n > state.length) {
11686 if (!state.ended) {
11687 state.needReadable = true;
11688 return 0;
11689 } else
11690 return state.length;
11691 }
11692
11693 return n;
11694}
11695
11696// you can override either this method, or the async _read(n) below.
11697Readable.prototype.read = function(n) {
11698 debug('read', n);
11699 var state = this._readableState;
11700 var nOrig = n;
11701
11702 if (!util.isNumber(n) || n > 0)
11703 state.emittedReadable = false;
11704
11705 // if we're doing read(0) to trigger a readable event, but we
11706 // already have a bunch of data in the buffer, then just trigger
11707 // the 'readable' event and move on.
11708 if (n === 0 &&
11709 state.needReadable &&
11710 (state.length >= state.highWaterMark || state.ended)) {
11711 debug('read: emitReadable', state.length, state.ended);
11712 if (state.length === 0 && state.ended)
11713 endReadable(this);
11714 else
11715 emitReadable(this);
11716 return null;
11717 }
11718
11719 n = howMuchToRead(n, state);
11720
11721 // if we've ended, and we're now clear, then finish it up.
11722 if (n === 0 && state.ended) {
11723 if (state.length === 0)
11724 endReadable(this);
11725 return null;
11726 }
11727
11728 // All the actual chunk generation logic needs to be
11729 // *below* the call to _read. The reason is that in certain
11730 // synthetic stream cases, such as passthrough streams, _read
11731 // may be a completely synchronous operation which may change
11732 // the state of the read buffer, providing enough data when
11733 // before there was *not* enough.
11734 //
11735 // So, the steps are:
11736 // 1. Figure out what the state of things will be after we do
11737 // a read from the buffer.
11738 //
11739 // 2. If that resulting state will trigger a _read, then call _read.
11740 // Note that this may be asynchronous, or synchronous. Yes, it is
11741 // deeply ugly to write APIs this way, but that still doesn't mean
11742 // that the Readable class should behave improperly, as streams are
11743 // designed to be sync/async agnostic.
11744 // Take note if the _read call is sync or async (ie, if the read call
11745 // has returned yet), so that we know whether or not it's safe to emit
11746 // 'readable' etc.
11747 //
11748 // 3. Actually pull the requested chunks out of the buffer and return.
11749
11750 // if we need a readable event, then we need to do some reading.
11751 var doRead = state.needReadable;
11752 debug('need readable', doRead);
11753
11754 // if we currently have less than the highWaterMark, then also read some
11755 if (state.length === 0 || state.length - n < state.highWaterMark) {
11756 doRead = true;
11757 debug('length less than watermark', doRead);
11758 }
11759
11760 // however, if we've ended, then there's no point, and if we're already
11761 // reading, then it's unnecessary.
11762 if (state.ended || state.reading) {
11763 doRead = false;
11764 debug('reading or ended', doRead);
11765 }
11766
11767 if (doRead) {
11768 debug('do read');
11769 state.reading = true;
11770 state.sync = true;
11771 // if the length is currently zero, then we *need* a readable event.
11772 if (state.length === 0)
11773 state.needReadable = true;
11774 // call internal read method
11775 this._read(state.highWaterMark);
11776 state.sync = false;
11777 }
11778
11779 // If _read pushed data synchronously, then `reading` will be false,
11780 // and we need to re-evaluate how much data we can return to the user.
11781 if (doRead && !state.reading)
11782 n = howMuchToRead(nOrig, state);
11783
11784 var ret;
11785 if (n > 0)
11786 ret = fromList(n, state);
11787 else
11788 ret = null;
11789
11790 if (util.isNull(ret)) {
11791 state.needReadable = true;
11792 n = 0;
11793 }
11794
11795 state.length -= n;
11796
11797 // If we have nothing in the buffer, then we want to know
11798 // as soon as we *do* get something into the buffer.
11799 if (state.length === 0 && !state.ended)
11800 state.needReadable = true;
11801
11802 // If we tried to read() past the EOF, then emit end on the next tick.
11803 if (nOrig !== n && state.ended && state.length === 0)
11804 endReadable(this);
11805
11806 if (!util.isNull(ret))
11807 this.emit('data', ret);
11808
11809 return ret;
11810};
11811
11812function chunkInvalid(state, chunk) {
11813 var er = null;
11814 if (!util.isBuffer(chunk) &&
11815 !util.isString(chunk) &&
11816 !util.isNullOrUndefined(chunk) &&
11817 !state.objectMode) {
11818 er = new TypeError('Invalid non-string/buffer chunk');
11819 }
11820 return er;
11821}
11822
11823
11824function onEofChunk(stream, state) {
11825 if (state.decoder && !state.ended) {
11826 var chunk = state.decoder.end();
11827 if (chunk && chunk.length) {
11828 state.buffer.push(chunk);
11829 state.length += state.objectMode ? 1 : chunk.length;
11830 }
11831 }
11832 state.ended = true;
11833
11834 // emit 'readable' now to make sure it gets picked up.
11835 emitReadable(stream);
11836}
11837
11838// Don't emit readable right away in sync mode, because this can trigger
11839// another read() call => stack overflow. This way, it might trigger
11840// a nextTick recursion warning, but that's not so bad.
11841function emitReadable(stream) {
11842 var state = stream._readableState;
11843 state.needReadable = false;
11844 if (!state.emittedReadable) {
11845 debug('emitReadable', state.flowing);
11846 state.emittedReadable = true;
11847 if (state.sync)
11848 process.nextTick(function() {
11849 emitReadable_(stream);
11850 });
11851 else
11852 emitReadable_(stream);
11853 }
11854}
11855
11856function emitReadable_(stream) {
11857 debug('emit readable');
11858 stream.emit('readable');
11859 flow(stream);
11860}
11861
11862
11863// at this point, the user has presumably seen the 'readable' event,
11864// and called read() to consume some data. that may have triggered
11865// in turn another _read(n) call, in which case reading = true if
11866// it's in progress.
11867// However, if we're not ended, or reading, and the length < hwm,
11868// then go ahead and try to read some more preemptively.
11869function maybeReadMore(stream, state) {
11870 if (!state.readingMore) {
11871 state.readingMore = true;
11872 process.nextTick(function() {
11873 maybeReadMore_(stream, state);
11874 });
11875 }
11876}
11877
11878function maybeReadMore_(stream, state) {
11879 var len = state.length;
11880 while (!state.reading && !state.flowing && !state.ended &&
11881 state.length < state.highWaterMark) {
11882 debug('maybeReadMore read 0');
11883 stream.read(0);
11884 if (len === state.length)
11885 // didn't get any data, stop spinning.
11886 break;
11887 else
11888 len = state.length;
11889 }
11890 state.readingMore = false;
11891}
11892
11893// abstract method. to be overridden in specific implementation classes.
11894// call cb(er, data) where data is <= n in length.
11895// for virtual (non-string, non-buffer) streams, "length" is somewhat
11896// arbitrary, and perhaps not very meaningful.
11897Readable.prototype._read = function(n) {
11898 this.emit('error', new Error('not implemented'));
11899};
11900
11901Readable.prototype.pipe = function(dest, pipeOpts) {
11902 var src = this;
11903 var state = this._readableState;
11904
11905 switch (state.pipesCount) {
11906 case 0:
11907 state.pipes = dest;
11908 break;
11909 case 1:
11910 state.pipes = [state.pipes, dest];
11911 break;
11912 default:
11913 state.pipes.push(dest);
11914 break;
11915 }
11916 state.pipesCount += 1;
11917 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
11918
11919 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
11920 dest !== process.stdout &&
11921 dest !== process.stderr;
11922
11923 var endFn = doEnd ? onend : cleanup;
11924 if (state.endEmitted)
11925 process.nextTick(endFn);
11926 else
11927 src.once('end', endFn);
11928
11929 dest.on('unpipe', onunpipe);
11930 function onunpipe(readable) {
11931 debug('onunpipe');
11932 if (readable === src) {
11933 cleanup();
11934 }
11935 }
11936
11937 function onend() {
11938 debug('onend');
11939 dest.end();
11940 }
11941
11942 // when the dest drains, it reduces the awaitDrain counter
11943 // on the source. This would be more elegant with a .once()
11944 // handler in flow(), but adding and removing repeatedly is
11945 // too slow.
11946 var ondrain = pipeOnDrain(src);
11947 dest.on('drain', ondrain);
11948
11949 function cleanup() {
11950 debug('cleanup');
11951 // cleanup event handlers once the pipe is broken
11952 dest.removeListener('close', onclose);
11953 dest.removeListener('finish', onfinish);
11954 dest.removeListener('drain', ondrain);
11955 dest.removeListener('error', onerror);
11956 dest.removeListener('unpipe', onunpipe);
11957 src.removeListener('end', onend);
11958 src.removeListener('end', cleanup);
11959 src.removeListener('data', ondata);
11960
11961 // if the reader is waiting for a drain event from this
11962 // specific writer, then it would cause it to never start
11963 // flowing again.
11964 // So, if this is awaiting a drain, then we just call it now.
11965 // If we don't know, then assume that we are waiting for one.
11966 if (state.awaitDrain &&
11967 (!dest._writableState || dest._writableState.needDrain))
11968 ondrain();
11969 }
11970
11971 src.on('data', ondata);
11972 function ondata(chunk) {
11973 debug('ondata');
11974 var ret = dest.write(chunk);
11975 if (false === ret) {
11976 debug('false write response, pause',
11977 src._readableState.awaitDrain);
11978 src._readableState.awaitDrain++;
11979 src.pause();
11980 }
11981 }
11982
11983 // if the dest has an error, then stop piping into it.
11984 // however, don't suppress the throwing behavior for this.
11985 function onerror(er) {
11986 debug('onerror', er);
11987 unpipe();
11988 dest.removeListener('error', onerror);
11989 if (EE.listenerCount(dest, 'error') === 0)
11990 dest.emit('error', er);
11991 }
11992 // This is a brutally ugly hack to make sure that our error handler
11993 // is attached before any userland ones. NEVER DO THIS.
11994 if (!dest._events || !dest._events.error)
11995 dest.on('error', onerror);
11996 else if (isArray(dest._events.error))
11997 dest._events.error.unshift(onerror);
11998 else
11999 dest._events.error = [onerror, dest._events.error];
12000
12001
12002
12003 // Both close and finish should trigger unpipe, but only once.
12004 function onclose() {
12005 dest.removeListener('finish', onfinish);
12006 unpipe();
12007 }
12008 dest.once('close', onclose);
12009 function onfinish() {
12010 debug('onfinish');
12011 dest.removeListener('close', onclose);
12012 unpipe();
12013 }
12014 dest.once('finish', onfinish);
12015
12016 function unpipe() {
12017 debug('unpipe');
12018 src.unpipe(dest);
12019 }
12020
12021 // tell the dest that it's being piped to
12022 dest.emit('pipe', src);
12023
12024 // start the flow if it hasn't been started already.
12025 if (!state.flowing) {
12026 debug('pipe resume');
12027 src.resume();
12028 }
12029
12030 return dest;
12031};
12032
12033function pipeOnDrain(src) {
12034 return function() {
12035 var state = src._readableState;
12036 debug('pipeOnDrain', state.awaitDrain);
12037 if (state.awaitDrain)
12038 state.awaitDrain--;
12039 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
12040 state.flowing = true;
12041 flow(src);
12042 }
12043 };
12044}
12045
12046
12047Readable.prototype.unpipe = function(dest) {
12048 var state = this._readableState;
12049
12050 // if we're not piping anywhere, then do nothing.
12051 if (state.pipesCount === 0)
12052 return this;
12053
12054 // just one destination. most common case.
12055 if (state.pipesCount === 1) {
12056 // passed in one, but it's not the right one.
12057 if (dest && dest !== state.pipes)
12058 return this;
12059
12060 if (!dest)
12061 dest = state.pipes;
12062
12063 // got a match.
12064 state.pipes = null;
12065 state.pipesCount = 0;
12066 state.flowing = false;
12067 if (dest)
12068 dest.emit('unpipe', this);
12069 return this;
12070 }
12071
12072 // slow case. multiple pipe destinations.
12073
12074 if (!dest) {
12075 // remove all.
12076 var dests = state.pipes;
12077 var len = state.pipesCount;
12078 state.pipes = null;
12079 state.pipesCount = 0;
12080 state.flowing = false;
12081
12082 for (var i = 0; i < len; i++)
12083 dests[i].emit('unpipe', this);
12084 return this;
12085 }
12086
12087 // try to find the right one.
12088 var i = indexOf(state.pipes, dest);
12089 if (i === -1)
12090 return this;
12091
12092 state.pipes.splice(i, 1);
12093 state.pipesCount -= 1;
12094 if (state.pipesCount === 1)
12095 state.pipes = state.pipes[0];
12096
12097 dest.emit('unpipe', this);
12098
12099 return this;
12100};
12101
12102// set up data events if they are asked for
12103// Ensure readable listeners eventually get something
12104Readable.prototype.on = function(ev, fn) {
12105 var res = Stream.prototype.on.call(this, ev, fn);
12106
12107 // If listening to data, and it has not explicitly been paused,
12108 // then call resume to start the flow of data on the next tick.
12109 if (ev === 'data' && false !== this._readableState.flowing) {
12110 this.resume();
12111 }
12112
12113 if (ev === 'readable' && this.readable) {
12114 var state = this._readableState;
12115 if (!state.readableListening) {
12116 state.readableListening = true;
12117 state.emittedReadable = false;
12118 state.needReadable = true;
12119 if (!state.reading) {
12120 var self = this;
12121 process.nextTick(function() {
12122 debug('readable nexttick read 0');
12123 self.read(0);
12124 });
12125 } else if (state.length) {
12126 emitReadable(this, state);
12127 }
12128 }
12129 }
12130
12131 return res;
12132};
12133Readable.prototype.addListener = Readable.prototype.on;
12134
12135// pause() and resume() are remnants of the legacy readable stream API
12136// If the user uses them, then switch into old mode.
12137Readable.prototype.resume = function() {
12138 var state = this._readableState;
12139 if (!state.flowing) {
12140 debug('resume');
12141 state.flowing = true;
12142 if (!state.reading) {
12143 debug('resume read 0');
12144 this.read(0);
12145 }
12146 resume(this, state);
12147 }
12148 return this;
12149};
12150
12151function resume(stream, state) {
12152 if (!state.resumeScheduled) {
12153 state.resumeScheduled = true;
12154 process.nextTick(function() {
12155 resume_(stream, state);
12156 });
12157 }
12158}
12159
12160function resume_(stream, state) {
12161 state.resumeScheduled = false;
12162 stream.emit('resume');
12163 flow(stream);
12164 if (state.flowing && !state.reading)
12165 stream.read(0);
12166}
12167
12168Readable.prototype.pause = function() {
12169 debug('call pause flowing=%j', this._readableState.flowing);
12170 if (false !== this._readableState.flowing) {
12171 debug('pause');
12172 this._readableState.flowing = false;
12173 this.emit('pause');
12174 }
12175 return this;
12176};
12177
12178function flow(stream) {
12179 var state = stream._readableState;
12180 debug('flow', state.flowing);
12181 if (state.flowing) {
12182 do {
12183 var chunk = stream.read();
12184 } while (null !== chunk && state.flowing);
12185 }
12186}
12187
12188// wrap an old-style stream as the async data source.
12189// This is *not* part of the readable stream interface.
12190// It is an ugly unfortunate mess of history.
12191Readable.prototype.wrap = function(stream) {
12192 var state = this._readableState;
12193 var paused = false;
12194
12195 var self = this;
12196 stream.on('end', function() {
12197 debug('wrapped end');
12198 if (state.decoder && !state.ended) {
12199 var chunk = state.decoder.end();
12200 if (chunk && chunk.length)
12201 self.push(chunk);
12202 }
12203
12204 self.push(null);
12205 });
12206
12207 stream.on('data', function(chunk) {
12208 debug('wrapped data');
12209 if (state.decoder)
12210 chunk = state.decoder.write(chunk);
12211 if (!chunk || !state.objectMode && !chunk.length)
12212 return;
12213
12214 var ret = self.push(chunk);
12215 if (!ret) {
12216 paused = true;
12217 stream.pause();
12218 }
12219 });
12220
12221 // proxy all the other methods.
12222 // important when wrapping filters and duplexes.
12223 for (var i in stream) {
12224 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
12225 this[i] = function(method) { return function() {
12226 return stream[method].apply(stream, arguments);
12227 }}(i);
12228 }
12229 }
12230
12231 // proxy certain important events.
12232 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
12233 forEach(events, function(ev) {
12234 stream.on(ev, self.emit.bind(self, ev));
12235 });
12236
12237 // when we try to consume some more bytes, simply unpause the
12238 // underlying stream.
12239 self._read = function(n) {
12240 debug('wrapped _read', n);
12241 if (paused) {
12242 paused = false;
12243 stream.resume();
12244 }
12245 };
12246
12247 return self;
12248};
12249
12250
12251
12252// exposed for testing purposes only.
12253Readable._fromList = fromList;
12254
12255// Pluck off n bytes from an array of buffers.
12256// Length is the combined lengths of all the buffers in the list.
12257function fromList(n, state) {
12258 var list = state.buffer;
12259 var length = state.length;
12260 var stringMode = !!state.decoder;
12261 var objectMode = !!state.objectMode;
12262 var ret;
12263
12264 // nothing in the list, definitely empty.
12265 if (list.length === 0)
12266 return null;
12267
12268 if (length === 0)
12269 ret = null;
12270 else if (objectMode)
12271 ret = list.shift();
12272 else if (!n || n >= length) {
12273 // read it all, truncate the array.
12274 if (stringMode)
12275 ret = list.join('');
12276 else
12277 ret = Buffer.concat(list, length);
12278 list.length = 0;
12279 } else {
12280 // read just some of it.
12281 if (n < list[0].length) {
12282 // just take a part of the first list item.
12283 // slice is the same for buffers and strings.
12284 var buf = list[0];
12285 ret = buf.slice(0, n);
12286 list[0] = buf.slice(n);
12287 } else if (n === list[0].length) {
12288 // first list is a perfect match
12289 ret = list.shift();
12290 } else {
12291 // complex case.
12292 // we have enough to cover it, but it spans past the first buffer.
12293 if (stringMode)
12294 ret = '';
12295 else
12296 ret = new Buffer(n);
12297
12298 var c = 0;
12299 for (var i = 0, l = list.length; i < l && c < n; i++) {
12300 var buf = list[0];
12301 var cpy = Math.min(n - c, buf.length);
12302
12303 if (stringMode)
12304 ret += buf.slice(0, cpy);
12305 else
12306 buf.copy(ret, c, 0, cpy);
12307
12308 if (cpy < buf.length)
12309 list[0] = buf.slice(cpy);
12310 else
12311 list.shift();
12312
12313 c += cpy;
12314 }
12315 }
12316 }
12317
12318 return ret;
12319}
12320
12321function endReadable(stream) {
12322 var state = stream._readableState;
12323
12324 // If we get here before consuming all the bytes, then that is a
12325 // bug in node. Should never happen.
12326 if (state.length > 0)
12327 throw new Error('endReadable called on non-empty stream');
12328
12329 if (!state.endEmitted) {
12330 state.ended = true;
12331 process.nextTick(function() {
12332 // Check that we didn't get one last unshift.
12333 if (!state.endEmitted && state.length === 0) {
12334 state.endEmitted = true;
12335 stream.readable = false;
12336 stream.emit('end');
12337 }
12338 });
12339 }
12340}
12341
12342function forEach (xs, f) {
12343 for (var i = 0, l = xs.length; i < l; i++) {
12344 f(xs[i], i);
12345 }
12346}
12347
12348function indexOf (xs, x) {
12349 for (var i = 0, l = xs.length; i < l; i++) {
12350 if (xs[i] === x) return i;
12351 }
12352 return -1;
12353}
12354
12355}).call(this)}).call(this,_dereq_(73))
12356},{"11":11,"13":13,"14":14,"26":26,"37":37,"73":73,"75":75,"80":80,"81":81,"85":85}],78:[function(_dereq_,module,exports){
12357// Copyright Joyent, Inc. and other Node contributors.
12358//
12359// Permission is hereby granted, free of charge, to any person obtaining a
12360// copy of this software and associated documentation files (the
12361// "Software"), to deal in the Software without restriction, including
12362// without limitation the rights to use, copy, modify, merge, publish,
12363// distribute, sublicense, and/or sell copies of the Software, and to permit
12364// persons to whom the Software is furnished to do so, subject to the
12365// following conditions:
12366//
12367// The above copyright notice and this permission notice shall be included
12368// in all copies or substantial portions of the Software.
12369//
12370// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12371// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12372// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12373// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12374// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12375// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12376// USE OR OTHER DEALINGS IN THE SOFTWARE.
12377
12378
12379// a transform stream is a readable/writable stream where you do
12380// something with the data. Sometimes it's called a "filter",
12381// but that's not a great name for it, since that implies a thing where
12382// some bits pass through, and others are simply ignored. (That would
12383// be a valid example of a transform, of course.)
12384//
12385// While the output is causally related to the input, it's not a
12386// necessarily symmetric or synchronous transformation. For example,
12387// a zlib stream might take multiple plain-text writes(), and then
12388// emit a single compressed chunk some time in the future.
12389//
12390// Here's how this works:
12391//
12392// The Transform stream has all the aspects of the readable and writable
12393// stream classes. When you write(chunk), that calls _write(chunk,cb)
12394// internally, and returns false if there's a lot of pending writes
12395// buffered up. When you call read(), that calls _read(n) until
12396// there's enough pending readable data buffered up.
12397//
12398// In a transform stream, the written data is placed in a buffer. When
12399// _read(n) is called, it transforms the queued up data, calling the
12400// buffered _write cb's as it consumes chunks. If consuming a single
12401// written chunk would result in multiple output chunks, then the first
12402// outputted bit calls the readcb, and subsequent chunks just go into
12403// the read buffer, and will cause it to emit 'readable' if necessary.
12404//
12405// This way, back-pressure is actually determined by the reading side,
12406// since _read has to be called to start processing a new chunk. However,
12407// a pathological inflate type of transform can cause excessive buffering
12408// here. For example, imagine a stream where every byte of input is
12409// interpreted as an integer from 0-255, and then results in that many
12410// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12411// 1kb of data being output. In this case, you could write a very small
12412// amount of input, and end up with a very large amount of output. In
12413// such a pathological inflating mechanism, there'd be no way to tell
12414// the system to stop doing the transform. A single 4MB write could
12415// cause the system to run out of memory.
12416//
12417// However, even in such a pathological case, only a single written chunk
12418// would be consumed, and then the rest would wait (un-transformed) until
12419// the results of the previous transformed chunk were consumed.
12420
12421module.exports = Transform;
12422
12423var Duplex = _dereq_(75);
12424
12425/*<replacement>*/
12426var util = _dereq_(14);
12427util.inherits = _dereq_(37);
12428/*</replacement>*/
12429
12430util.inherits(Transform, Duplex);
12431
12432
12433function TransformState(options, stream) {
12434 this.afterTransform = function(er, data) {
12435 return afterTransform(stream, er, data);
12436 };
12437
12438 this.needTransform = false;
12439 this.transforming = false;
12440 this.writecb = null;
12441 this.writechunk = null;
12442}
12443
12444function afterTransform(stream, er, data) {
12445 var ts = stream._transformState;
12446 ts.transforming = false;
12447
12448 var cb = ts.writecb;
12449
12450 if (!cb)
12451 return stream.emit('error', new Error('no writecb in Transform class'));
12452
12453 ts.writechunk = null;
12454 ts.writecb = null;
12455
12456 if (!util.isNullOrUndefined(data))
12457 stream.push(data);
12458
12459 if (cb)
12460 cb(er);
12461
12462 var rs = stream._readableState;
12463 rs.reading = false;
12464 if (rs.needReadable || rs.length < rs.highWaterMark) {
12465 stream._read(rs.highWaterMark);
12466 }
12467}
12468
12469
12470function Transform(options) {
12471 if (!(this instanceof Transform))
12472 return new Transform(options);
12473
12474 Duplex.call(this, options);
12475
12476 this._transformState = new TransformState(options, this);
12477
12478 // when the writable side finishes, then flush out anything remaining.
12479 var stream = this;
12480
12481 // start out asking for a readable event once data is transformed.
12482 this._readableState.needReadable = true;
12483
12484 // we have implemented the _read method, and done the other things
12485 // that Readable wants before the first _read call, so unset the
12486 // sync guard flag.
12487 this._readableState.sync = false;
12488
12489 this.once('prefinish', function() {
12490 if (util.isFunction(this._flush))
12491 this._flush(function(er) {
12492 done(stream, er);
12493 });
12494 else
12495 done(stream);
12496 });
12497}
12498
12499Transform.prototype.push = function(chunk, encoding) {
12500 this._transformState.needTransform = false;
12501 return Duplex.prototype.push.call(this, chunk, encoding);
12502};
12503
12504// This is the part where you do stuff!
12505// override this function in implementation classes.
12506// 'chunk' is an input chunk.
12507//
12508// Call `push(newChunk)` to pass along transformed output
12509// to the readable side. You may call 'push' zero or more times.
12510//
12511// Call `cb(err)` when you are done with this chunk. If you pass
12512// an error, then that'll put the hurt on the whole operation. If you
12513// never call cb(), then you'll never get another chunk.
12514Transform.prototype._transform = function(chunk, encoding, cb) {
12515 throw new Error('not implemented');
12516};
12517
12518Transform.prototype._write = function(chunk, encoding, cb) {
12519 var ts = this._transformState;
12520 ts.writecb = cb;
12521 ts.writechunk = chunk;
12522 ts.writeencoding = encoding;
12523 if (!ts.transforming) {
12524 var rs = this._readableState;
12525 if (ts.needTransform ||
12526 rs.needReadable ||
12527 rs.length < rs.highWaterMark)
12528 this._read(rs.highWaterMark);
12529 }
12530};
12531
12532// Doesn't matter what the args are here.
12533// _transform does all the work.
12534// That we got here means that the readable side wants more data.
12535Transform.prototype._read = function(n) {
12536 var ts = this._transformState;
12537
12538 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
12539 ts.transforming = true;
12540 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12541 } else {
12542 // mark that we need a transform, so that any data that comes in
12543 // will get processed, now that we've asked for it.
12544 ts.needTransform = true;
12545 }
12546};
12547
12548
12549function done(stream, er) {
12550 if (er)
12551 return stream.emit('error', er);
12552
12553 // if there's nothing in the write buffer, then that means
12554 // that nothing more will ever be provided
12555 var ws = stream._writableState;
12556 var ts = stream._transformState;
12557
12558 if (ws.length)
12559 throw new Error('calling transform done when ws.length != 0');
12560
12561 if (ts.transforming)
12562 throw new Error('calling transform done when still transforming');
12563
12564 return stream.push(null);
12565}
12566
12567},{"14":14,"37":37,"75":75}],79:[function(_dereq_,module,exports){
12568(function (process){(function (){
12569// Copyright Joyent, Inc. and other Node contributors.
12570//
12571// Permission is hereby granted, free of charge, to any person obtaining a
12572// copy of this software and associated documentation files (the
12573// "Software"), to deal in the Software without restriction, including
12574// without limitation the rights to use, copy, modify, merge, publish,
12575// distribute, sublicense, and/or sell copies of the Software, and to permit
12576// persons to whom the Software is furnished to do so, subject to the
12577// following conditions:
12578//
12579// The above copyright notice and this permission notice shall be included
12580// in all copies or substantial portions of the Software.
12581//
12582// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12583// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12584// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12585// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12586// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12587// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12588// USE OR OTHER DEALINGS IN THE SOFTWARE.
12589
12590// A bit simpler than readable streams.
12591// Implement an async ._write(chunk, cb), and it'll handle all
12592// the drain event emission and buffering.
12593
12594module.exports = Writable;
12595
12596/*<replacement>*/
12597var Buffer = _dereq_(13).Buffer;
12598/*</replacement>*/
12599
12600Writable.WritableState = WritableState;
12601
12602
12603/*<replacement>*/
12604var util = _dereq_(14);
12605util.inherits = _dereq_(37);
12606/*</replacement>*/
12607
12608var Stream = _dereq_(85);
12609
12610util.inherits(Writable, Stream);
12611
12612function WriteReq(chunk, encoding, cb) {
12613 this.chunk = chunk;
12614 this.encoding = encoding;
12615 this.callback = cb;
12616}
12617
12618function WritableState(options, stream) {
12619 var Duplex = _dereq_(75);
12620
12621 options = options || {};
12622
12623 // the point at which write() starts returning false
12624 // Note: 0 is a valid value, means that we always return false if
12625 // the entire buffer is not flushed immediately on write()
12626 var hwm = options.highWaterMark;
12627 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
12628 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
12629
12630 // object stream flag to indicate whether or not this stream
12631 // contains buffers or objects.
12632 this.objectMode = !!options.objectMode;
12633
12634 if (stream instanceof Duplex)
12635 this.objectMode = this.objectMode || !!options.writableObjectMode;
12636
12637 // cast to ints.
12638 this.highWaterMark = ~~this.highWaterMark;
12639
12640 this.needDrain = false;
12641 // at the start of calling end()
12642 this.ending = false;
12643 // when end() has been called, and returned
12644 this.ended = false;
12645 // when 'finish' is emitted
12646 this.finished = false;
12647
12648 // should we decode strings into buffers before passing to _write?
12649 // this is here so that some node-core streams can optimize string
12650 // handling at a lower level.
12651 var noDecode = options.decodeStrings === false;
12652 this.decodeStrings = !noDecode;
12653
12654 // Crypto is kind of old and crusty. Historically, its default string
12655 // encoding is 'binary' so we have to make this configurable.
12656 // Everything else in the universe uses 'utf8', though.
12657 this.defaultEncoding = options.defaultEncoding || 'utf8';
12658
12659 // not an actual buffer we keep track of, but a measurement
12660 // of how much we're waiting to get pushed to some underlying
12661 // socket or file.
12662 this.length = 0;
12663
12664 // a flag to see when we're in the middle of a write.
12665 this.writing = false;
12666
12667 // when true all writes will be buffered until .uncork() call
12668 this.corked = 0;
12669
12670 // a flag to be able to tell if the onwrite cb is called immediately,
12671 // or on a later tick. We set this to true at first, because any
12672 // actions that shouldn't happen until "later" should generally also
12673 // not happen before the first write call.
12674 this.sync = true;
12675
12676 // a flag to know if we're processing previously buffered items, which
12677 // may call the _write() callback in the same tick, so that we don't
12678 // end up in an overlapped onwrite situation.
12679 this.bufferProcessing = false;
12680
12681 // the callback that's passed to _write(chunk,cb)
12682 this.onwrite = function(er) {
12683 onwrite(stream, er);
12684 };
12685
12686 // the callback that the user supplies to write(chunk,encoding,cb)
12687 this.writecb = null;
12688
12689 // the amount that is being written when _write is called.
12690 this.writelen = 0;
12691
12692 this.buffer = [];
12693
12694 // number of pending user-supplied write callbacks
12695 // this must be 0 before 'finish' can be emitted
12696 this.pendingcb = 0;
12697
12698 // emit prefinish if the only thing we're waiting for is _write cbs
12699 // This is relevant for synchronous Transform streams
12700 this.prefinished = false;
12701
12702 // True if the error was already emitted and should not be thrown again
12703 this.errorEmitted = false;
12704}
12705
12706function Writable(options) {
12707 var Duplex = _dereq_(75);
12708
12709 // Writable ctor is applied to Duplexes, though they're not
12710 // instanceof Writable, they're instanceof Readable.
12711 if (!(this instanceof Writable) && !(this instanceof Duplex))
12712 return new Writable(options);
12713
12714 this._writableState = new WritableState(options, this);
12715
12716 // legacy.
12717 this.writable = true;
12718
12719 Stream.call(this);
12720}
12721
12722// Otherwise people can pipe Writable streams, which is just wrong.
12723Writable.prototype.pipe = function() {
12724 this.emit('error', new Error('Cannot pipe. Not readable.'));
12725};
12726
12727
12728function writeAfterEnd(stream, state, cb) {
12729 var er = new Error('write after end');
12730 // TODO: defer error events consistently everywhere, not just the cb
12731 stream.emit('error', er);
12732 process.nextTick(function() {
12733 cb(er);
12734 });
12735}
12736
12737// If we get something that is not a buffer, string, null, or undefined,
12738// and we're not in objectMode, then that's an error.
12739// Otherwise stream chunks are all considered to be of length=1, and the
12740// watermarks determine how many objects to keep in the buffer, rather than
12741// how many bytes or characters.
12742function validChunk(stream, state, chunk, cb) {
12743 var valid = true;
12744 if (!util.isBuffer(chunk) &&
12745 !util.isString(chunk) &&
12746 !util.isNullOrUndefined(chunk) &&
12747 !state.objectMode) {
12748 var er = new TypeError('Invalid non-string/buffer chunk');
12749 stream.emit('error', er);
12750 process.nextTick(function() {
12751 cb(er);
12752 });
12753 valid = false;
12754 }
12755 return valid;
12756}
12757
12758Writable.prototype.write = function(chunk, encoding, cb) {
12759 var state = this._writableState;
12760 var ret = false;
12761
12762 if (util.isFunction(encoding)) {
12763 cb = encoding;
12764 encoding = null;
12765 }
12766
12767 if (util.isBuffer(chunk))
12768 encoding = 'buffer';
12769 else if (!encoding)
12770 encoding = state.defaultEncoding;
12771
12772 if (!util.isFunction(cb))
12773 cb = function() {};
12774
12775 if (state.ended)
12776 writeAfterEnd(this, state, cb);
12777 else if (validChunk(this, state, chunk, cb)) {
12778 state.pendingcb++;
12779 ret = writeOrBuffer(this, state, chunk, encoding, cb);
12780 }
12781
12782 return ret;
12783};
12784
12785Writable.prototype.cork = function() {
12786 var state = this._writableState;
12787
12788 state.corked++;
12789};
12790
12791Writable.prototype.uncork = function() {
12792 var state = this._writableState;
12793
12794 if (state.corked) {
12795 state.corked--;
12796
12797 if (!state.writing &&
12798 !state.corked &&
12799 !state.finished &&
12800 !state.bufferProcessing &&
12801 state.buffer.length)
12802 clearBuffer(this, state);
12803 }
12804};
12805
12806function decodeChunk(state, chunk, encoding) {
12807 if (!state.objectMode &&
12808 state.decodeStrings !== false &&
12809 util.isString(chunk)) {
12810 chunk = new Buffer(chunk, encoding);
12811 }
12812 return chunk;
12813}
12814
12815// if we're already writing something, then just put this
12816// in the queue, and wait our turn. Otherwise, call _write
12817// If we return false, then we need a drain event, so set that flag.
12818function writeOrBuffer(stream, state, chunk, encoding, cb) {
12819 chunk = decodeChunk(state, chunk, encoding);
12820 if (util.isBuffer(chunk))
12821 encoding = 'buffer';
12822 var len = state.objectMode ? 1 : chunk.length;
12823
12824 state.length += len;
12825
12826 var ret = state.length < state.highWaterMark;
12827 // we must ensure that previous needDrain will not be reset to false.
12828 if (!ret)
12829 state.needDrain = true;
12830
12831 if (state.writing || state.corked)
12832 state.buffer.push(new WriteReq(chunk, encoding, cb));
12833 else
12834 doWrite(stream, state, false, len, chunk, encoding, cb);
12835
12836 return ret;
12837}
12838
12839function doWrite(stream, state, writev, len, chunk, encoding, cb) {
12840 state.writelen = len;
12841 state.writecb = cb;
12842 state.writing = true;
12843 state.sync = true;
12844 if (writev)
12845 stream._writev(chunk, state.onwrite);
12846 else
12847 stream._write(chunk, encoding, state.onwrite);
12848 state.sync = false;
12849}
12850
12851function onwriteError(stream, state, sync, er, cb) {
12852 if (sync)
12853 process.nextTick(function() {
12854 state.pendingcb--;
12855 cb(er);
12856 });
12857 else {
12858 state.pendingcb--;
12859 cb(er);
12860 }
12861
12862 stream._writableState.errorEmitted = true;
12863 stream.emit('error', er);
12864}
12865
12866function onwriteStateUpdate(state) {
12867 state.writing = false;
12868 state.writecb = null;
12869 state.length -= state.writelen;
12870 state.writelen = 0;
12871}
12872
12873function onwrite(stream, er) {
12874 var state = stream._writableState;
12875 var sync = state.sync;
12876 var cb = state.writecb;
12877
12878 onwriteStateUpdate(state);
12879
12880 if (er)
12881 onwriteError(stream, state, sync, er, cb);
12882 else {
12883 // Check if we're actually ready to finish, but don't emit yet
12884 var finished = needFinish(stream, state);
12885
12886 if (!finished &&
12887 !state.corked &&
12888 !state.bufferProcessing &&
12889 state.buffer.length) {
12890 clearBuffer(stream, state);
12891 }
12892
12893 if (sync) {
12894 process.nextTick(function() {
12895 afterWrite(stream, state, finished, cb);
12896 });
12897 } else {
12898 afterWrite(stream, state, finished, cb);
12899 }
12900 }
12901}
12902
12903function afterWrite(stream, state, finished, cb) {
12904 if (!finished)
12905 onwriteDrain(stream, state);
12906 state.pendingcb--;
12907 cb();
12908 finishMaybe(stream, state);
12909}
12910
12911// Must force callback to be called on nextTick, so that we don't
12912// emit 'drain' before the write() consumer gets the 'false' return
12913// value, and has a chance to attach a 'drain' listener.
12914function onwriteDrain(stream, state) {
12915 if (state.length === 0 && state.needDrain) {
12916 state.needDrain = false;
12917 stream.emit('drain');
12918 }
12919}
12920
12921
12922// if there's something in the buffer waiting, then process it
12923function clearBuffer(stream, state) {
12924 state.bufferProcessing = true;
12925
12926 if (stream._writev && state.buffer.length > 1) {
12927 // Fast case, write everything using _writev()
12928 var cbs = [];
12929 for (var c = 0; c < state.buffer.length; c++)
12930 cbs.push(state.buffer[c].callback);
12931
12932 // count the one we are adding, as well.
12933 // TODO(isaacs) clean this up
12934 state.pendingcb++;
12935 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
12936 for (var i = 0; i < cbs.length; i++) {
12937 state.pendingcb--;
12938 cbs[i](err);
12939 }
12940 });
12941
12942 // Clear buffer
12943 state.buffer = [];
12944 } else {
12945 // Slow case, write chunks one-by-one
12946 for (var c = 0; c < state.buffer.length; c++) {
12947 var entry = state.buffer[c];
12948 var chunk = entry.chunk;
12949 var encoding = entry.encoding;
12950 var cb = entry.callback;
12951 var len = state.objectMode ? 1 : chunk.length;
12952
12953 doWrite(stream, state, false, len, chunk, encoding, cb);
12954
12955 // if we didn't call the onwrite immediately, then
12956 // it means that we need to wait until it does.
12957 // also, that means that the chunk and cb are currently
12958 // being processed, so move the buffer counter past them.
12959 if (state.writing) {
12960 c++;
12961 break;
12962 }
12963 }
12964
12965 if (c < state.buffer.length)
12966 state.buffer = state.buffer.slice(c);
12967 else
12968 state.buffer.length = 0;
12969 }
12970
12971 state.bufferProcessing = false;
12972}
12973
12974Writable.prototype._write = function(chunk, encoding, cb) {
12975 cb(new Error('not implemented'));
12976
12977};
12978
12979Writable.prototype._writev = null;
12980
12981Writable.prototype.end = function(chunk, encoding, cb) {
12982 var state = this._writableState;
12983
12984 if (util.isFunction(chunk)) {
12985 cb = chunk;
12986 chunk = null;
12987 encoding = null;
12988 } else if (util.isFunction(encoding)) {
12989 cb = encoding;
12990 encoding = null;
12991 }
12992
12993 if (!util.isNullOrUndefined(chunk))
12994 this.write(chunk, encoding);
12995
12996 // .end() fully uncorks
12997 if (state.corked) {
12998 state.corked = 1;
12999 this.uncork();
13000 }
13001
13002 // ignore unnecessary end() calls.
13003 if (!state.ending && !state.finished)
13004 endWritable(this, state, cb);
13005};
13006
13007
13008function needFinish(stream, state) {
13009 return (state.ending &&
13010 state.length === 0 &&
13011 !state.finished &&
13012 !state.writing);
13013}
13014
13015function prefinish(stream, state) {
13016 if (!state.prefinished) {
13017 state.prefinished = true;
13018 stream.emit('prefinish');
13019 }
13020}
13021
13022function finishMaybe(stream, state) {
13023 var need = needFinish(stream, state);
13024 if (need) {
13025 if (state.pendingcb === 0) {
13026 prefinish(stream, state);
13027 state.finished = true;
13028 stream.emit('finish');
13029 } else
13030 prefinish(stream, state);
13031 }
13032 return need;
13033}
13034
13035function endWritable(stream, state, cb) {
13036 state.ending = true;
13037 finishMaybe(stream, state);
13038 if (cb) {
13039 if (state.finished)
13040 process.nextTick(cb);
13041 else
13042 stream.once('finish', cb);
13043 }
13044 state.ended = true;
13045}
13046
13047}).call(this)}).call(this,_dereq_(73))
13048},{"13":13,"14":14,"37":37,"73":73,"75":75,"85":85}],80:[function(_dereq_,module,exports){
13049module.exports = Array.isArray || function (arr) {
13050 return Object.prototype.toString.call(arr) == '[object Array]';
13051};
13052
13053},{}],81:[function(_dereq_,module,exports){
13054// Copyright Joyent, Inc. and other Node contributors.
13055//
13056// Permission is hereby granted, free of charge, to any person obtaining a
13057// copy of this software and associated documentation files (the
13058// "Software"), to deal in the Software without restriction, including
13059// without limitation the rights to use, copy, modify, merge, publish,
13060// distribute, sublicense, and/or sell copies of the Software, and to permit
13061// persons to whom the Software is furnished to do so, subject to the
13062// following conditions:
13063//
13064// The above copyright notice and this permission notice shall be included
13065// in all copies or substantial portions of the Software.
13066//
13067// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13068// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13069// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13070// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13071// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13072// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13073// USE OR OTHER DEALINGS IN THE SOFTWARE.
13074
13075var Buffer = _dereq_(13).Buffer;
13076
13077var isBufferEncoding = Buffer.isEncoding
13078 || function(encoding) {
13079 switch (encoding && encoding.toLowerCase()) {
13080 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;
13081 default: return false;
13082 }
13083 }
13084
13085
13086function assertEncoding(encoding) {
13087 if (encoding && !isBufferEncoding(encoding)) {
13088 throw new Error('Unknown encoding: ' + encoding);
13089 }
13090}
13091
13092// StringDecoder provides an interface for efficiently splitting a series of
13093// buffers into a series of JS strings without breaking apart multi-byte
13094// characters. CESU-8 is handled as part of the UTF-8 encoding.
13095//
13096// @TODO Handling all encodings inside a single object makes it very difficult
13097// to reason about this code, so it should be split up in the future.
13098// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
13099// points as used by CESU-8.
13100var StringDecoder = exports.StringDecoder = function(encoding) {
13101 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
13102 assertEncoding(encoding);
13103 switch (this.encoding) {
13104 case 'utf8':
13105 // CESU-8 represents each of Surrogate Pair by 3-bytes
13106 this.surrogateSize = 3;
13107 break;
13108 case 'ucs2':
13109 case 'utf16le':
13110 // UTF-16 represents each of Surrogate Pair by 2-bytes
13111 this.surrogateSize = 2;
13112 this.detectIncompleteChar = utf16DetectIncompleteChar;
13113 break;
13114 case 'base64':
13115 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
13116 this.surrogateSize = 3;
13117 this.detectIncompleteChar = base64DetectIncompleteChar;
13118 break;
13119 default:
13120 this.write = passThroughWrite;
13121 return;
13122 }
13123
13124 // Enough space to store all bytes of a single character. UTF-8 needs 4
13125 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
13126 this.charBuffer = new Buffer(6);
13127 // Number of bytes received for the current incomplete multi-byte character.
13128 this.charReceived = 0;
13129 // Number of bytes expected for the current incomplete multi-byte character.
13130 this.charLength = 0;
13131};
13132
13133
13134// write decodes the given buffer and returns it as JS string that is
13135// guaranteed to not contain any partial multi-byte characters. Any partial
13136// character found at the end of the buffer is buffered up, and will be
13137// returned when calling write again with the remaining bytes.
13138//
13139// Note: Converting a Buffer containing an orphan surrogate to a String
13140// currently works, but converting a String to a Buffer (via `new Buffer`, or
13141// Buffer#write) will replace incomplete surrogates with the unicode
13142// replacement character. See https://codereview.chromium.org/121173009/ .
13143StringDecoder.prototype.write = function(buffer) {
13144 var charStr = '';
13145 // if our last write ended with an incomplete multibyte character
13146 while (this.charLength) {
13147 // determine how many remaining bytes this buffer has to offer for this char
13148 var available = (buffer.length >= this.charLength - this.charReceived) ?
13149 this.charLength - this.charReceived :
13150 buffer.length;
13151
13152 // add the new bytes to the char buffer
13153 buffer.copy(this.charBuffer, this.charReceived, 0, available);
13154 this.charReceived += available;
13155
13156 if (this.charReceived < this.charLength) {
13157 // still not enough chars in this buffer? wait for more ...
13158 return '';
13159 }
13160
13161 // remove bytes belonging to the current character from the buffer
13162 buffer = buffer.slice(available, buffer.length);
13163
13164 // get the character that was split
13165 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
13166
13167 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13168 var charCode = charStr.charCodeAt(charStr.length - 1);
13169 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13170 this.charLength += this.surrogateSize;
13171 charStr = '';
13172 continue;
13173 }
13174 this.charReceived = this.charLength = 0;
13175
13176 // if there are no more bytes in this buffer, just emit our char
13177 if (buffer.length === 0) {
13178 return charStr;
13179 }
13180 break;
13181 }
13182
13183 // determine and set charLength / charReceived
13184 this.detectIncompleteChar(buffer);
13185
13186 var end = buffer.length;
13187 if (this.charLength) {
13188 // buffer the incomplete character bytes we got
13189 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
13190 end -= this.charReceived;
13191 }
13192
13193 charStr += buffer.toString(this.encoding, 0, end);
13194
13195 var end = charStr.length - 1;
13196 var charCode = charStr.charCodeAt(end);
13197 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13198 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13199 var size = this.surrogateSize;
13200 this.charLength += size;
13201 this.charReceived += size;
13202 this.charBuffer.copy(this.charBuffer, size, 0, size);
13203 buffer.copy(this.charBuffer, 0, 0, size);
13204 return charStr.substring(0, end);
13205 }
13206
13207 // or just emit the charStr
13208 return charStr;
13209};
13210
13211// detectIncompleteChar determines if there is an incomplete UTF-8 character at
13212// the end of the given buffer. If so, it sets this.charLength to the byte
13213// length that character, and sets this.charReceived to the number of bytes
13214// that are available for this character.
13215StringDecoder.prototype.detectIncompleteChar = function(buffer) {
13216 // determine how many bytes we have to check at the end of this buffer
13217 var i = (buffer.length >= 3) ? 3 : buffer.length;
13218
13219 // Figure out if one of the last i bytes of our buffer announces an
13220 // incomplete char.
13221 for (; i > 0; i--) {
13222 var c = buffer[buffer.length - i];
13223
13224 // See http://en.wikipedia.org/wiki/UTF-8#Description
13225
13226 // 110XXXXX
13227 if (i == 1 && c >> 5 == 0x06) {
13228 this.charLength = 2;
13229 break;
13230 }
13231
13232 // 1110XXXX
13233 if (i <= 2 && c >> 4 == 0x0E) {
13234 this.charLength = 3;
13235 break;
13236 }
13237
13238 // 11110XXX
13239 if (i <= 3 && c >> 3 == 0x1E) {
13240 this.charLength = 4;
13241 break;
13242 }
13243 }
13244 this.charReceived = i;
13245};
13246
13247StringDecoder.prototype.end = function(buffer) {
13248 var res = '';
13249 if (buffer && buffer.length)
13250 res = this.write(buffer);
13251
13252 if (this.charReceived) {
13253 var cr = this.charReceived;
13254 var buf = this.charBuffer;
13255 var enc = this.encoding;
13256 res += buf.slice(0, cr).toString(enc);
13257 }
13258
13259 return res;
13260};
13261
13262function passThroughWrite(buffer) {
13263 return buffer.toString(this.encoding);
13264}
13265
13266function utf16DetectIncompleteChar(buffer) {
13267 this.charReceived = buffer.length % 2;
13268 this.charLength = this.charReceived ? 2 : 0;
13269}
13270
13271function base64DetectIncompleteChar(buffer) {
13272 this.charReceived = buffer.length % 3;
13273 this.charLength = this.charReceived ? 3 : 0;
13274}
13275
13276},{"13":13}],82:[function(_dereq_,module,exports){
13277(function (process){(function (){
13278exports = module.exports = _dereq_(77);
13279exports.Stream = _dereq_(85);
13280exports.Readable = exports;
13281exports.Writable = _dereq_(79);
13282exports.Duplex = _dereq_(75);
13283exports.Transform = _dereq_(78);
13284exports.PassThrough = _dereq_(76);
13285if (!process.browser && process.env.READABLE_STREAM === 'disable') {
13286 module.exports = _dereq_(85);
13287}
13288
13289}).call(this)}).call(this,_dereq_(73))
13290},{"73":73,"75":75,"76":76,"77":77,"78":78,"79":79,"85":85}],83:[function(_dereq_,module,exports){
13291/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
13292/* eslint-disable node/no-deprecated-api */
13293var buffer = _dereq_(13)
13294var Buffer = buffer.Buffer
13295
13296// alternative to using Object.keys for old browsers
13297function copyProps (src, dst) {
13298 for (var key in src) {
13299 dst[key] = src[key]
13300 }
13301}
13302if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13303 module.exports = buffer
13304} else {
13305 // Copy properties from require('buffer')
13306 copyProps(buffer, exports)
13307 exports.Buffer = SafeBuffer
13308}
13309
13310function SafeBuffer (arg, encodingOrOffset, length) {
13311 return Buffer(arg, encodingOrOffset, length)
13312}
13313
13314SafeBuffer.prototype = Object.create(Buffer.prototype)
13315
13316// Copy static methods from Buffer
13317copyProps(Buffer, SafeBuffer)
13318
13319SafeBuffer.from = function (arg, encodingOrOffset, length) {
13320 if (typeof arg === 'number') {
13321 throw new TypeError('Argument must not be a number')
13322 }
13323 return Buffer(arg, encodingOrOffset, length)
13324}
13325
13326SafeBuffer.alloc = function (size, fill, encoding) {
13327 if (typeof size !== 'number') {
13328 throw new TypeError('Argument must be a number')
13329 }
13330 var buf = Buffer(size)
13331 if (fill !== undefined) {
13332 if (typeof encoding === 'string') {
13333 buf.fill(fill, encoding)
13334 } else {
13335 buf.fill(fill)
13336 }
13337 } else {
13338 buf.fill(0)
13339 }
13340 return buf
13341}
13342
13343SafeBuffer.allocUnsafe = function (size) {
13344 if (typeof size !== 'number') {
13345 throw new TypeError('Argument must be a number')
13346 }
13347 return Buffer(size)
13348}
13349
13350SafeBuffer.allocUnsafeSlow = function (size) {
13351 if (typeof size !== 'number') {
13352 throw new TypeError('Argument must be a number')
13353 }
13354 return buffer.SlowBuffer(size)
13355}
13356
13357},{"13":13}],84:[function(_dereq_,module,exports){
13358(function (factory) {
13359 if (typeof exports === 'object') {
13360 // Node/CommonJS
13361 module.exports = factory();
13362 } else if (typeof define === 'function' && define.amd) {
13363 // AMD
13364 define(factory);
13365 } else {
13366 // Browser globals (with support for web workers)
13367 var glob;
13368
13369 try {
13370 glob = window;
13371 } catch (e) {
13372 glob = self;
13373 }
13374
13375 glob.SparkMD5 = factory();
13376 }
13377}(function (undefined) {
13378
13379 'use strict';
13380
13381 /*
13382 * Fastest md5 implementation around (JKM md5).
13383 * Credits: Joseph Myers
13384 *
13385 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
13386 * @see http://jsperf.com/md5-shootout/7
13387 */
13388
13389 /* this function is much faster,
13390 so if possible we use it. Some IEs
13391 are the only ones I know of that
13392 need the idiotic second function,
13393 generated by an if clause. */
13394 var add32 = function (a, b) {
13395 return (a + b) & 0xFFFFFFFF;
13396 },
13397 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
13398
13399
13400 function cmn(q, a, b, x, s, t) {
13401 a = add32(add32(a, q), add32(x, t));
13402 return add32((a << s) | (a >>> (32 - s)), b);
13403 }
13404
13405 function md5cycle(x, k) {
13406 var a = x[0],
13407 b = x[1],
13408 c = x[2],
13409 d = x[3];
13410
13411 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
13412 a = (a << 7 | a >>> 25) + b | 0;
13413 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
13414 d = (d << 12 | d >>> 20) + a | 0;
13415 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
13416 c = (c << 17 | c >>> 15) + d | 0;
13417 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
13418 b = (b << 22 | b >>> 10) + c | 0;
13419 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
13420 a = (a << 7 | a >>> 25) + b | 0;
13421 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
13422 d = (d << 12 | d >>> 20) + a | 0;
13423 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
13424 c = (c << 17 | c >>> 15) + d | 0;
13425 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
13426 b = (b << 22 | b >>> 10) + c | 0;
13427 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
13428 a = (a << 7 | a >>> 25) + b | 0;
13429 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
13430 d = (d << 12 | d >>> 20) + a | 0;
13431 c += (d & a | ~d & b) + k[10] - 42063 | 0;
13432 c = (c << 17 | c >>> 15) + d | 0;
13433 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
13434 b = (b << 22 | b >>> 10) + c | 0;
13435 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
13436 a = (a << 7 | a >>> 25) + b | 0;
13437 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
13438 d = (d << 12 | d >>> 20) + a | 0;
13439 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
13440 c = (c << 17 | c >>> 15) + d | 0;
13441 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
13442 b = (b << 22 | b >>> 10) + c | 0;
13443
13444 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
13445 a = (a << 5 | a >>> 27) + b | 0;
13446 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
13447 d = (d << 9 | d >>> 23) + a | 0;
13448 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
13449 c = (c << 14 | c >>> 18) + d | 0;
13450 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
13451 b = (b << 20 | b >>> 12) + c | 0;
13452 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
13453 a = (a << 5 | a >>> 27) + b | 0;
13454 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
13455 d = (d << 9 | d >>> 23) + a | 0;
13456 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
13457 c = (c << 14 | c >>> 18) + d | 0;
13458 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
13459 b = (b << 20 | b >>> 12) + c | 0;
13460 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
13461 a = (a << 5 | a >>> 27) + b | 0;
13462 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
13463 d = (d << 9 | d >>> 23) + a | 0;
13464 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
13465 c = (c << 14 | c >>> 18) + d | 0;
13466 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
13467 b = (b << 20 | b >>> 12) + c | 0;
13468 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
13469 a = (a << 5 | a >>> 27) + b | 0;
13470 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
13471 d = (d << 9 | d >>> 23) + a | 0;
13472 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
13473 c = (c << 14 | c >>> 18) + d | 0;
13474 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
13475 b = (b << 20 | b >>> 12) + c | 0;
13476
13477 a += (b ^ c ^ d) + k[5] - 378558 | 0;
13478 a = (a << 4 | a >>> 28) + b | 0;
13479 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
13480 d = (d << 11 | d >>> 21) + a | 0;
13481 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
13482 c = (c << 16 | c >>> 16) + d | 0;
13483 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
13484 b = (b << 23 | b >>> 9) + c | 0;
13485 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
13486 a = (a << 4 | a >>> 28) + b | 0;
13487 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
13488 d = (d << 11 | d >>> 21) + a | 0;
13489 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
13490 c = (c << 16 | c >>> 16) + d | 0;
13491 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
13492 b = (b << 23 | b >>> 9) + c | 0;
13493 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
13494 a = (a << 4 | a >>> 28) + b | 0;
13495 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
13496 d = (d << 11 | d >>> 21) + a | 0;
13497 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
13498 c = (c << 16 | c >>> 16) + d | 0;
13499 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
13500 b = (b << 23 | b >>> 9) + c | 0;
13501 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
13502 a = (a << 4 | a >>> 28) + b | 0;
13503 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
13504 d = (d << 11 | d >>> 21) + a | 0;
13505 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
13506 c = (c << 16 | c >>> 16) + d | 0;
13507 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
13508 b = (b << 23 | b >>> 9) + c | 0;
13509
13510 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
13511 a = (a << 6 | a >>> 26) + b | 0;
13512 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
13513 d = (d << 10 | d >>> 22) + a | 0;
13514 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
13515 c = (c << 15 | c >>> 17) + d | 0;
13516 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
13517 b = (b << 21 |b >>> 11) + c | 0;
13518 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
13519 a = (a << 6 | a >>> 26) + b | 0;
13520 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
13521 d = (d << 10 | d >>> 22) + a | 0;
13522 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
13523 c = (c << 15 | c >>> 17) + d | 0;
13524 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
13525 b = (b << 21 |b >>> 11) + c | 0;
13526 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
13527 a = (a << 6 | a >>> 26) + b | 0;
13528 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
13529 d = (d << 10 | d >>> 22) + a | 0;
13530 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
13531 c = (c << 15 | c >>> 17) + d | 0;
13532 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
13533 b = (b << 21 |b >>> 11) + c | 0;
13534 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
13535 a = (a << 6 | a >>> 26) + b | 0;
13536 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
13537 d = (d << 10 | d >>> 22) + a | 0;
13538 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
13539 c = (c << 15 | c >>> 17) + d | 0;
13540 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
13541 b = (b << 21 | b >>> 11) + c | 0;
13542
13543 x[0] = a + x[0] | 0;
13544 x[1] = b + x[1] | 0;
13545 x[2] = c + x[2] | 0;
13546 x[3] = d + x[3] | 0;
13547 }
13548
13549 function md5blk(s) {
13550 var md5blks = [],
13551 i; /* Andy King said do it this way. */
13552
13553 for (i = 0; i < 64; i += 4) {
13554 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
13555 }
13556 return md5blks;
13557 }
13558
13559 function md5blk_array(a) {
13560 var md5blks = [],
13561 i; /* Andy King said do it this way. */
13562
13563 for (i = 0; i < 64; i += 4) {
13564 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13565 }
13566 return md5blks;
13567 }
13568
13569 function md51(s) {
13570 var n = s.length,
13571 state = [1732584193, -271733879, -1732584194, 271733878],
13572 i,
13573 length,
13574 tail,
13575 tmp,
13576 lo,
13577 hi;
13578
13579 for (i = 64; i <= n; i += 64) {
13580 md5cycle(state, md5blk(s.substring(i - 64, i)));
13581 }
13582 s = s.substring(i - 64);
13583 length = s.length;
13584 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13585 for (i = 0; i < length; i += 1) {
13586 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13587 }
13588 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13589 if (i > 55) {
13590 md5cycle(state, tail);
13591 for (i = 0; i < 16; i += 1) {
13592 tail[i] = 0;
13593 }
13594 }
13595
13596 // Beware that the final length might not fit in 32 bits so we take care of that
13597 tmp = n * 8;
13598 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13599 lo = parseInt(tmp[2], 16);
13600 hi = parseInt(tmp[1], 16) || 0;
13601
13602 tail[14] = lo;
13603 tail[15] = hi;
13604
13605 md5cycle(state, tail);
13606 return state;
13607 }
13608
13609 function md51_array(a) {
13610 var n = a.length,
13611 state = [1732584193, -271733879, -1732584194, 271733878],
13612 i,
13613 length,
13614 tail,
13615 tmp,
13616 lo,
13617 hi;
13618
13619 for (i = 64; i <= n; i += 64) {
13620 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13621 }
13622
13623 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13624 // containing the last element of the parent array if the sub array specified starts
13625 // beyond the length of the parent array - weird.
13626 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13627 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13628
13629 length = a.length;
13630 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13631 for (i = 0; i < length; i += 1) {
13632 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13633 }
13634
13635 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13636 if (i > 55) {
13637 md5cycle(state, tail);
13638 for (i = 0; i < 16; i += 1) {
13639 tail[i] = 0;
13640 }
13641 }
13642
13643 // Beware that the final length might not fit in 32 bits so we take care of that
13644 tmp = n * 8;
13645 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13646 lo = parseInt(tmp[2], 16);
13647 hi = parseInt(tmp[1], 16) || 0;
13648
13649 tail[14] = lo;
13650 tail[15] = hi;
13651
13652 md5cycle(state, tail);
13653
13654 return state;
13655 }
13656
13657 function rhex(n) {
13658 var s = '',
13659 j;
13660 for (j = 0; j < 4; j += 1) {
13661 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
13662 }
13663 return s;
13664 }
13665
13666 function hex(x) {
13667 var i;
13668 for (i = 0; i < x.length; i += 1) {
13669 x[i] = rhex(x[i]);
13670 }
13671 return x.join('');
13672 }
13673
13674 // In some cases the fast add32 function cannot be used..
13675 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
13676 add32 = function (x, y) {
13677 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
13678 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
13679 return (msw << 16) | (lsw & 0xFFFF);
13680 };
13681 }
13682
13683 // ---------------------------------------------------
13684
13685 /**
13686 * ArrayBuffer slice polyfill.
13687 *
13688 * @see https://github.com/ttaubert/node-arraybuffer-slice
13689 */
13690
13691 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
13692 (function () {
13693 function clamp(val, length) {
13694 val = (val | 0) || 0;
13695
13696 if (val < 0) {
13697 return Math.max(val + length, 0);
13698 }
13699
13700 return Math.min(val, length);
13701 }
13702
13703 ArrayBuffer.prototype.slice = function (from, to) {
13704 var length = this.byteLength,
13705 begin = clamp(from, length),
13706 end = length,
13707 num,
13708 target,
13709 targetArray,
13710 sourceArray;
13711
13712 if (to !== undefined) {
13713 end = clamp(to, length);
13714 }
13715
13716 if (begin > end) {
13717 return new ArrayBuffer(0);
13718 }
13719
13720 num = end - begin;
13721 target = new ArrayBuffer(num);
13722 targetArray = new Uint8Array(target);
13723
13724 sourceArray = new Uint8Array(this, begin, num);
13725 targetArray.set(sourceArray);
13726
13727 return target;
13728 };
13729 })();
13730 }
13731
13732 // ---------------------------------------------------
13733
13734 /**
13735 * Helpers.
13736 */
13737
13738 function toUtf8(str) {
13739 if (/[\u0080-\uFFFF]/.test(str)) {
13740 str = unescape(encodeURIComponent(str));
13741 }
13742
13743 return str;
13744 }
13745
13746 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
13747 var length = str.length,
13748 buff = new ArrayBuffer(length),
13749 arr = new Uint8Array(buff),
13750 i;
13751
13752 for (i = 0; i < length; i += 1) {
13753 arr[i] = str.charCodeAt(i);
13754 }
13755
13756 return returnUInt8Array ? arr : buff;
13757 }
13758
13759 function arrayBuffer2Utf8Str(buff) {
13760 return String.fromCharCode.apply(null, new Uint8Array(buff));
13761 }
13762
13763 function concatenateArrayBuffers(first, second, returnUInt8Array) {
13764 var result = new Uint8Array(first.byteLength + second.byteLength);
13765
13766 result.set(new Uint8Array(first));
13767 result.set(new Uint8Array(second), first.byteLength);
13768
13769 return returnUInt8Array ? result : result.buffer;
13770 }
13771
13772 function hexToBinaryString(hex) {
13773 var bytes = [],
13774 length = hex.length,
13775 x;
13776
13777 for (x = 0; x < length - 1; x += 2) {
13778 bytes.push(parseInt(hex.substr(x, 2), 16));
13779 }
13780
13781 return String.fromCharCode.apply(String, bytes);
13782 }
13783
13784 // ---------------------------------------------------
13785
13786 /**
13787 * SparkMD5 OOP implementation.
13788 *
13789 * Use this class to perform an incremental md5, otherwise use the
13790 * static methods instead.
13791 */
13792
13793 function SparkMD5() {
13794 // call reset to init the instance
13795 this.reset();
13796 }
13797
13798 /**
13799 * Appends a string.
13800 * A conversion will be applied if an utf8 string is detected.
13801 *
13802 * @param {String} str The string to be appended
13803 *
13804 * @return {SparkMD5} The instance itself
13805 */
13806 SparkMD5.prototype.append = function (str) {
13807 // Converts the string to utf8 bytes if necessary
13808 // Then append as binary
13809 this.appendBinary(toUtf8(str));
13810
13811 return this;
13812 };
13813
13814 /**
13815 * Appends a binary string.
13816 *
13817 * @param {String} contents The binary string to be appended
13818 *
13819 * @return {SparkMD5} The instance itself
13820 */
13821 SparkMD5.prototype.appendBinary = function (contents) {
13822 this._buff += contents;
13823 this._length += contents.length;
13824
13825 var length = this._buff.length,
13826 i;
13827
13828 for (i = 64; i <= length; i += 64) {
13829 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
13830 }
13831
13832 this._buff = this._buff.substring(i - 64);
13833
13834 return this;
13835 };
13836
13837 /**
13838 * Finishes the incremental computation, reseting the internal state and
13839 * returning the result.
13840 *
13841 * @param {Boolean} raw True to get the raw string, false to get the hex string
13842 *
13843 * @return {String} The result
13844 */
13845 SparkMD5.prototype.end = function (raw) {
13846 var buff = this._buff,
13847 length = buff.length,
13848 i,
13849 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
13850 ret;
13851
13852 for (i = 0; i < length; i += 1) {
13853 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
13854 }
13855
13856 this._finish(tail, length);
13857 ret = hex(this._hash);
13858
13859 if (raw) {
13860 ret = hexToBinaryString(ret);
13861 }
13862
13863 this.reset();
13864
13865 return ret;
13866 };
13867
13868 /**
13869 * Resets the internal state of the computation.
13870 *
13871 * @return {SparkMD5} The instance itself
13872 */
13873 SparkMD5.prototype.reset = function () {
13874 this._buff = '';
13875 this._length = 0;
13876 this._hash = [1732584193, -271733879, -1732584194, 271733878];
13877
13878 return this;
13879 };
13880
13881 /**
13882 * Gets the internal state of the computation.
13883 *
13884 * @return {Object} The state
13885 */
13886 SparkMD5.prototype.getState = function () {
13887 return {
13888 buff: this._buff,
13889 length: this._length,
13890 hash: this._hash.slice()
13891 };
13892 };
13893
13894 /**
13895 * Gets the internal state of the computation.
13896 *
13897 * @param {Object} state The state
13898 *
13899 * @return {SparkMD5} The instance itself
13900 */
13901 SparkMD5.prototype.setState = function (state) {
13902 this._buff = state.buff;
13903 this._length = state.length;
13904 this._hash = state.hash;
13905
13906 return this;
13907 };
13908
13909 /**
13910 * Releases memory used by the incremental buffer and other additional
13911 * resources. If you plan to use the instance again, use reset instead.
13912 */
13913 SparkMD5.prototype.destroy = function () {
13914 delete this._hash;
13915 delete this._buff;
13916 delete this._length;
13917 };
13918
13919 /**
13920 * Finish the final calculation based on the tail.
13921 *
13922 * @param {Array} tail The tail (will be modified)
13923 * @param {Number} length The length of the remaining buffer
13924 */
13925 SparkMD5.prototype._finish = function (tail, length) {
13926 var i = length,
13927 tmp,
13928 lo,
13929 hi;
13930
13931 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13932 if (i > 55) {
13933 md5cycle(this._hash, tail);
13934 for (i = 0; i < 16; i += 1) {
13935 tail[i] = 0;
13936 }
13937 }
13938
13939 // Do the final computation based on the tail and length
13940 // Beware that the final length may not fit in 32 bits so we take care of that
13941 tmp = this._length * 8;
13942 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13943 lo = parseInt(tmp[2], 16);
13944 hi = parseInt(tmp[1], 16) || 0;
13945
13946 tail[14] = lo;
13947 tail[15] = hi;
13948 md5cycle(this._hash, tail);
13949 };
13950
13951 /**
13952 * Performs the md5 hash on a string.
13953 * A conversion will be applied if utf8 string is detected.
13954 *
13955 * @param {String} str The string
13956 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
13957 *
13958 * @return {String} The result
13959 */
13960 SparkMD5.hash = function (str, raw) {
13961 // Converts the string to utf8 bytes if necessary
13962 // Then compute it using the binary function
13963 return SparkMD5.hashBinary(toUtf8(str), raw);
13964 };
13965
13966 /**
13967 * Performs the md5 hash on a binary string.
13968 *
13969 * @param {String} content The binary string
13970 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
13971 *
13972 * @return {String} The result
13973 */
13974 SparkMD5.hashBinary = function (content, raw) {
13975 var hash = md51(content),
13976 ret = hex(hash);
13977
13978 return raw ? hexToBinaryString(ret) : ret;
13979 };
13980
13981 // ---------------------------------------------------
13982
13983 /**
13984 * SparkMD5 OOP implementation for array buffers.
13985 *
13986 * Use this class to perform an incremental md5 ONLY for array buffers.
13987 */
13988 SparkMD5.ArrayBuffer = function () {
13989 // call reset to init the instance
13990 this.reset();
13991 };
13992
13993 /**
13994 * Appends an array buffer.
13995 *
13996 * @param {ArrayBuffer} arr The array to be appended
13997 *
13998 * @return {SparkMD5.ArrayBuffer} The instance itself
13999 */
14000 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
14001 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
14002 length = buff.length,
14003 i;
14004
14005 this._length += arr.byteLength;
14006
14007 for (i = 64; i <= length; i += 64) {
14008 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
14009 }
14010
14011 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
14012
14013 return this;
14014 };
14015
14016 /**
14017 * Finishes the incremental computation, reseting the internal state and
14018 * returning the result.
14019 *
14020 * @param {Boolean} raw True to get the raw string, false to get the hex string
14021 *
14022 * @return {String} The result
14023 */
14024 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
14025 var buff = this._buff,
14026 length = buff.length,
14027 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14028 i,
14029 ret;
14030
14031 for (i = 0; i < length; i += 1) {
14032 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
14033 }
14034
14035 this._finish(tail, length);
14036 ret = hex(this._hash);
14037
14038 if (raw) {
14039 ret = hexToBinaryString(ret);
14040 }
14041
14042 this.reset();
14043
14044 return ret;
14045 };
14046
14047 /**
14048 * Resets the internal state of the computation.
14049 *
14050 * @return {SparkMD5.ArrayBuffer} The instance itself
14051 */
14052 SparkMD5.ArrayBuffer.prototype.reset = function () {
14053 this._buff = new Uint8Array(0);
14054 this._length = 0;
14055 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14056
14057 return this;
14058 };
14059
14060 /**
14061 * Gets the internal state of the computation.
14062 *
14063 * @return {Object} The state
14064 */
14065 SparkMD5.ArrayBuffer.prototype.getState = function () {
14066 var state = SparkMD5.prototype.getState.call(this);
14067
14068 // Convert buffer to a string
14069 state.buff = arrayBuffer2Utf8Str(state.buff);
14070
14071 return state;
14072 };
14073
14074 /**
14075 * Gets the internal state of the computation.
14076 *
14077 * @param {Object} state The state
14078 *
14079 * @return {SparkMD5.ArrayBuffer} The instance itself
14080 */
14081 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
14082 // Convert string to buffer
14083 state.buff = utf8Str2ArrayBuffer(state.buff, true);
14084
14085 return SparkMD5.prototype.setState.call(this, state);
14086 };
14087
14088 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
14089
14090 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
14091
14092 /**
14093 * Performs the md5 hash on an array buffer.
14094 *
14095 * @param {ArrayBuffer} arr The array buffer
14096 * @param {Boolean} [raw] True to get the raw string, false to get the hex one
14097 *
14098 * @return {String} The result
14099 */
14100 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
14101 var hash = md51_array(new Uint8Array(arr)),
14102 ret = hex(hash);
14103
14104 return raw ? hexToBinaryString(ret) : ret;
14105 };
14106
14107 return SparkMD5;
14108}));
14109
14110},{}],85:[function(_dereq_,module,exports){
14111// Copyright Joyent, Inc. and other Node contributors.
14112//
14113// Permission is hereby granted, free of charge, to any person obtaining a
14114// copy of this software and associated documentation files (the
14115// "Software"), to deal in the Software without restriction, including
14116// without limitation the rights to use, copy, modify, merge, publish,
14117// distribute, sublicense, and/or sell copies of the Software, and to permit
14118// persons to whom the Software is furnished to do so, subject to the
14119// following conditions:
14120//
14121// The above copyright notice and this permission notice shall be included
14122// in all copies or substantial portions of the Software.
14123//
14124// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14125// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14126// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14127// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14128// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14129// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14130// USE OR OTHER DEALINGS IN THE SOFTWARE.
14131
14132module.exports = Stream;
14133
14134var EE = _dereq_(26).EventEmitter;
14135var inherits = _dereq_(37);
14136
14137inherits(Stream, EE);
14138Stream.Readable = _dereq_(97);
14139Stream.Writable = _dereq_(99);
14140Stream.Duplex = _dereq_(87);
14141Stream.Transform = _dereq_(98);
14142Stream.PassThrough = _dereq_(96);
14143
14144// Backwards-compat with node 0.4.x
14145Stream.Stream = Stream;
14146
14147
14148
14149// old-style streams. Note that the pipe method (the only relevant
14150// part of this class) is overridden in the Readable class.
14151
14152function Stream() {
14153 EE.call(this);
14154}
14155
14156Stream.prototype.pipe = function(dest, options) {
14157 var source = this;
14158
14159 function ondata(chunk) {
14160 if (dest.writable) {
14161 if (false === dest.write(chunk) && source.pause) {
14162 source.pause();
14163 }
14164 }
14165 }
14166
14167 source.on('data', ondata);
14168
14169 function ondrain() {
14170 if (source.readable && source.resume) {
14171 source.resume();
14172 }
14173 }
14174
14175 dest.on('drain', ondrain);
14176
14177 // If the 'end' option is not supplied, dest.end() will be called when
14178 // source gets the 'end' or 'close' events. Only dest.end() once.
14179 if (!dest._isStdio && (!options || options.end !== false)) {
14180 source.on('end', onend);
14181 source.on('close', onclose);
14182 }
14183
14184 var didOnEnd = false;
14185 function onend() {
14186 if (didOnEnd) return;
14187 didOnEnd = true;
14188
14189 dest.end();
14190 }
14191
14192
14193 function onclose() {
14194 if (didOnEnd) return;
14195 didOnEnd = true;
14196
14197 if (typeof dest.destroy === 'function') dest.destroy();
14198 }
14199
14200 // don't leave dangling pipes when there are errors.
14201 function onerror(er) {
14202 cleanup();
14203 if (EE.listenerCount(this, 'error') === 0) {
14204 throw er; // Unhandled stream error in pipe.
14205 }
14206 }
14207
14208 source.on('error', onerror);
14209 dest.on('error', onerror);
14210
14211 // remove all the event listeners that were added.
14212 function cleanup() {
14213 source.removeListener('data', ondata);
14214 dest.removeListener('drain', ondrain);
14215
14216 source.removeListener('end', onend);
14217 source.removeListener('close', onclose);
14218
14219 source.removeListener('error', onerror);
14220 dest.removeListener('error', onerror);
14221
14222 source.removeListener('end', cleanup);
14223 source.removeListener('close', cleanup);
14224
14225 dest.removeListener('close', cleanup);
14226 }
14227
14228 source.on('end', cleanup);
14229 source.on('close', cleanup);
14230
14231 dest.on('close', cleanup);
14232
14233 dest.emit('pipe', source);
14234
14235 // Allow for unix-like usage: A.pipe(B).pipe(C)
14236 return dest;
14237};
14238
14239},{"26":26,"37":37,"87":87,"96":96,"97":97,"98":98,"99":99}],86:[function(_dereq_,module,exports){
14240var toString = {}.toString;
14241
14242module.exports = Array.isArray || function (arr) {
14243 return toString.call(arr) == '[object Array]';
14244};
14245
14246},{}],87:[function(_dereq_,module,exports){
14247module.exports = _dereq_(88);
14248
14249},{"88":88}],88:[function(_dereq_,module,exports){
14250// Copyright Joyent, Inc. and other Node contributors.
14251//
14252// Permission is hereby granted, free of charge, to any person obtaining a
14253// copy of this software and associated documentation files (the
14254// "Software"), to deal in the Software without restriction, including
14255// without limitation the rights to use, copy, modify, merge, publish,
14256// distribute, sublicense, and/or sell copies of the Software, and to permit
14257// persons to whom the Software is furnished to do so, subject to the
14258// following conditions:
14259//
14260// The above copyright notice and this permission notice shall be included
14261// in all copies or substantial portions of the Software.
14262//
14263// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14264// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14265// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14266// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14267// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14268// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14269// USE OR OTHER DEALINGS IN THE SOFTWARE.
14270
14271// a duplex stream is just a stream that is both readable and writable.
14272// Since JS doesn't have multiple prototypal inheritance, this class
14273// prototypally inherits from Readable, and then parasitically from
14274// Writable.
14275
14276'use strict';
14277
14278/*<replacement>*/
14279
14280var pna = _dereq_(72);
14281/*</replacement>*/
14282
14283/*<replacement>*/
14284var objectKeys = Object.keys || function (obj) {
14285 var keys = [];
14286 for (var key in obj) {
14287 keys.push(key);
14288 }return keys;
14289};
14290/*</replacement>*/
14291
14292module.exports = Duplex;
14293
14294/*<replacement>*/
14295var util = Object.create(_dereq_(14));
14296util.inherits = _dereq_(37);
14297/*</replacement>*/
14298
14299var Readable = _dereq_(90);
14300var Writable = _dereq_(92);
14301
14302util.inherits(Duplex, Readable);
14303
14304{
14305 // avoid scope creep, the keys array can then be collected
14306 var keys = objectKeys(Writable.prototype);
14307 for (var v = 0; v < keys.length; v++) {
14308 var method = keys[v];
14309 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
14310 }
14311}
14312
14313function Duplex(options) {
14314 if (!(this instanceof Duplex)) return new Duplex(options);
14315
14316 Readable.call(this, options);
14317 Writable.call(this, options);
14318
14319 if (options && options.readable === false) this.readable = false;
14320
14321 if (options && options.writable === false) this.writable = false;
14322
14323 this.allowHalfOpen = true;
14324 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
14325
14326 this.once('end', onend);
14327}
14328
14329Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
14330 // making it explicit this property is not enumerable
14331 // because otherwise some prototype manipulation in
14332 // userland will fail
14333 enumerable: false,
14334 get: function () {
14335 return this._writableState.highWaterMark;
14336 }
14337});
14338
14339// the no-half-open enforcer
14340function onend() {
14341 // if we allow half-open state, or if the writable side ended,
14342 // then we're ok.
14343 if (this.allowHalfOpen || this._writableState.ended) return;
14344
14345 // no more data can be written.
14346 // But allow more writes to happen in this tick.
14347 pna.nextTick(onEndNT, this);
14348}
14349
14350function onEndNT(self) {
14351 self.end();
14352}
14353
14354Object.defineProperty(Duplex.prototype, 'destroyed', {
14355 get: function () {
14356 if (this._readableState === undefined || this._writableState === undefined) {
14357 return false;
14358 }
14359 return this._readableState.destroyed && this._writableState.destroyed;
14360 },
14361 set: function (value) {
14362 // we ignore the value if the stream
14363 // has not been initialized yet
14364 if (this._readableState === undefined || this._writableState === undefined) {
14365 return;
14366 }
14367
14368 // backward compatibility, the user is explicitly
14369 // managing destroyed
14370 this._readableState.destroyed = value;
14371 this._writableState.destroyed = value;
14372 }
14373});
14374
14375Duplex.prototype._destroy = function (err, cb) {
14376 this.push(null);
14377 this.end();
14378
14379 pna.nextTick(cb, err);
14380};
14381},{"14":14,"37":37,"72":72,"90":90,"92":92}],89:[function(_dereq_,module,exports){
14382// Copyright Joyent, Inc. and other Node contributors.
14383//
14384// Permission is hereby granted, free of charge, to any person obtaining a
14385// copy of this software and associated documentation files (the
14386// "Software"), to deal in the Software without restriction, including
14387// without limitation the rights to use, copy, modify, merge, publish,
14388// distribute, sublicense, and/or sell copies of the Software, and to permit
14389// persons to whom the Software is furnished to do so, subject to the
14390// following conditions:
14391//
14392// The above copyright notice and this permission notice shall be included
14393// in all copies or substantial portions of the Software.
14394//
14395// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14396// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14397// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14398// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14399// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14400// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14401// USE OR OTHER DEALINGS IN THE SOFTWARE.
14402
14403// a passthrough stream.
14404// basically just the most minimal sort of Transform stream.
14405// Every written chunk gets output as-is.
14406
14407'use strict';
14408
14409module.exports = PassThrough;
14410
14411var Transform = _dereq_(91);
14412
14413/*<replacement>*/
14414var util = Object.create(_dereq_(14));
14415util.inherits = _dereq_(37);
14416/*</replacement>*/
14417
14418util.inherits(PassThrough, Transform);
14419
14420function PassThrough(options) {
14421 if (!(this instanceof PassThrough)) return new PassThrough(options);
14422
14423 Transform.call(this, options);
14424}
14425
14426PassThrough.prototype._transform = function (chunk, encoding, cb) {
14427 cb(null, chunk);
14428};
14429},{"14":14,"37":37,"91":91}],90:[function(_dereq_,module,exports){
14430(function (process,global){(function (){
14431// Copyright Joyent, Inc. and other Node contributors.
14432//
14433// Permission is hereby granted, free of charge, to any person obtaining a
14434// copy of this software and associated documentation files (the
14435// "Software"), to deal in the Software without restriction, including
14436// without limitation the rights to use, copy, modify, merge, publish,
14437// distribute, sublicense, and/or sell copies of the Software, and to permit
14438// persons to whom the Software is furnished to do so, subject to the
14439// following conditions:
14440//
14441// The above copyright notice and this permission notice shall be included
14442// in all copies or substantial portions of the Software.
14443//
14444// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14445// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14446// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14447// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14448// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14449// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14450// USE OR OTHER DEALINGS IN THE SOFTWARE.
14451
14452'use strict';
14453
14454/*<replacement>*/
14455
14456var pna = _dereq_(72);
14457/*</replacement>*/
14458
14459module.exports = Readable;
14460
14461/*<replacement>*/
14462var isArray = _dereq_(86);
14463/*</replacement>*/
14464
14465/*<replacement>*/
14466var Duplex;
14467/*</replacement>*/
14468
14469Readable.ReadableState = ReadableState;
14470
14471/*<replacement>*/
14472var EE = _dereq_(26).EventEmitter;
14473
14474var EElistenerCount = function (emitter, type) {
14475 return emitter.listeners(type).length;
14476};
14477/*</replacement>*/
14478
14479/*<replacement>*/
14480var Stream = _dereq_(95);
14481/*</replacement>*/
14482
14483/*<replacement>*/
14484
14485var Buffer = _dereq_(100).Buffer;
14486var OurUint8Array = global.Uint8Array || function () {};
14487function _uint8ArrayToBuffer(chunk) {
14488 return Buffer.from(chunk);
14489}
14490function _isUint8Array(obj) {
14491 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14492}
14493
14494/*</replacement>*/
14495
14496/*<replacement>*/
14497var util = Object.create(_dereq_(14));
14498util.inherits = _dereq_(37);
14499/*</replacement>*/
14500
14501/*<replacement>*/
14502var debugUtil = _dereq_(11);
14503var debug = void 0;
14504if (debugUtil && debugUtil.debuglog) {
14505 debug = debugUtil.debuglog('stream');
14506} else {
14507 debug = function () {};
14508}
14509/*</replacement>*/
14510
14511var BufferList = _dereq_(93);
14512var destroyImpl = _dereq_(94);
14513var StringDecoder;
14514
14515util.inherits(Readable, Stream);
14516
14517var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14518
14519function prependListener(emitter, event, fn) {
14520 // Sadly this is not cacheable as some libraries bundle their own
14521 // event emitter implementation with them.
14522 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
14523
14524 // This is a hack to make sure that our error handler is attached before any
14525 // userland ones. NEVER DO THIS. This is here only because this code needs
14526 // to continue to work with older versions of Node.js that do not include
14527 // the prependListener() method. The goal is to eventually remove this hack.
14528 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]];
14529}
14530
14531function ReadableState(options, stream) {
14532 Duplex = Duplex || _dereq_(88);
14533
14534 options = options || {};
14535
14536 // Duplex streams are both readable and writable, but share
14537 // the same options object.
14538 // However, some cases require setting options to different
14539 // values for the readable and the writable sides of the duplex stream.
14540 // These options can be provided separately as readableXXX and writableXXX.
14541 var isDuplex = stream instanceof Duplex;
14542
14543 // object stream flag. Used to make read(n) ignore n and to
14544 // make all the buffer merging and length checks go away
14545 this.objectMode = !!options.objectMode;
14546
14547 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
14548
14549 // the point at which it stops calling _read() to fill the buffer
14550 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14551 var hwm = options.highWaterMark;
14552 var readableHwm = options.readableHighWaterMark;
14553 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14554
14555 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
14556
14557 // cast to ints.
14558 this.highWaterMark = Math.floor(this.highWaterMark);
14559
14560 // A linked list is used to store data chunks instead of an array because the
14561 // linked list can remove elements from the beginning faster than
14562 // array.shift()
14563 this.buffer = new BufferList();
14564 this.length = 0;
14565 this.pipes = null;
14566 this.pipesCount = 0;
14567 this.flowing = null;
14568 this.ended = false;
14569 this.endEmitted = false;
14570 this.reading = false;
14571
14572 // a flag to be able to tell if the event 'readable'/'data' is emitted
14573 // immediately, or on a later tick. We set this to true at first, because
14574 // any actions that shouldn't happen until "later" should generally also
14575 // not happen before the first read call.
14576 this.sync = true;
14577
14578 // whenever we return null, then we set a flag to say
14579 // that we're awaiting a 'readable' event emission.
14580 this.needReadable = false;
14581 this.emittedReadable = false;
14582 this.readableListening = false;
14583 this.resumeScheduled = false;
14584
14585 // has it been destroyed
14586 this.destroyed = false;
14587
14588 // Crypto is kind of old and crusty. Historically, its default string
14589 // encoding is 'binary' so we have to make this configurable.
14590 // Everything else in the universe uses 'utf8', though.
14591 this.defaultEncoding = options.defaultEncoding || 'utf8';
14592
14593 // the number of writers that are awaiting a drain event in .pipe()s
14594 this.awaitDrain = 0;
14595
14596 // if true, a maybeReadMore has been scheduled
14597 this.readingMore = false;
14598
14599 this.decoder = null;
14600 this.encoding = null;
14601 if (options.encoding) {
14602 if (!StringDecoder) StringDecoder = _dereq_(101).StringDecoder;
14603 this.decoder = new StringDecoder(options.encoding);
14604 this.encoding = options.encoding;
14605 }
14606}
14607
14608function Readable(options) {
14609 Duplex = Duplex || _dereq_(88);
14610
14611 if (!(this instanceof Readable)) return new Readable(options);
14612
14613 this._readableState = new ReadableState(options, this);
14614
14615 // legacy
14616 this.readable = true;
14617
14618 if (options) {
14619 if (typeof options.read === 'function') this._read = options.read;
14620
14621 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14622 }
14623
14624 Stream.call(this);
14625}
14626
14627Object.defineProperty(Readable.prototype, 'destroyed', {
14628 get: function () {
14629 if (this._readableState === undefined) {
14630 return false;
14631 }
14632 return this._readableState.destroyed;
14633 },
14634 set: function (value) {
14635 // we ignore the value if the stream
14636 // has not been initialized yet
14637 if (!this._readableState) {
14638 return;
14639 }
14640
14641 // backward compatibility, the user is explicitly
14642 // managing destroyed
14643 this._readableState.destroyed = value;
14644 }
14645});
14646
14647Readable.prototype.destroy = destroyImpl.destroy;
14648Readable.prototype._undestroy = destroyImpl.undestroy;
14649Readable.prototype._destroy = function (err, cb) {
14650 this.push(null);
14651 cb(err);
14652};
14653
14654// Manually shove something into the read() buffer.
14655// This returns true if the highWaterMark has not been hit yet,
14656// similar to how Writable.write() returns true if you should
14657// write() some more.
14658Readable.prototype.push = function (chunk, encoding) {
14659 var state = this._readableState;
14660 var skipChunkCheck;
14661
14662 if (!state.objectMode) {
14663 if (typeof chunk === 'string') {
14664 encoding = encoding || state.defaultEncoding;
14665 if (encoding !== state.encoding) {
14666 chunk = Buffer.from(chunk, encoding);
14667 encoding = '';
14668 }
14669 skipChunkCheck = true;
14670 }
14671 } else {
14672 skipChunkCheck = true;
14673 }
14674
14675 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
14676};
14677
14678// Unshift should *always* be something directly out of read()
14679Readable.prototype.unshift = function (chunk) {
14680 return readableAddChunk(this, chunk, null, true, false);
14681};
14682
14683function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
14684 var state = stream._readableState;
14685 if (chunk === null) {
14686 state.reading = false;
14687 onEofChunk(stream, state);
14688 } else {
14689 var er;
14690 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
14691 if (er) {
14692 stream.emit('error', er);
14693 } else if (state.objectMode || chunk && chunk.length > 0) {
14694 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
14695 chunk = _uint8ArrayToBuffer(chunk);
14696 }
14697
14698 if (addToFront) {
14699 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
14700 } else if (state.ended) {
14701 stream.emit('error', new Error('stream.push() after EOF'));
14702 } else {
14703 state.reading = false;
14704 if (state.decoder && !encoding) {
14705 chunk = state.decoder.write(chunk);
14706 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
14707 } else {
14708 addChunk(stream, state, chunk, false);
14709 }
14710 }
14711 } else if (!addToFront) {
14712 state.reading = false;
14713 }
14714 }
14715
14716 return needMoreData(state);
14717}
14718
14719function addChunk(stream, state, chunk, addToFront) {
14720 if (state.flowing && state.length === 0 && !state.sync) {
14721 stream.emit('data', chunk);
14722 stream.read(0);
14723 } else {
14724 // update the buffer info.
14725 state.length += state.objectMode ? 1 : chunk.length;
14726 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
14727
14728 if (state.needReadable) emitReadable(stream);
14729 }
14730 maybeReadMore(stream, state);
14731}
14732
14733function chunkInvalid(state, chunk) {
14734 var er;
14735 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
14736 er = new TypeError('Invalid non-string/buffer chunk');
14737 }
14738 return er;
14739}
14740
14741// if it's past the high water mark, we can push in some more.
14742// Also, if we have no data yet, we can stand some
14743// more bytes. This is to work around cases where hwm=0,
14744// such as the repl. Also, if the push() triggered a
14745// readable event, and the user called read(largeNumber) such that
14746// needReadable was set, then we ought to push more, so that another
14747// 'readable' event will be triggered.
14748function needMoreData(state) {
14749 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
14750}
14751
14752Readable.prototype.isPaused = function () {
14753 return this._readableState.flowing === false;
14754};
14755
14756// backwards compatibility.
14757Readable.prototype.setEncoding = function (enc) {
14758 if (!StringDecoder) StringDecoder = _dereq_(101).StringDecoder;
14759 this._readableState.decoder = new StringDecoder(enc);
14760 this._readableState.encoding = enc;
14761 return this;
14762};
14763
14764// Don't raise the hwm > 8MB
14765var MAX_HWM = 0x800000;
14766function computeNewHighWaterMark(n) {
14767 if (n >= MAX_HWM) {
14768 n = MAX_HWM;
14769 } else {
14770 // Get the next highest power of 2 to prevent increasing hwm excessively in
14771 // tiny amounts
14772 n--;
14773 n |= n >>> 1;
14774 n |= n >>> 2;
14775 n |= n >>> 4;
14776 n |= n >>> 8;
14777 n |= n >>> 16;
14778 n++;
14779 }
14780 return n;
14781}
14782
14783// This function is designed to be inlinable, so please take care when making
14784// changes to the function body.
14785function howMuchToRead(n, state) {
14786 if (n <= 0 || state.length === 0 && state.ended) return 0;
14787 if (state.objectMode) return 1;
14788 if (n !== n) {
14789 // Only flow one buffer at a time
14790 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
14791 }
14792 // If we're asking for more than the current hwm, then raise the hwm.
14793 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
14794 if (n <= state.length) return n;
14795 // Don't have enough
14796 if (!state.ended) {
14797 state.needReadable = true;
14798 return 0;
14799 }
14800 return state.length;
14801}
14802
14803// you can override either this method, or the async _read(n) below.
14804Readable.prototype.read = function (n) {
14805 debug('read', n);
14806 n = parseInt(n, 10);
14807 var state = this._readableState;
14808 var nOrig = n;
14809
14810 if (n !== 0) state.emittedReadable = false;
14811
14812 // if we're doing read(0) to trigger a readable event, but we
14813 // already have a bunch of data in the buffer, then just trigger
14814 // the 'readable' event and move on.
14815 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
14816 debug('read: emitReadable', state.length, state.ended);
14817 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
14818 return null;
14819 }
14820
14821 n = howMuchToRead(n, state);
14822
14823 // if we've ended, and we're now clear, then finish it up.
14824 if (n === 0 && state.ended) {
14825 if (state.length === 0) endReadable(this);
14826 return null;
14827 }
14828
14829 // All the actual chunk generation logic needs to be
14830 // *below* the call to _read. The reason is that in certain
14831 // synthetic stream cases, such as passthrough streams, _read
14832 // may be a completely synchronous operation which may change
14833 // the state of the read buffer, providing enough data when
14834 // before there was *not* enough.
14835 //
14836 // So, the steps are:
14837 // 1. Figure out what the state of things will be after we do
14838 // a read from the buffer.
14839 //
14840 // 2. If that resulting state will trigger a _read, then call _read.
14841 // Note that this may be asynchronous, or synchronous. Yes, it is
14842 // deeply ugly to write APIs this way, but that still doesn't mean
14843 // that the Readable class should behave improperly, as streams are
14844 // designed to be sync/async agnostic.
14845 // Take note if the _read call is sync or async (ie, if the read call
14846 // has returned yet), so that we know whether or not it's safe to emit
14847 // 'readable' etc.
14848 //
14849 // 3. Actually pull the requested chunks out of the buffer and return.
14850
14851 // if we need a readable event, then we need to do some reading.
14852 var doRead = state.needReadable;
14853 debug('need readable', doRead);
14854
14855 // if we currently have less than the highWaterMark, then also read some
14856 if (state.length === 0 || state.length - n < state.highWaterMark) {
14857 doRead = true;
14858 debug('length less than watermark', doRead);
14859 }
14860
14861 // however, if we've ended, then there's no point, and if we're already
14862 // reading, then it's unnecessary.
14863 if (state.ended || state.reading) {
14864 doRead = false;
14865 debug('reading or ended', doRead);
14866 } else if (doRead) {
14867 debug('do read');
14868 state.reading = true;
14869 state.sync = true;
14870 // if the length is currently zero, then we *need* a readable event.
14871 if (state.length === 0) state.needReadable = true;
14872 // call internal read method
14873 this._read(state.highWaterMark);
14874 state.sync = false;
14875 // If _read pushed data synchronously, then `reading` will be false,
14876 // and we need to re-evaluate how much data we can return to the user.
14877 if (!state.reading) n = howMuchToRead(nOrig, state);
14878 }
14879
14880 var ret;
14881 if (n > 0) ret = fromList(n, state);else ret = null;
14882
14883 if (ret === null) {
14884 state.needReadable = true;
14885 n = 0;
14886 } else {
14887 state.length -= n;
14888 }
14889
14890 if (state.length === 0) {
14891 // If we have nothing in the buffer, then we want to know
14892 // as soon as we *do* get something into the buffer.
14893 if (!state.ended) state.needReadable = true;
14894
14895 // If we tried to read() past the EOF, then emit end on the next tick.
14896 if (nOrig !== n && state.ended) endReadable(this);
14897 }
14898
14899 if (ret !== null) this.emit('data', ret);
14900
14901 return ret;
14902};
14903
14904function onEofChunk(stream, state) {
14905 if (state.ended) return;
14906 if (state.decoder) {
14907 var chunk = state.decoder.end();
14908 if (chunk && chunk.length) {
14909 state.buffer.push(chunk);
14910 state.length += state.objectMode ? 1 : chunk.length;
14911 }
14912 }
14913 state.ended = true;
14914
14915 // emit 'readable' now to make sure it gets picked up.
14916 emitReadable(stream);
14917}
14918
14919// Don't emit readable right away in sync mode, because this can trigger
14920// another read() call => stack overflow. This way, it might trigger
14921// a nextTick recursion warning, but that's not so bad.
14922function emitReadable(stream) {
14923 var state = stream._readableState;
14924 state.needReadable = false;
14925 if (!state.emittedReadable) {
14926 debug('emitReadable', state.flowing);
14927 state.emittedReadable = true;
14928 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
14929 }
14930}
14931
14932function emitReadable_(stream) {
14933 debug('emit readable');
14934 stream.emit('readable');
14935 flow(stream);
14936}
14937
14938// at this point, the user has presumably seen the 'readable' event,
14939// and called read() to consume some data. that may have triggered
14940// in turn another _read(n) call, in which case reading = true if
14941// it's in progress.
14942// However, if we're not ended, or reading, and the length < hwm,
14943// then go ahead and try to read some more preemptively.
14944function maybeReadMore(stream, state) {
14945 if (!state.readingMore) {
14946 state.readingMore = true;
14947 pna.nextTick(maybeReadMore_, stream, state);
14948 }
14949}
14950
14951function maybeReadMore_(stream, state) {
14952 var len = state.length;
14953 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
14954 debug('maybeReadMore read 0');
14955 stream.read(0);
14956 if (len === state.length)
14957 // didn't get any data, stop spinning.
14958 break;else len = state.length;
14959 }
14960 state.readingMore = false;
14961}
14962
14963// abstract method. to be overridden in specific implementation classes.
14964// call cb(er, data) where data is <= n in length.
14965// for virtual (non-string, non-buffer) streams, "length" is somewhat
14966// arbitrary, and perhaps not very meaningful.
14967Readable.prototype._read = function (n) {
14968 this.emit('error', new Error('_read() is not implemented'));
14969};
14970
14971Readable.prototype.pipe = function (dest, pipeOpts) {
14972 var src = this;
14973 var state = this._readableState;
14974
14975 switch (state.pipesCount) {
14976 case 0:
14977 state.pipes = dest;
14978 break;
14979 case 1:
14980 state.pipes = [state.pipes, dest];
14981 break;
14982 default:
14983 state.pipes.push(dest);
14984 break;
14985 }
14986 state.pipesCount += 1;
14987 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
14988
14989 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
14990
14991 var endFn = doEnd ? onend : unpipe;
14992 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
14993
14994 dest.on('unpipe', onunpipe);
14995 function onunpipe(readable, unpipeInfo) {
14996 debug('onunpipe');
14997 if (readable === src) {
14998 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
14999 unpipeInfo.hasUnpiped = true;
15000 cleanup();
15001 }
15002 }
15003 }
15004
15005 function onend() {
15006 debug('onend');
15007 dest.end();
15008 }
15009
15010 // when the dest drains, it reduces the awaitDrain counter
15011 // on the source. This would be more elegant with a .once()
15012 // handler in flow(), but adding and removing repeatedly is
15013 // too slow.
15014 var ondrain = pipeOnDrain(src);
15015 dest.on('drain', ondrain);
15016
15017 var cleanedUp = false;
15018 function cleanup() {
15019 debug('cleanup');
15020 // cleanup event handlers once the pipe is broken
15021 dest.removeListener('close', onclose);
15022 dest.removeListener('finish', onfinish);
15023 dest.removeListener('drain', ondrain);
15024 dest.removeListener('error', onerror);
15025 dest.removeListener('unpipe', onunpipe);
15026 src.removeListener('end', onend);
15027 src.removeListener('end', unpipe);
15028 src.removeListener('data', ondata);
15029
15030 cleanedUp = true;
15031
15032 // if the reader is waiting for a drain event from this
15033 // specific writer, then it would cause it to never start
15034 // flowing again.
15035 // So, if this is awaiting a drain, then we just call it now.
15036 // If we don't know, then assume that we are waiting for one.
15037 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
15038 }
15039
15040 // If the user pushes more data while we're writing to dest then we'll end up
15041 // in ondata again. However, we only want to increase awaitDrain once because
15042 // dest will only emit one 'drain' event for the multiple writes.
15043 // => Introduce a guard on increasing awaitDrain.
15044 var increasedAwaitDrain = false;
15045 src.on('data', ondata);
15046 function ondata(chunk) {
15047 debug('ondata');
15048 increasedAwaitDrain = false;
15049 var ret = dest.write(chunk);
15050 if (false === ret && !increasedAwaitDrain) {
15051 // If the user unpiped during `dest.write()`, it is possible
15052 // to get stuck in a permanently paused state if that write
15053 // also returned false.
15054 // => Check whether `dest` is still a piping destination.
15055 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
15056 debug('false write response, pause', src._readableState.awaitDrain);
15057 src._readableState.awaitDrain++;
15058 increasedAwaitDrain = true;
15059 }
15060 src.pause();
15061 }
15062 }
15063
15064 // if the dest has an error, then stop piping into it.
15065 // however, don't suppress the throwing behavior for this.
15066 function onerror(er) {
15067 debug('onerror', er);
15068 unpipe();
15069 dest.removeListener('error', onerror);
15070 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
15071 }
15072
15073 // Make sure our error handler is attached before userland ones.
15074 prependListener(dest, 'error', onerror);
15075
15076 // Both close and finish should trigger unpipe, but only once.
15077 function onclose() {
15078 dest.removeListener('finish', onfinish);
15079 unpipe();
15080 }
15081 dest.once('close', onclose);
15082 function onfinish() {
15083 debug('onfinish');
15084 dest.removeListener('close', onclose);
15085 unpipe();
15086 }
15087 dest.once('finish', onfinish);
15088
15089 function unpipe() {
15090 debug('unpipe');
15091 src.unpipe(dest);
15092 }
15093
15094 // tell the dest that it's being piped to
15095 dest.emit('pipe', src);
15096
15097 // start the flow if it hasn't been started already.
15098 if (!state.flowing) {
15099 debug('pipe resume');
15100 src.resume();
15101 }
15102
15103 return dest;
15104};
15105
15106function pipeOnDrain(src) {
15107 return function () {
15108 var state = src._readableState;
15109 debug('pipeOnDrain', state.awaitDrain);
15110 if (state.awaitDrain) state.awaitDrain--;
15111 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
15112 state.flowing = true;
15113 flow(src);
15114 }
15115 };
15116}
15117
15118Readable.prototype.unpipe = function (dest) {
15119 var state = this._readableState;
15120 var unpipeInfo = { hasUnpiped: false };
15121
15122 // if we're not piping anywhere, then do nothing.
15123 if (state.pipesCount === 0) return this;
15124
15125 // just one destination. most common case.
15126 if (state.pipesCount === 1) {
15127 // passed in one, but it's not the right one.
15128 if (dest && dest !== state.pipes) return this;
15129
15130 if (!dest) dest = state.pipes;
15131
15132 // got a match.
15133 state.pipes = null;
15134 state.pipesCount = 0;
15135 state.flowing = false;
15136 if (dest) dest.emit('unpipe', this, unpipeInfo);
15137 return this;
15138 }
15139
15140 // slow case. multiple pipe destinations.
15141
15142 if (!dest) {
15143 // remove all.
15144 var dests = state.pipes;
15145 var len = state.pipesCount;
15146 state.pipes = null;
15147 state.pipesCount = 0;
15148 state.flowing = false;
15149
15150 for (var i = 0; i < len; i++) {
15151 dests[i].emit('unpipe', this, unpipeInfo);
15152 }return this;
15153 }
15154
15155 // try to find the right one.
15156 var index = indexOf(state.pipes, dest);
15157 if (index === -1) return this;
15158
15159 state.pipes.splice(index, 1);
15160 state.pipesCount -= 1;
15161 if (state.pipesCount === 1) state.pipes = state.pipes[0];
15162
15163 dest.emit('unpipe', this, unpipeInfo);
15164
15165 return this;
15166};
15167
15168// set up data events if they are asked for
15169// Ensure readable listeners eventually get something
15170Readable.prototype.on = function (ev, fn) {
15171 var res = Stream.prototype.on.call(this, ev, fn);
15172
15173 if (ev === 'data') {
15174 // Start flowing on next tick if stream isn't explicitly paused
15175 if (this._readableState.flowing !== false) this.resume();
15176 } else if (ev === 'readable') {
15177 var state = this._readableState;
15178 if (!state.endEmitted && !state.readableListening) {
15179 state.readableListening = state.needReadable = true;
15180 state.emittedReadable = false;
15181 if (!state.reading) {
15182 pna.nextTick(nReadingNextTick, this);
15183 } else if (state.length) {
15184 emitReadable(this);
15185 }
15186 }
15187 }
15188
15189 return res;
15190};
15191Readable.prototype.addListener = Readable.prototype.on;
15192
15193function nReadingNextTick(self) {
15194 debug('readable nexttick read 0');
15195 self.read(0);
15196}
15197
15198// pause() and resume() are remnants of the legacy readable stream API
15199// If the user uses them, then switch into old mode.
15200Readable.prototype.resume = function () {
15201 var state = this._readableState;
15202 if (!state.flowing) {
15203 debug('resume');
15204 state.flowing = true;
15205 resume(this, state);
15206 }
15207 return this;
15208};
15209
15210function resume(stream, state) {
15211 if (!state.resumeScheduled) {
15212 state.resumeScheduled = true;
15213 pna.nextTick(resume_, stream, state);
15214 }
15215}
15216
15217function resume_(stream, state) {
15218 if (!state.reading) {
15219 debug('resume read 0');
15220 stream.read(0);
15221 }
15222
15223 state.resumeScheduled = false;
15224 state.awaitDrain = 0;
15225 stream.emit('resume');
15226 flow(stream);
15227 if (state.flowing && !state.reading) stream.read(0);
15228}
15229
15230Readable.prototype.pause = function () {
15231 debug('call pause flowing=%j', this._readableState.flowing);
15232 if (false !== this._readableState.flowing) {
15233 debug('pause');
15234 this._readableState.flowing = false;
15235 this.emit('pause');
15236 }
15237 return this;
15238};
15239
15240function flow(stream) {
15241 var state = stream._readableState;
15242 debug('flow', state.flowing);
15243 while (state.flowing && stream.read() !== null) {}
15244}
15245
15246// wrap an old-style stream as the async data source.
15247// This is *not* part of the readable stream interface.
15248// It is an ugly unfortunate mess of history.
15249Readable.prototype.wrap = function (stream) {
15250 var _this = this;
15251
15252 var state = this._readableState;
15253 var paused = false;
15254
15255 stream.on('end', function () {
15256 debug('wrapped end');
15257 if (state.decoder && !state.ended) {
15258 var chunk = state.decoder.end();
15259 if (chunk && chunk.length) _this.push(chunk);
15260 }
15261
15262 _this.push(null);
15263 });
15264
15265 stream.on('data', function (chunk) {
15266 debug('wrapped data');
15267 if (state.decoder) chunk = state.decoder.write(chunk);
15268
15269 // don't skip over falsy values in objectMode
15270 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
15271
15272 var ret = _this.push(chunk);
15273 if (!ret) {
15274 paused = true;
15275 stream.pause();
15276 }
15277 });
15278
15279 // proxy all the other methods.
15280 // important when wrapping filters and duplexes.
15281 for (var i in stream) {
15282 if (this[i] === undefined && typeof stream[i] === 'function') {
15283 this[i] = function (method) {
15284 return function () {
15285 return stream[method].apply(stream, arguments);
15286 };
15287 }(i);
15288 }
15289 }
15290
15291 // proxy certain important events.
15292 for (var n = 0; n < kProxyEvents.length; n++) {
15293 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
15294 }
15295
15296 // when we try to consume some more bytes, simply unpause the
15297 // underlying stream.
15298 this._read = function (n) {
15299 debug('wrapped _read', n);
15300 if (paused) {
15301 paused = false;
15302 stream.resume();
15303 }
15304 };
15305
15306 return this;
15307};
15308
15309Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
15310 // making it explicit this property is not enumerable
15311 // because otherwise some prototype manipulation in
15312 // userland will fail
15313 enumerable: false,
15314 get: function () {
15315 return this._readableState.highWaterMark;
15316 }
15317});
15318
15319// exposed for testing purposes only.
15320Readable._fromList = fromList;
15321
15322// Pluck off n bytes from an array of buffers.
15323// Length is the combined lengths of all the buffers in the list.
15324// This function is designed to be inlinable, so please take care when making
15325// changes to the function body.
15326function fromList(n, state) {
15327 // nothing buffered
15328 if (state.length === 0) return null;
15329
15330 var ret;
15331 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
15332 // read it all, truncate the list
15333 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);
15334 state.buffer.clear();
15335 } else {
15336 // read part of list
15337 ret = fromListPartial(n, state.buffer, state.decoder);
15338 }
15339
15340 return ret;
15341}
15342
15343// Extracts only enough buffered data to satisfy the amount requested.
15344// This function is designed to be inlinable, so please take care when making
15345// changes to the function body.
15346function fromListPartial(n, list, hasStrings) {
15347 var ret;
15348 if (n < list.head.data.length) {
15349 // slice is the same for buffers and strings
15350 ret = list.head.data.slice(0, n);
15351 list.head.data = list.head.data.slice(n);
15352 } else if (n === list.head.data.length) {
15353 // first chunk is a perfect match
15354 ret = list.shift();
15355 } else {
15356 // result spans more than one buffer
15357 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
15358 }
15359 return ret;
15360}
15361
15362// Copies a specified amount of characters from the list of buffered data
15363// chunks.
15364// This function is designed to be inlinable, so please take care when making
15365// changes to the function body.
15366function copyFromBufferString(n, list) {
15367 var p = list.head;
15368 var c = 1;
15369 var ret = p.data;
15370 n -= ret.length;
15371 while (p = p.next) {
15372 var str = p.data;
15373 var nb = n > str.length ? str.length : n;
15374 if (nb === str.length) ret += str;else ret += str.slice(0, n);
15375 n -= nb;
15376 if (n === 0) {
15377 if (nb === str.length) {
15378 ++c;
15379 if (p.next) list.head = p.next;else list.head = list.tail = null;
15380 } else {
15381 list.head = p;
15382 p.data = str.slice(nb);
15383 }
15384 break;
15385 }
15386 ++c;
15387 }
15388 list.length -= c;
15389 return ret;
15390}
15391
15392// Copies a specified amount of bytes from the list of buffered data chunks.
15393// This function is designed to be inlinable, so please take care when making
15394// changes to the function body.
15395function copyFromBuffer(n, list) {
15396 var ret = Buffer.allocUnsafe(n);
15397 var p = list.head;
15398 var c = 1;
15399 p.data.copy(ret);
15400 n -= p.data.length;
15401 while (p = p.next) {
15402 var buf = p.data;
15403 var nb = n > buf.length ? buf.length : n;
15404 buf.copy(ret, ret.length - n, 0, nb);
15405 n -= nb;
15406 if (n === 0) {
15407 if (nb === buf.length) {
15408 ++c;
15409 if (p.next) list.head = p.next;else list.head = list.tail = null;
15410 } else {
15411 list.head = p;
15412 p.data = buf.slice(nb);
15413 }
15414 break;
15415 }
15416 ++c;
15417 }
15418 list.length -= c;
15419 return ret;
15420}
15421
15422function endReadable(stream) {
15423 var state = stream._readableState;
15424
15425 // If we get here before consuming all the bytes, then that is a
15426 // bug in node. Should never happen.
15427 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
15428
15429 if (!state.endEmitted) {
15430 state.ended = true;
15431 pna.nextTick(endReadableNT, state, stream);
15432 }
15433}
15434
15435function endReadableNT(state, stream) {
15436 // Check that we didn't get one last unshift.
15437 if (!state.endEmitted && state.length === 0) {
15438 state.endEmitted = true;
15439 stream.readable = false;
15440 stream.emit('end');
15441 }
15442}
15443
15444function indexOf(xs, x) {
15445 for (var i = 0, l = xs.length; i < l; i++) {
15446 if (xs[i] === x) return i;
15447 }
15448 return -1;
15449}
15450}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15451},{"100":100,"101":101,"11":11,"14":14,"26":26,"37":37,"72":72,"73":73,"86":86,"88":88,"93":93,"94":94,"95":95}],91:[function(_dereq_,module,exports){
15452// Copyright Joyent, Inc. and other Node contributors.
15453//
15454// Permission is hereby granted, free of charge, to any person obtaining a
15455// copy of this software and associated documentation files (the
15456// "Software"), to deal in the Software without restriction, including
15457// without limitation the rights to use, copy, modify, merge, publish,
15458// distribute, sublicense, and/or sell copies of the Software, and to permit
15459// persons to whom the Software is furnished to do so, subject to the
15460// following conditions:
15461//
15462// The above copyright notice and this permission notice shall be included
15463// in all copies or substantial portions of the Software.
15464//
15465// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15466// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15467// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15468// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15469// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15470// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15471// USE OR OTHER DEALINGS IN THE SOFTWARE.
15472
15473// a transform stream is a readable/writable stream where you do
15474// something with the data. Sometimes it's called a "filter",
15475// but that's not a great name for it, since that implies a thing where
15476// some bits pass through, and others are simply ignored. (That would
15477// be a valid example of a transform, of course.)
15478//
15479// While the output is causally related to the input, it's not a
15480// necessarily symmetric or synchronous transformation. For example,
15481// a zlib stream might take multiple plain-text writes(), and then
15482// emit a single compressed chunk some time in the future.
15483//
15484// Here's how this works:
15485//
15486// The Transform stream has all the aspects of the readable and writable
15487// stream classes. When you write(chunk), that calls _write(chunk,cb)
15488// internally, and returns false if there's a lot of pending writes
15489// buffered up. When you call read(), that calls _read(n) until
15490// there's enough pending readable data buffered up.
15491//
15492// In a transform stream, the written data is placed in a buffer. When
15493// _read(n) is called, it transforms the queued up data, calling the
15494// buffered _write cb's as it consumes chunks. If consuming a single
15495// written chunk would result in multiple output chunks, then the first
15496// outputted bit calls the readcb, and subsequent chunks just go into
15497// the read buffer, and will cause it to emit 'readable' if necessary.
15498//
15499// This way, back-pressure is actually determined by the reading side,
15500// since _read has to be called to start processing a new chunk. However,
15501// a pathological inflate type of transform can cause excessive buffering
15502// here. For example, imagine a stream where every byte of input is
15503// interpreted as an integer from 0-255, and then results in that many
15504// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
15505// 1kb of data being output. In this case, you could write a very small
15506// amount of input, and end up with a very large amount of output. In
15507// such a pathological inflating mechanism, there'd be no way to tell
15508// the system to stop doing the transform. A single 4MB write could
15509// cause the system to run out of memory.
15510//
15511// However, even in such a pathological case, only a single written chunk
15512// would be consumed, and then the rest would wait (un-transformed) until
15513// the results of the previous transformed chunk were consumed.
15514
15515'use strict';
15516
15517module.exports = Transform;
15518
15519var Duplex = _dereq_(88);
15520
15521/*<replacement>*/
15522var util = Object.create(_dereq_(14));
15523util.inherits = _dereq_(37);
15524/*</replacement>*/
15525
15526util.inherits(Transform, Duplex);
15527
15528function afterTransform(er, data) {
15529 var ts = this._transformState;
15530 ts.transforming = false;
15531
15532 var cb = ts.writecb;
15533
15534 if (!cb) {
15535 return this.emit('error', new Error('write callback called multiple times'));
15536 }
15537
15538 ts.writechunk = null;
15539 ts.writecb = null;
15540
15541 if (data != null) // single equals check for both `null` and `undefined`
15542 this.push(data);
15543
15544 cb(er);
15545
15546 var rs = this._readableState;
15547 rs.reading = false;
15548 if (rs.needReadable || rs.length < rs.highWaterMark) {
15549 this._read(rs.highWaterMark);
15550 }
15551}
15552
15553function Transform(options) {
15554 if (!(this instanceof Transform)) return new Transform(options);
15555
15556 Duplex.call(this, options);
15557
15558 this._transformState = {
15559 afterTransform: afterTransform.bind(this),
15560 needTransform: false,
15561 transforming: false,
15562 writecb: null,
15563 writechunk: null,
15564 writeencoding: null
15565 };
15566
15567 // start out asking for a readable event once data is transformed.
15568 this._readableState.needReadable = true;
15569
15570 // we have implemented the _read method, and done the other things
15571 // that Readable wants before the first _read call, so unset the
15572 // sync guard flag.
15573 this._readableState.sync = false;
15574
15575 if (options) {
15576 if (typeof options.transform === 'function') this._transform = options.transform;
15577
15578 if (typeof options.flush === 'function') this._flush = options.flush;
15579 }
15580
15581 // When the writable side finishes, then flush out anything remaining.
15582 this.on('prefinish', prefinish);
15583}
15584
15585function prefinish() {
15586 var _this = this;
15587
15588 if (typeof this._flush === 'function') {
15589 this._flush(function (er, data) {
15590 done(_this, er, data);
15591 });
15592 } else {
15593 done(this, null, null);
15594 }
15595}
15596
15597Transform.prototype.push = function (chunk, encoding) {
15598 this._transformState.needTransform = false;
15599 return Duplex.prototype.push.call(this, chunk, encoding);
15600};
15601
15602// This is the part where you do stuff!
15603// override this function in implementation classes.
15604// 'chunk' is an input chunk.
15605//
15606// Call `push(newChunk)` to pass along transformed output
15607// to the readable side. You may call 'push' zero or more times.
15608//
15609// Call `cb(err)` when you are done with this chunk. If you pass
15610// an error, then that'll put the hurt on the whole operation. If you
15611// never call cb(), then you'll never get another chunk.
15612Transform.prototype._transform = function (chunk, encoding, cb) {
15613 throw new Error('_transform() is not implemented');
15614};
15615
15616Transform.prototype._write = function (chunk, encoding, cb) {
15617 var ts = this._transformState;
15618 ts.writecb = cb;
15619 ts.writechunk = chunk;
15620 ts.writeencoding = encoding;
15621 if (!ts.transforming) {
15622 var rs = this._readableState;
15623 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15624 }
15625};
15626
15627// Doesn't matter what the args are here.
15628// _transform does all the work.
15629// That we got here means that the readable side wants more data.
15630Transform.prototype._read = function (n) {
15631 var ts = this._transformState;
15632
15633 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15634 ts.transforming = true;
15635 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15636 } else {
15637 // mark that we need a transform, so that any data that comes in
15638 // will get processed, now that we've asked for it.
15639 ts.needTransform = true;
15640 }
15641};
15642
15643Transform.prototype._destroy = function (err, cb) {
15644 var _this2 = this;
15645
15646 Duplex.prototype._destroy.call(this, err, function (err2) {
15647 cb(err2);
15648 _this2.emit('close');
15649 });
15650};
15651
15652function done(stream, er, data) {
15653 if (er) return stream.emit('error', er);
15654
15655 if (data != null) // single equals check for both `null` and `undefined`
15656 stream.push(data);
15657
15658 // if there's nothing in the write buffer, then that means
15659 // that nothing more will ever be provided
15660 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
15661
15662 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
15663
15664 return stream.push(null);
15665}
15666},{"14":14,"37":37,"88":88}],92:[function(_dereq_,module,exports){
15667(function (process,global,setImmediate){(function (){
15668// Copyright Joyent, Inc. and other Node contributors.
15669//
15670// Permission is hereby granted, free of charge, to any person obtaining a
15671// copy of this software and associated documentation files (the
15672// "Software"), to deal in the Software without restriction, including
15673// without limitation the rights to use, copy, modify, merge, publish,
15674// distribute, sublicense, and/or sell copies of the Software, and to permit
15675// persons to whom the Software is furnished to do so, subject to the
15676// following conditions:
15677//
15678// The above copyright notice and this permission notice shall be included
15679// in all copies or substantial portions of the Software.
15680//
15681// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15682// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15683// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15684// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15685// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15686// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15687// USE OR OTHER DEALINGS IN THE SOFTWARE.
15688
15689// A bit simpler than readable streams.
15690// Implement an async ._write(chunk, encoding, cb), and it'll handle all
15691// the drain event emission and buffering.
15692
15693'use strict';
15694
15695/*<replacement>*/
15696
15697var pna = _dereq_(72);
15698/*</replacement>*/
15699
15700module.exports = Writable;
15701
15702/* <replacement> */
15703function WriteReq(chunk, encoding, cb) {
15704 this.chunk = chunk;
15705 this.encoding = encoding;
15706 this.callback = cb;
15707 this.next = null;
15708}
15709
15710// It seems a linked list but it is not
15711// there will be only 2 of these for each stream
15712function CorkedRequest(state) {
15713 var _this = this;
15714
15715 this.next = null;
15716 this.entry = null;
15717 this.finish = function () {
15718 onCorkedFinish(_this, state);
15719 };
15720}
15721/* </replacement> */
15722
15723/*<replacement>*/
15724var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
15725/*</replacement>*/
15726
15727/*<replacement>*/
15728var Duplex;
15729/*</replacement>*/
15730
15731Writable.WritableState = WritableState;
15732
15733/*<replacement>*/
15734var util = Object.create(_dereq_(14));
15735util.inherits = _dereq_(37);
15736/*</replacement>*/
15737
15738/*<replacement>*/
15739var internalUtil = {
15740 deprecate: _dereq_(121)
15741};
15742/*</replacement>*/
15743
15744/*<replacement>*/
15745var Stream = _dereq_(95);
15746/*</replacement>*/
15747
15748/*<replacement>*/
15749
15750var Buffer = _dereq_(100).Buffer;
15751var OurUint8Array = global.Uint8Array || function () {};
15752function _uint8ArrayToBuffer(chunk) {
15753 return Buffer.from(chunk);
15754}
15755function _isUint8Array(obj) {
15756 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
15757}
15758
15759/*</replacement>*/
15760
15761var destroyImpl = _dereq_(94);
15762
15763util.inherits(Writable, Stream);
15764
15765function nop() {}
15766
15767function WritableState(options, stream) {
15768 Duplex = Duplex || _dereq_(88);
15769
15770 options = options || {};
15771
15772 // Duplex streams are both readable and writable, but share
15773 // the same options object.
15774 // However, some cases require setting options to different
15775 // values for the readable and the writable sides of the duplex stream.
15776 // These options can be provided separately as readableXXX and writableXXX.
15777 var isDuplex = stream instanceof Duplex;
15778
15779 // object stream flag to indicate whether or not this stream
15780 // contains buffers or objects.
15781 this.objectMode = !!options.objectMode;
15782
15783 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
15784
15785 // the point at which write() starts returning false
15786 // Note: 0 is a valid value, means that we always return false if
15787 // the entire buffer is not flushed immediately on write()
15788 var hwm = options.highWaterMark;
15789 var writableHwm = options.writableHighWaterMark;
15790 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
15791
15792 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
15793
15794 // cast to ints.
15795 this.highWaterMark = Math.floor(this.highWaterMark);
15796
15797 // if _final has been called
15798 this.finalCalled = false;
15799
15800 // drain event flag.
15801 this.needDrain = false;
15802 // at the start of calling end()
15803 this.ending = false;
15804 // when end() has been called, and returned
15805 this.ended = false;
15806 // when 'finish' is emitted
15807 this.finished = false;
15808
15809 // has it been destroyed
15810 this.destroyed = false;
15811
15812 // should we decode strings into buffers before passing to _write?
15813 // this is here so that some node-core streams can optimize string
15814 // handling at a lower level.
15815 var noDecode = options.decodeStrings === false;
15816 this.decodeStrings = !noDecode;
15817
15818 // Crypto is kind of old and crusty. Historically, its default string
15819 // encoding is 'binary' so we have to make this configurable.
15820 // Everything else in the universe uses 'utf8', though.
15821 this.defaultEncoding = options.defaultEncoding || 'utf8';
15822
15823 // not an actual buffer we keep track of, but a measurement
15824 // of how much we're waiting to get pushed to some underlying
15825 // socket or file.
15826 this.length = 0;
15827
15828 // a flag to see when we're in the middle of a write.
15829 this.writing = false;
15830
15831 // when true all writes will be buffered until .uncork() call
15832 this.corked = 0;
15833
15834 // a flag to be able to tell if the onwrite cb is called immediately,
15835 // or on a later tick. We set this to true at first, because any
15836 // actions that shouldn't happen until "later" should generally also
15837 // not happen before the first write call.
15838 this.sync = true;
15839
15840 // a flag to know if we're processing previously buffered items, which
15841 // may call the _write() callback in the same tick, so that we don't
15842 // end up in an overlapped onwrite situation.
15843 this.bufferProcessing = false;
15844
15845 // the callback that's passed to _write(chunk,cb)
15846 this.onwrite = function (er) {
15847 onwrite(stream, er);
15848 };
15849
15850 // the callback that the user supplies to write(chunk,encoding,cb)
15851 this.writecb = null;
15852
15853 // the amount that is being written when _write is called.
15854 this.writelen = 0;
15855
15856 this.bufferedRequest = null;
15857 this.lastBufferedRequest = null;
15858
15859 // number of pending user-supplied write callbacks
15860 // this must be 0 before 'finish' can be emitted
15861 this.pendingcb = 0;
15862
15863 // emit prefinish if the only thing we're waiting for is _write cbs
15864 // This is relevant for synchronous Transform streams
15865 this.prefinished = false;
15866
15867 // True if the error was already emitted and should not be thrown again
15868 this.errorEmitted = false;
15869
15870 // count buffered requests
15871 this.bufferedRequestCount = 0;
15872
15873 // allocate the first CorkedRequest, there is always
15874 // one allocated and free to use, and we maintain at most two
15875 this.corkedRequestsFree = new CorkedRequest(this);
15876}
15877
15878WritableState.prototype.getBuffer = function getBuffer() {
15879 var current = this.bufferedRequest;
15880 var out = [];
15881 while (current) {
15882 out.push(current);
15883 current = current.next;
15884 }
15885 return out;
15886};
15887
15888(function () {
15889 try {
15890 Object.defineProperty(WritableState.prototype, 'buffer', {
15891 get: internalUtil.deprecate(function () {
15892 return this.getBuffer();
15893 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
15894 });
15895 } catch (_) {}
15896})();
15897
15898// Test _writableState for inheritance to account for Duplex streams,
15899// whose prototype chain only points to Readable.
15900var realHasInstance;
15901if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
15902 realHasInstance = Function.prototype[Symbol.hasInstance];
15903 Object.defineProperty(Writable, Symbol.hasInstance, {
15904 value: function (object) {
15905 if (realHasInstance.call(this, object)) return true;
15906 if (this !== Writable) return false;
15907
15908 return object && object._writableState instanceof WritableState;
15909 }
15910 });
15911} else {
15912 realHasInstance = function (object) {
15913 return object instanceof this;
15914 };
15915}
15916
15917function Writable(options) {
15918 Duplex = Duplex || _dereq_(88);
15919
15920 // Writable ctor is applied to Duplexes, too.
15921 // `realHasInstance` is necessary because using plain `instanceof`
15922 // would return false, as no `_writableState` property is attached.
15923
15924 // Trying to use the custom `instanceof` for Writable here will also break the
15925 // Node.js LazyTransform implementation, which has a non-trivial getter for
15926 // `_writableState` that would lead to infinite recursion.
15927 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
15928 return new Writable(options);
15929 }
15930
15931 this._writableState = new WritableState(options, this);
15932
15933 // legacy.
15934 this.writable = true;
15935
15936 if (options) {
15937 if (typeof options.write === 'function') this._write = options.write;
15938
15939 if (typeof options.writev === 'function') this._writev = options.writev;
15940
15941 if (typeof options.destroy === 'function') this._destroy = options.destroy;
15942
15943 if (typeof options.final === 'function') this._final = options.final;
15944 }
15945
15946 Stream.call(this);
15947}
15948
15949// Otherwise people can pipe Writable streams, which is just wrong.
15950Writable.prototype.pipe = function () {
15951 this.emit('error', new Error('Cannot pipe, not readable'));
15952};
15953
15954function writeAfterEnd(stream, cb) {
15955 var er = new Error('write after end');
15956 // TODO: defer error events consistently everywhere, not just the cb
15957 stream.emit('error', er);
15958 pna.nextTick(cb, er);
15959}
15960
15961// Checks that a user-supplied chunk is valid, especially for the particular
15962// mode the stream is in. Currently this means that `null` is never accepted
15963// and undefined/non-string values are only allowed in object mode.
15964function validChunk(stream, state, chunk, cb) {
15965 var valid = true;
15966 var er = false;
15967
15968 if (chunk === null) {
15969 er = new TypeError('May not write null values to stream');
15970 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15971 er = new TypeError('Invalid non-string/buffer chunk');
15972 }
15973 if (er) {
15974 stream.emit('error', er);
15975 pna.nextTick(cb, er);
15976 valid = false;
15977 }
15978 return valid;
15979}
15980
15981Writable.prototype.write = function (chunk, encoding, cb) {
15982 var state = this._writableState;
15983 var ret = false;
15984 var isBuf = !state.objectMode && _isUint8Array(chunk);
15985
15986 if (isBuf && !Buffer.isBuffer(chunk)) {
15987 chunk = _uint8ArrayToBuffer(chunk);
15988 }
15989
15990 if (typeof encoding === 'function') {
15991 cb = encoding;
15992 encoding = null;
15993 }
15994
15995 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
15996
15997 if (typeof cb !== 'function') cb = nop;
15998
15999 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
16000 state.pendingcb++;
16001 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
16002 }
16003
16004 return ret;
16005};
16006
16007Writable.prototype.cork = function () {
16008 var state = this._writableState;
16009
16010 state.corked++;
16011};
16012
16013Writable.prototype.uncork = function () {
16014 var state = this._writableState;
16015
16016 if (state.corked) {
16017 state.corked--;
16018
16019 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
16020 }
16021};
16022
16023Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
16024 // node::ParseEncoding() requires lower case.
16025 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
16026 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);
16027 this._writableState.defaultEncoding = encoding;
16028 return this;
16029};
16030
16031function decodeChunk(state, chunk, encoding) {
16032 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
16033 chunk = Buffer.from(chunk, encoding);
16034 }
16035 return chunk;
16036}
16037
16038Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
16039 // making it explicit this property is not enumerable
16040 // because otherwise some prototype manipulation in
16041 // userland will fail
16042 enumerable: false,
16043 get: function () {
16044 return this._writableState.highWaterMark;
16045 }
16046});
16047
16048// if we're already writing something, then just put this
16049// in the queue, and wait our turn. Otherwise, call _write
16050// If we return false, then we need a drain event, so set that flag.
16051function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
16052 if (!isBuf) {
16053 var newChunk = decodeChunk(state, chunk, encoding);
16054 if (chunk !== newChunk) {
16055 isBuf = true;
16056 encoding = 'buffer';
16057 chunk = newChunk;
16058 }
16059 }
16060 var len = state.objectMode ? 1 : chunk.length;
16061
16062 state.length += len;
16063
16064 var ret = state.length < state.highWaterMark;
16065 // we must ensure that previous needDrain will not be reset to false.
16066 if (!ret) state.needDrain = true;
16067
16068 if (state.writing || state.corked) {
16069 var last = state.lastBufferedRequest;
16070 state.lastBufferedRequest = {
16071 chunk: chunk,
16072 encoding: encoding,
16073 isBuf: isBuf,
16074 callback: cb,
16075 next: null
16076 };
16077 if (last) {
16078 last.next = state.lastBufferedRequest;
16079 } else {
16080 state.bufferedRequest = state.lastBufferedRequest;
16081 }
16082 state.bufferedRequestCount += 1;
16083 } else {
16084 doWrite(stream, state, false, len, chunk, encoding, cb);
16085 }
16086
16087 return ret;
16088}
16089
16090function doWrite(stream, state, writev, len, chunk, encoding, cb) {
16091 state.writelen = len;
16092 state.writecb = cb;
16093 state.writing = true;
16094 state.sync = true;
16095 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
16096 state.sync = false;
16097}
16098
16099function onwriteError(stream, state, sync, er, cb) {
16100 --state.pendingcb;
16101
16102 if (sync) {
16103 // defer the callback if we are being called synchronously
16104 // to avoid piling up things on the stack
16105 pna.nextTick(cb, er);
16106 // this can emit finish, and it will always happen
16107 // after error
16108 pna.nextTick(finishMaybe, stream, state);
16109 stream._writableState.errorEmitted = true;
16110 stream.emit('error', er);
16111 } else {
16112 // the caller expect this to happen before if
16113 // it is async
16114 cb(er);
16115 stream._writableState.errorEmitted = true;
16116 stream.emit('error', er);
16117 // this can emit finish, but finish must
16118 // always follow error
16119 finishMaybe(stream, state);
16120 }
16121}
16122
16123function onwriteStateUpdate(state) {
16124 state.writing = false;
16125 state.writecb = null;
16126 state.length -= state.writelen;
16127 state.writelen = 0;
16128}
16129
16130function onwrite(stream, er) {
16131 var state = stream._writableState;
16132 var sync = state.sync;
16133 var cb = state.writecb;
16134
16135 onwriteStateUpdate(state);
16136
16137 if (er) onwriteError(stream, state, sync, er, cb);else {
16138 // Check if we're actually ready to finish, but don't emit yet
16139 var finished = needFinish(state);
16140
16141 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
16142 clearBuffer(stream, state);
16143 }
16144
16145 if (sync) {
16146 /*<replacement>*/
16147 asyncWrite(afterWrite, stream, state, finished, cb);
16148 /*</replacement>*/
16149 } else {
16150 afterWrite(stream, state, finished, cb);
16151 }
16152 }
16153}
16154
16155function afterWrite(stream, state, finished, cb) {
16156 if (!finished) onwriteDrain(stream, state);
16157 state.pendingcb--;
16158 cb();
16159 finishMaybe(stream, state);
16160}
16161
16162// Must force callback to be called on nextTick, so that we don't
16163// emit 'drain' before the write() consumer gets the 'false' return
16164// value, and has a chance to attach a 'drain' listener.
16165function onwriteDrain(stream, state) {
16166 if (state.length === 0 && state.needDrain) {
16167 state.needDrain = false;
16168 stream.emit('drain');
16169 }
16170}
16171
16172// if there's something in the buffer waiting, then process it
16173function clearBuffer(stream, state) {
16174 state.bufferProcessing = true;
16175 var entry = state.bufferedRequest;
16176
16177 if (stream._writev && entry && entry.next) {
16178 // Fast case, write everything using _writev()
16179 var l = state.bufferedRequestCount;
16180 var buffer = new Array(l);
16181 var holder = state.corkedRequestsFree;
16182 holder.entry = entry;
16183
16184 var count = 0;
16185 var allBuffers = true;
16186 while (entry) {
16187 buffer[count] = entry;
16188 if (!entry.isBuf) allBuffers = false;
16189 entry = entry.next;
16190 count += 1;
16191 }
16192 buffer.allBuffers = allBuffers;
16193
16194 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
16195
16196 // doWrite is almost always async, defer these to save a bit of time
16197 // as the hot path ends with doWrite
16198 state.pendingcb++;
16199 state.lastBufferedRequest = null;
16200 if (holder.next) {
16201 state.corkedRequestsFree = holder.next;
16202 holder.next = null;
16203 } else {
16204 state.corkedRequestsFree = new CorkedRequest(state);
16205 }
16206 state.bufferedRequestCount = 0;
16207 } else {
16208 // Slow case, write chunks one-by-one
16209 while (entry) {
16210 var chunk = entry.chunk;
16211 var encoding = entry.encoding;
16212 var cb = entry.callback;
16213 var len = state.objectMode ? 1 : chunk.length;
16214
16215 doWrite(stream, state, false, len, chunk, encoding, cb);
16216 entry = entry.next;
16217 state.bufferedRequestCount--;
16218 // if we didn't call the onwrite immediately, then
16219 // it means that we need to wait until it does.
16220 // also, that means that the chunk and cb are currently
16221 // being processed, so move the buffer counter past them.
16222 if (state.writing) {
16223 break;
16224 }
16225 }
16226
16227 if (entry === null) state.lastBufferedRequest = null;
16228 }
16229
16230 state.bufferedRequest = entry;
16231 state.bufferProcessing = false;
16232}
16233
16234Writable.prototype._write = function (chunk, encoding, cb) {
16235 cb(new Error('_write() is not implemented'));
16236};
16237
16238Writable.prototype._writev = null;
16239
16240Writable.prototype.end = function (chunk, encoding, cb) {
16241 var state = this._writableState;
16242
16243 if (typeof chunk === 'function') {
16244 cb = chunk;
16245 chunk = null;
16246 encoding = null;
16247 } else if (typeof encoding === 'function') {
16248 cb = encoding;
16249 encoding = null;
16250 }
16251
16252 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
16253
16254 // .end() fully uncorks
16255 if (state.corked) {
16256 state.corked = 1;
16257 this.uncork();
16258 }
16259
16260 // ignore unnecessary end() calls.
16261 if (!state.ending && !state.finished) endWritable(this, state, cb);
16262};
16263
16264function needFinish(state) {
16265 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
16266}
16267function callFinal(stream, state) {
16268 stream._final(function (err) {
16269 state.pendingcb--;
16270 if (err) {
16271 stream.emit('error', err);
16272 }
16273 state.prefinished = true;
16274 stream.emit('prefinish');
16275 finishMaybe(stream, state);
16276 });
16277}
16278function prefinish(stream, state) {
16279 if (!state.prefinished && !state.finalCalled) {
16280 if (typeof stream._final === 'function') {
16281 state.pendingcb++;
16282 state.finalCalled = true;
16283 pna.nextTick(callFinal, stream, state);
16284 } else {
16285 state.prefinished = true;
16286 stream.emit('prefinish');
16287 }
16288 }
16289}
16290
16291function finishMaybe(stream, state) {
16292 var need = needFinish(state);
16293 if (need) {
16294 prefinish(stream, state);
16295 if (state.pendingcb === 0) {
16296 state.finished = true;
16297 stream.emit('finish');
16298 }
16299 }
16300 return need;
16301}
16302
16303function endWritable(stream, state, cb) {
16304 state.ending = true;
16305 finishMaybe(stream, state);
16306 if (cb) {
16307 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
16308 }
16309 state.ended = true;
16310 stream.writable = false;
16311}
16312
16313function onCorkedFinish(corkReq, state, err) {
16314 var entry = corkReq.entry;
16315 corkReq.entry = null;
16316 while (entry) {
16317 var cb = entry.callback;
16318 state.pendingcb--;
16319 cb(err);
16320 entry = entry.next;
16321 }
16322 if (state.corkedRequestsFree) {
16323 state.corkedRequestsFree.next = corkReq;
16324 } else {
16325 state.corkedRequestsFree = corkReq;
16326 }
16327}
16328
16329Object.defineProperty(Writable.prototype, 'destroyed', {
16330 get: function () {
16331 if (this._writableState === undefined) {
16332 return false;
16333 }
16334 return this._writableState.destroyed;
16335 },
16336 set: function (value) {
16337 // we ignore the value if the stream
16338 // has not been initialized yet
16339 if (!this._writableState) {
16340 return;
16341 }
16342
16343 // backward compatibility, the user is explicitly
16344 // managing destroyed
16345 this._writableState.destroyed = value;
16346 }
16347});
16348
16349Writable.prototype.destroy = destroyImpl.destroy;
16350Writable.prototype._undestroy = destroyImpl.undestroy;
16351Writable.prototype._destroy = function (err, cb) {
16352 this.end();
16353 cb(err);
16354};
16355}).call(this)}).call(this,_dereq_(73),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(119).setImmediate)
16356},{"100":100,"119":119,"121":121,"14":14,"37":37,"72":72,"73":73,"88":88,"94":94,"95":95}],93:[function(_dereq_,module,exports){
16357'use strict';
16358
16359function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16360
16361var Buffer = _dereq_(100).Buffer;
16362var util = _dereq_(11);
16363
16364function copyBuffer(src, target, offset) {
16365 src.copy(target, offset);
16366}
16367
16368module.exports = function () {
16369 function BufferList() {
16370 _classCallCheck(this, BufferList);
16371
16372 this.head = null;
16373 this.tail = null;
16374 this.length = 0;
16375 }
16376
16377 BufferList.prototype.push = function push(v) {
16378 var entry = { data: v, next: null };
16379 if (this.length > 0) this.tail.next = entry;else this.head = entry;
16380 this.tail = entry;
16381 ++this.length;
16382 };
16383
16384 BufferList.prototype.unshift = function unshift(v) {
16385 var entry = { data: v, next: this.head };
16386 if (this.length === 0) this.tail = entry;
16387 this.head = entry;
16388 ++this.length;
16389 };
16390
16391 BufferList.prototype.shift = function shift() {
16392 if (this.length === 0) return;
16393 var ret = this.head.data;
16394 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
16395 --this.length;
16396 return ret;
16397 };
16398
16399 BufferList.prototype.clear = function clear() {
16400 this.head = this.tail = null;
16401 this.length = 0;
16402 };
16403
16404 BufferList.prototype.join = function join(s) {
16405 if (this.length === 0) return '';
16406 var p = this.head;
16407 var ret = '' + p.data;
16408 while (p = p.next) {
16409 ret += s + p.data;
16410 }return ret;
16411 };
16412
16413 BufferList.prototype.concat = function concat(n) {
16414 if (this.length === 0) return Buffer.alloc(0);
16415 if (this.length === 1) return this.head.data;
16416 var ret = Buffer.allocUnsafe(n >>> 0);
16417 var p = this.head;
16418 var i = 0;
16419 while (p) {
16420 copyBuffer(p.data, ret, i);
16421 i += p.data.length;
16422 p = p.next;
16423 }
16424 return ret;
16425 };
16426
16427 return BufferList;
16428}();
16429
16430if (util && util.inspect && util.inspect.custom) {
16431 module.exports.prototype[util.inspect.custom] = function () {
16432 var obj = util.inspect({ length: this.length });
16433 return this.constructor.name + ' ' + obj;
16434 };
16435}
16436},{"100":100,"11":11}],94:[function(_dereq_,module,exports){
16437'use strict';
16438
16439/*<replacement>*/
16440
16441var pna = _dereq_(72);
16442/*</replacement>*/
16443
16444// undocumented cb() API, needed for core, not for public API
16445function destroy(err, cb) {
16446 var _this = this;
16447
16448 var readableDestroyed = this._readableState && this._readableState.destroyed;
16449 var writableDestroyed = this._writableState && this._writableState.destroyed;
16450
16451 if (readableDestroyed || writableDestroyed) {
16452 if (cb) {
16453 cb(err);
16454 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
16455 pna.nextTick(emitErrorNT, this, err);
16456 }
16457 return this;
16458 }
16459
16460 // we set destroyed to true before firing error callbacks in order
16461 // to make it re-entrance safe in case destroy() is called within callbacks
16462
16463 if (this._readableState) {
16464 this._readableState.destroyed = true;
16465 }
16466
16467 // if this is a duplex stream mark the writable part as destroyed as well
16468 if (this._writableState) {
16469 this._writableState.destroyed = true;
16470 }
16471
16472 this._destroy(err || null, function (err) {
16473 if (!cb && err) {
16474 pna.nextTick(emitErrorNT, _this, err);
16475 if (_this._writableState) {
16476 _this._writableState.errorEmitted = true;
16477 }
16478 } else if (cb) {
16479 cb(err);
16480 }
16481 });
16482
16483 return this;
16484}
16485
16486function undestroy() {
16487 if (this._readableState) {
16488 this._readableState.destroyed = false;
16489 this._readableState.reading = false;
16490 this._readableState.ended = false;
16491 this._readableState.endEmitted = false;
16492 }
16493
16494 if (this._writableState) {
16495 this._writableState.destroyed = false;
16496 this._writableState.ended = false;
16497 this._writableState.ending = false;
16498 this._writableState.finished = false;
16499 this._writableState.errorEmitted = false;
16500 }
16501}
16502
16503function emitErrorNT(self, err) {
16504 self.emit('error', err);
16505}
16506
16507module.exports = {
16508 destroy: destroy,
16509 undestroy: undestroy
16510};
16511},{"72":72}],95:[function(_dereq_,module,exports){
16512arguments[4][56][0].apply(exports,arguments)
16513},{"26":26,"56":56}],96:[function(_dereq_,module,exports){
16514module.exports = _dereq_(97).PassThrough
16515
16516},{"97":97}],97:[function(_dereq_,module,exports){
16517exports = module.exports = _dereq_(90);
16518exports.Stream = exports;
16519exports.Readable = exports;
16520exports.Writable = _dereq_(92);
16521exports.Duplex = _dereq_(88);
16522exports.Transform = _dereq_(91);
16523exports.PassThrough = _dereq_(89);
16524
16525},{"88":88,"89":89,"90":90,"91":91,"92":92}],98:[function(_dereq_,module,exports){
16526module.exports = _dereq_(97).Transform
16527
16528},{"97":97}],99:[function(_dereq_,module,exports){
16529module.exports = _dereq_(92);
16530
16531},{"92":92}],100:[function(_dereq_,module,exports){
16532/* eslint-disable node/no-deprecated-api */
16533var buffer = _dereq_(13)
16534var Buffer = buffer.Buffer
16535
16536// alternative to using Object.keys for old browsers
16537function copyProps (src, dst) {
16538 for (var key in src) {
16539 dst[key] = src[key]
16540 }
16541}
16542if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
16543 module.exports = buffer
16544} else {
16545 // Copy properties from require('buffer')
16546 copyProps(buffer, exports)
16547 exports.Buffer = SafeBuffer
16548}
16549
16550function SafeBuffer (arg, encodingOrOffset, length) {
16551 return Buffer(arg, encodingOrOffset, length)
16552}
16553
16554// Copy static methods from Buffer
16555copyProps(Buffer, SafeBuffer)
16556
16557SafeBuffer.from = function (arg, encodingOrOffset, length) {
16558 if (typeof arg === 'number') {
16559 throw new TypeError('Argument must not be a number')
16560 }
16561 return Buffer(arg, encodingOrOffset, length)
16562}
16563
16564SafeBuffer.alloc = function (size, fill, encoding) {
16565 if (typeof size !== 'number') {
16566 throw new TypeError('Argument must be a number')
16567 }
16568 var buf = Buffer(size)
16569 if (fill !== undefined) {
16570 if (typeof encoding === 'string') {
16571 buf.fill(fill, encoding)
16572 } else {
16573 buf.fill(fill)
16574 }
16575 } else {
16576 buf.fill(0)
16577 }
16578 return buf
16579}
16580
16581SafeBuffer.allocUnsafe = function (size) {
16582 if (typeof size !== 'number') {
16583 throw new TypeError('Argument must be a number')
16584 }
16585 return Buffer(size)
16586}
16587
16588SafeBuffer.allocUnsafeSlow = function (size) {
16589 if (typeof size !== 'number') {
16590 throw new TypeError('Argument must be a number')
16591 }
16592 return buffer.SlowBuffer(size)
16593}
16594
16595},{"13":13}],101:[function(_dereq_,module,exports){
16596// Copyright Joyent, Inc. and other Node contributors.
16597//
16598// Permission is hereby granted, free of charge, to any person obtaining a
16599// copy of this software and associated documentation files (the
16600// "Software"), to deal in the Software without restriction, including
16601// without limitation the rights to use, copy, modify, merge, publish,
16602// distribute, sublicense, and/or sell copies of the Software, and to permit
16603// persons to whom the Software is furnished to do so, subject to the
16604// following conditions:
16605//
16606// The above copyright notice and this permission notice shall be included
16607// in all copies or substantial portions of the Software.
16608//
16609// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16610// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16611// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16612// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16613// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16614// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16615// USE OR OTHER DEALINGS IN THE SOFTWARE.
16616
16617'use strict';
16618
16619/*<replacement>*/
16620
16621var Buffer = _dereq_(100).Buffer;
16622/*</replacement>*/
16623
16624var isEncoding = Buffer.isEncoding || function (encoding) {
16625 encoding = '' + encoding;
16626 switch (encoding && encoding.toLowerCase()) {
16627 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':
16628 return true;
16629 default:
16630 return false;
16631 }
16632};
16633
16634function _normalizeEncoding(enc) {
16635 if (!enc) return 'utf8';
16636 var retried;
16637 while (true) {
16638 switch (enc) {
16639 case 'utf8':
16640 case 'utf-8':
16641 return 'utf8';
16642 case 'ucs2':
16643 case 'ucs-2':
16644 case 'utf16le':
16645 case 'utf-16le':
16646 return 'utf16le';
16647 case 'latin1':
16648 case 'binary':
16649 return 'latin1';
16650 case 'base64':
16651 case 'ascii':
16652 case 'hex':
16653 return enc;
16654 default:
16655 if (retried) return; // undefined
16656 enc = ('' + enc).toLowerCase();
16657 retried = true;
16658 }
16659 }
16660};
16661
16662// Do not cache `Buffer.isEncoding` when checking encoding names as some
16663// modules monkey-patch it to support additional encodings
16664function normalizeEncoding(enc) {
16665 var nenc = _normalizeEncoding(enc);
16666 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16667 return nenc || enc;
16668}
16669
16670// StringDecoder provides an interface for efficiently splitting a series of
16671// buffers into a series of JS strings without breaking apart multi-byte
16672// characters.
16673exports.StringDecoder = StringDecoder;
16674function StringDecoder(encoding) {
16675 this.encoding = normalizeEncoding(encoding);
16676 var nb;
16677 switch (this.encoding) {
16678 case 'utf16le':
16679 this.text = utf16Text;
16680 this.end = utf16End;
16681 nb = 4;
16682 break;
16683 case 'utf8':
16684 this.fillLast = utf8FillLast;
16685 nb = 4;
16686 break;
16687 case 'base64':
16688 this.text = base64Text;
16689 this.end = base64End;
16690 nb = 3;
16691 break;
16692 default:
16693 this.write = simpleWrite;
16694 this.end = simpleEnd;
16695 return;
16696 }
16697 this.lastNeed = 0;
16698 this.lastTotal = 0;
16699 this.lastChar = Buffer.allocUnsafe(nb);
16700}
16701
16702StringDecoder.prototype.write = function (buf) {
16703 if (buf.length === 0) return '';
16704 var r;
16705 var i;
16706 if (this.lastNeed) {
16707 r = this.fillLast(buf);
16708 if (r === undefined) return '';
16709 i = this.lastNeed;
16710 this.lastNeed = 0;
16711 } else {
16712 i = 0;
16713 }
16714 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
16715 return r || '';
16716};
16717
16718StringDecoder.prototype.end = utf8End;
16719
16720// Returns only complete characters in a Buffer
16721StringDecoder.prototype.text = utf8Text;
16722
16723// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
16724StringDecoder.prototype.fillLast = function (buf) {
16725 if (this.lastNeed <= buf.length) {
16726 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
16727 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16728 }
16729 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
16730 this.lastNeed -= buf.length;
16731};
16732
16733// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
16734// continuation byte. If an invalid byte is detected, -2 is returned.
16735function utf8CheckByte(byte) {
16736 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;
16737 return byte >> 6 === 0x02 ? -1 : -2;
16738}
16739
16740// Checks at most 3 bytes at the end of a Buffer in order to detect an
16741// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
16742// needed to complete the UTF-8 character (if applicable) are returned.
16743function utf8CheckIncomplete(self, buf, i) {
16744 var j = buf.length - 1;
16745 if (j < i) return 0;
16746 var nb = utf8CheckByte(buf[j]);
16747 if (nb >= 0) {
16748 if (nb > 0) self.lastNeed = nb - 1;
16749 return nb;
16750 }
16751 if (--j < i || nb === -2) return 0;
16752 nb = utf8CheckByte(buf[j]);
16753 if (nb >= 0) {
16754 if (nb > 0) self.lastNeed = nb - 2;
16755 return nb;
16756 }
16757 if (--j < i || nb === -2) return 0;
16758 nb = utf8CheckByte(buf[j]);
16759 if (nb >= 0) {
16760 if (nb > 0) {
16761 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
16762 }
16763 return nb;
16764 }
16765 return 0;
16766}
16767
16768// Validates as many continuation bytes for a multi-byte UTF-8 character as
16769// needed or are available. If we see a non-continuation byte where we expect
16770// one, we "replace" the validated continuation bytes we've seen so far with
16771// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
16772// behavior. The continuation byte check is included three times in the case
16773// where all of the continuation bytes for a character exist in the same buffer.
16774// It is also done this way as a slight performance increase instead of using a
16775// loop.
16776function utf8CheckExtraBytes(self, buf, p) {
16777 if ((buf[0] & 0xC0) !== 0x80) {
16778 self.lastNeed = 0;
16779 return '\ufffd';
16780 }
16781 if (self.lastNeed > 1 && buf.length > 1) {
16782 if ((buf[1] & 0xC0) !== 0x80) {
16783 self.lastNeed = 1;
16784 return '\ufffd';
16785 }
16786 if (self.lastNeed > 2 && buf.length > 2) {
16787 if ((buf[2] & 0xC0) !== 0x80) {
16788 self.lastNeed = 2;
16789 return '\ufffd';
16790 }
16791 }
16792 }
16793}
16794
16795// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
16796function utf8FillLast(buf) {
16797 var p = this.lastTotal - this.lastNeed;
16798 var r = utf8CheckExtraBytes(this, buf, p);
16799 if (r !== undefined) return r;
16800 if (this.lastNeed <= buf.length) {
16801 buf.copy(this.lastChar, p, 0, this.lastNeed);
16802 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16803 }
16804 buf.copy(this.lastChar, p, 0, buf.length);
16805 this.lastNeed -= buf.length;
16806}
16807
16808// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
16809// partial character, the character's bytes are buffered until the required
16810// number of bytes are available.
16811function utf8Text(buf, i) {
16812 var total = utf8CheckIncomplete(this, buf, i);
16813 if (!this.lastNeed) return buf.toString('utf8', i);
16814 this.lastTotal = total;
16815 var end = buf.length - (total - this.lastNeed);
16816 buf.copy(this.lastChar, 0, end);
16817 return buf.toString('utf8', i, end);
16818}
16819
16820// For UTF-8, a replacement character is added when ending on a partial
16821// character.
16822function utf8End(buf) {
16823 var r = buf && buf.length ? this.write(buf) : '';
16824 if (this.lastNeed) return r + '\ufffd';
16825 return r;
16826}
16827
16828// UTF-16LE typically needs two bytes per character, but even if we have an even
16829// number of bytes available, we need to check if we end on a leading/high
16830// surrogate. In that case, we need to wait for the next two bytes in order to
16831// decode the last character properly.
16832function utf16Text(buf, i) {
16833 if ((buf.length - i) % 2 === 0) {
16834 var r = buf.toString('utf16le', i);
16835 if (r) {
16836 var c = r.charCodeAt(r.length - 1);
16837 if (c >= 0xD800 && c <= 0xDBFF) {
16838 this.lastNeed = 2;
16839 this.lastTotal = 4;
16840 this.lastChar[0] = buf[buf.length - 2];
16841 this.lastChar[1] = buf[buf.length - 1];
16842 return r.slice(0, -1);
16843 }
16844 }
16845 return r;
16846 }
16847 this.lastNeed = 1;
16848 this.lastTotal = 2;
16849 this.lastChar[0] = buf[buf.length - 1];
16850 return buf.toString('utf16le', i, buf.length - 1);
16851}
16852
16853// For UTF-16LE we do not explicitly append special replacement characters if we
16854// end on a partial character, we simply let v8 handle that.
16855function utf16End(buf) {
16856 var r = buf && buf.length ? this.write(buf) : '';
16857 if (this.lastNeed) {
16858 var end = this.lastTotal - this.lastNeed;
16859 return r + this.lastChar.toString('utf16le', 0, end);
16860 }
16861 return r;
16862}
16863
16864function base64Text(buf, i) {
16865 var n = (buf.length - i) % 3;
16866 if (n === 0) return buf.toString('base64', i);
16867 this.lastNeed = 3 - n;
16868 this.lastTotal = 3;
16869 if (n === 1) {
16870 this.lastChar[0] = buf[buf.length - 1];
16871 } else {
16872 this.lastChar[0] = buf[buf.length - 2];
16873 this.lastChar[1] = buf[buf.length - 1];
16874 }
16875 return buf.toString('base64', i, buf.length - n);
16876}
16877
16878function base64End(buf) {
16879 var r = buf && buf.length ? this.write(buf) : '';
16880 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
16881 return r;
16882}
16883
16884// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
16885function simpleWrite(buf) {
16886 return buf.toString(this.encoding);
16887}
16888
16889function simpleEnd(buf) {
16890 return buf && buf.length ? this.write(buf) : '';
16891}
16892},{"100":100}],102:[function(_dereq_,module,exports){
16893arguments[4][101][0].apply(exports,arguments)
16894},{"101":101,"83":83}],103:[function(_dereq_,module,exports){
16895arguments[4][43][0].apply(exports,arguments)
16896},{"43":43}],104:[function(_dereq_,module,exports){
16897arguments[4][44][0].apply(exports,arguments)
16898},{"106":106,"108":108,"37":37,"44":44,"73":73}],105:[function(_dereq_,module,exports){
16899arguments[4][45][0].apply(exports,arguments)
16900},{"107":107,"37":37,"45":45}],106:[function(_dereq_,module,exports){
16901arguments[4][46][0].apply(exports,arguments)
16902},{"102":102,"103":103,"104":104,"109":109,"11":11,"110":110,"111":111,"113":113,"115":115,"116":116,"13":13,"26":26,"37":37,"46":46,"73":73}],107:[function(_dereq_,module,exports){
16903arguments[4][47][0].apply(exports,arguments)
16904},{"103":103,"104":104,"37":37,"47":47}],108:[function(_dereq_,module,exports){
16905arguments[4][48][0].apply(exports,arguments)
16906},{"103":103,"104":104,"111":111,"115":115,"116":116,"121":121,"13":13,"37":37,"48":48,"73":73}],109:[function(_dereq_,module,exports){
16907arguments[4][49][0].apply(exports,arguments)
16908},{"112":112,"49":49,"73":73}],110:[function(_dereq_,module,exports){
16909arguments[4][50][0].apply(exports,arguments)
16910},{"11":11,"13":13,"50":50}],111:[function(_dereq_,module,exports){
16911arguments[4][51][0].apply(exports,arguments)
16912},{"51":51,"73":73}],112:[function(_dereq_,module,exports){
16913arguments[4][52][0].apply(exports,arguments)
16914},{"103":103,"52":52}],113:[function(_dereq_,module,exports){
16915arguments[4][53][0].apply(exports,arguments)
16916},{"53":53}],114:[function(_dereq_,module,exports){
16917arguments[4][54][0].apply(exports,arguments)
16918},{"103":103,"112":112,"54":54}],115:[function(_dereq_,module,exports){
16919arguments[4][55][0].apply(exports,arguments)
16920},{"103":103,"55":55}],116:[function(_dereq_,module,exports){
16921arguments[4][56][0].apply(exports,arguments)
16922},{"26":26,"56":56}],117:[function(_dereq_,module,exports){
16923arguments[4][57][0].apply(exports,arguments)
16924},{"104":104,"105":105,"106":106,"107":107,"108":108,"112":112,"114":114,"57":57}],118:[function(_dereq_,module,exports){
16925(function (process){(function (){
16926var Transform = _dereq_(117).Transform
16927 , inherits = _dereq_(37)
16928
16929function DestroyableTransform(opts) {
16930 Transform.call(this, opts)
16931 this._destroyed = false
16932}
16933
16934inherits(DestroyableTransform, Transform)
16935
16936DestroyableTransform.prototype.destroy = function(err) {
16937 if (this._destroyed) return
16938 this._destroyed = true
16939
16940 var self = this
16941 process.nextTick(function() {
16942 if (err)
16943 self.emit('error', err)
16944 self.emit('close')
16945 })
16946}
16947
16948// a noop _transform function
16949function noop (chunk, enc, callback) {
16950 callback(null, chunk)
16951}
16952
16953
16954// create a new export function, used by both the main export and
16955// the .ctor export, contains common logic for dealing with arguments
16956function through2 (construct) {
16957 return function (options, transform, flush) {
16958 if (typeof options == 'function') {
16959 flush = transform
16960 transform = options
16961 options = {}
16962 }
16963
16964 if (typeof transform != 'function')
16965 transform = noop
16966
16967 if (typeof flush != 'function')
16968 flush = null
16969
16970 return construct(options, transform, flush)
16971 }
16972}
16973
16974
16975// main export, just make me a transform stream!
16976module.exports = through2(function (options, transform, flush) {
16977 var t2 = new DestroyableTransform(options)
16978
16979 t2._transform = transform
16980
16981 if (flush)
16982 t2._flush = flush
16983
16984 return t2
16985})
16986
16987
16988// make me a reusable prototype that I can `new`, or implicitly `new`
16989// with a constructor call
16990module.exports.ctor = through2(function (options, transform, flush) {
16991 function Through2 (override) {
16992 if (!(this instanceof Through2))
16993 return new Through2(override)
16994
16995 this.options = Object.assign({}, options, override)
16996
16997 DestroyableTransform.call(this, this.options)
16998 }
16999
17000 inherits(Through2, DestroyableTransform)
17001
17002 Through2.prototype._transform = transform
17003
17004 if (flush)
17005 Through2.prototype._flush = flush
17006
17007 return Through2
17008})
17009
17010
17011module.exports.obj = through2(function (options, transform, flush) {
17012 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
17013
17014 t2._transform = transform
17015
17016 if (flush)
17017 t2._flush = flush
17018
17019 return t2
17020})
17021
17022}).call(this)}).call(this,_dereq_(73))
17023},{"117":117,"37":37,"73":73}],119:[function(_dereq_,module,exports){
17024(function (setImmediate,clearImmediate){(function (){
17025var nextTick = _dereq_(73).nextTick;
17026var apply = Function.prototype.apply;
17027var slice = Array.prototype.slice;
17028var immediateIds = {};
17029var nextImmediateId = 0;
17030
17031// DOM APIs, for completeness
17032
17033exports.setTimeout = function() {
17034 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
17035};
17036exports.setInterval = function() {
17037 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
17038};
17039exports.clearTimeout =
17040exports.clearInterval = function(timeout) { timeout.close(); };
17041
17042function Timeout(id, clearFn) {
17043 this._id = id;
17044 this._clearFn = clearFn;
17045}
17046Timeout.prototype.unref = Timeout.prototype.ref = function() {};
17047Timeout.prototype.close = function() {
17048 this._clearFn.call(window, this._id);
17049};
17050
17051// Does not start the time, just sets up the members needed.
17052exports.enroll = function(item, msecs) {
17053 clearTimeout(item._idleTimeoutId);
17054 item._idleTimeout = msecs;
17055};
17056
17057exports.unenroll = function(item) {
17058 clearTimeout(item._idleTimeoutId);
17059 item._idleTimeout = -1;
17060};
17061
17062exports._unrefActive = exports.active = function(item) {
17063 clearTimeout(item._idleTimeoutId);
17064
17065 var msecs = item._idleTimeout;
17066 if (msecs >= 0) {
17067 item._idleTimeoutId = setTimeout(function onTimeout() {
17068 if (item._onTimeout)
17069 item._onTimeout();
17070 }, msecs);
17071 }
17072};
17073
17074// That's not how node.js implements it but the exposed api is the same.
17075exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
17076 var id = nextImmediateId++;
17077 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
17078
17079 immediateIds[id] = true;
17080
17081 nextTick(function onNextTick() {
17082 if (immediateIds[id]) {
17083 // fn.call() is faster so we optimize for the common use-case
17084 // @see http://jsperf.com/call-apply-segu
17085 if (args) {
17086 fn.apply(null, args);
17087 } else {
17088 fn.call(null);
17089 }
17090 // Prevent ids from leaking
17091 exports.clearImmediate(id);
17092 }
17093 });
17094
17095 return id;
17096};
17097
17098exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
17099 delete immediateIds[id];
17100};
17101}).call(this)}).call(this,_dereq_(119).setImmediate,_dereq_(119).clearImmediate)
17102},{"119":119,"73":73}],120:[function(_dereq_,module,exports){
17103'use strict';
17104
17105// Simple FIFO queue implementation to avoid having to do shift()
17106// on an array, which is slow.
17107
17108function Queue() {
17109 this.length = 0;
17110}
17111
17112Queue.prototype.push = function (item) {
17113 var node = {item: item};
17114 if (this.last) {
17115 this.last = this.last.next = node;
17116 } else {
17117 this.last = this.first = node;
17118 }
17119 this.length++;
17120};
17121
17122Queue.prototype.shift = function () {
17123 var node = this.first;
17124 if (node) {
17125 this.first = node.next;
17126 if (!(--this.length)) {
17127 this.last = undefined;
17128 }
17129 return node.item;
17130 }
17131};
17132
17133Queue.prototype.slice = function (start, end) {
17134 start = typeof start === 'undefined' ? 0 : start;
17135 end = typeof end === 'undefined' ? Infinity : end;
17136
17137 var output = [];
17138
17139 var i = 0;
17140 for (var node = this.first; node; node = node.next) {
17141 if (--end < 0) {
17142 break;
17143 } else if (++i > start) {
17144 output.push(node.item);
17145 }
17146 }
17147 return output;
17148}
17149
17150module.exports = Queue;
17151
17152},{}],121:[function(_dereq_,module,exports){
17153(function (global){(function (){
17154
17155/**
17156 * Module exports.
17157 */
17158
17159module.exports = deprecate;
17160
17161/**
17162 * Mark that a method should not be used.
17163 * Returns a modified function which warns once by default.
17164 *
17165 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
17166 *
17167 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
17168 * will throw an Error when invoked.
17169 *
17170 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
17171 * will invoke `console.trace()` instead of `console.error()`.
17172 *
17173 * @param {Function} fn - the function to deprecate
17174 * @param {String} msg - the string to print to the console when `fn` is invoked
17175 * @returns {Function} a new "deprecated" version of `fn`
17176 * @api public
17177 */
17178
17179function deprecate (fn, msg) {
17180 if (config('noDeprecation')) {
17181 return fn;
17182 }
17183
17184 var warned = false;
17185 function deprecated() {
17186 if (!warned) {
17187 if (config('throwDeprecation')) {
17188 throw new Error(msg);
17189 } else if (config('traceDeprecation')) {
17190 console.trace(msg);
17191 } else {
17192 console.warn(msg);
17193 }
17194 warned = true;
17195 }
17196 return fn.apply(this, arguments);
17197 }
17198
17199 return deprecated;
17200}
17201
17202/**
17203 * Checks `localStorage` for boolean values for the given `name`.
17204 *
17205 * @param {String} name
17206 * @returns {Boolean}
17207 * @api private
17208 */
17209
17210function config (name) {
17211 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
17212 try {
17213 if (!global.localStorage) return false;
17214 } catch (_) {
17215 return false;
17216 }
17217 var val = global.localStorage[name];
17218 if (null == val) return false;
17219 return String(val).toLowerCase() === 'true';
17220}
17221
17222}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17223},{}],122:[function(_dereq_,module,exports){
17224arguments[4][7][0].apply(exports,arguments)
17225},{"7":7}],123:[function(_dereq_,module,exports){
17226arguments[4][8][0].apply(exports,arguments)
17227},{"8":8}],124:[function(_dereq_,module,exports){
17228arguments[4][9][0].apply(exports,arguments)
17229},{"122":122,"123":123,"73":73,"9":9}],125:[function(_dereq_,module,exports){
17230"use strict";
17231
17232Object.defineProperty(exports, "__esModule", {
17233 value: true
17234});
17235Object.defineProperty(exports, "v1", {
17236 enumerable: true,
17237 get: function () {
17238 return _v.default;
17239 }
17240});
17241Object.defineProperty(exports, "v3", {
17242 enumerable: true,
17243 get: function () {
17244 return _v2.default;
17245 }
17246});
17247Object.defineProperty(exports, "v4", {
17248 enumerable: true,
17249 get: function () {
17250 return _v3.default;
17251 }
17252});
17253Object.defineProperty(exports, "v5", {
17254 enumerable: true,
17255 get: function () {
17256 return _v4.default;
17257 }
17258});
17259Object.defineProperty(exports, "NIL", {
17260 enumerable: true,
17261 get: function () {
17262 return _nil.default;
17263 }
17264});
17265Object.defineProperty(exports, "version", {
17266 enumerable: true,
17267 get: function () {
17268 return _version.default;
17269 }
17270});
17271Object.defineProperty(exports, "validate", {
17272 enumerable: true,
17273 get: function () {
17274 return _validate.default;
17275 }
17276});
17277Object.defineProperty(exports, "stringify", {
17278 enumerable: true,
17279 get: function () {
17280 return _stringify.default;
17281 }
17282});
17283Object.defineProperty(exports, "parse", {
17284 enumerable: true,
17285 get: function () {
17286 return _parse.default;
17287 }
17288});
17289
17290var _v = _interopRequireDefault(_dereq_(133));
17291
17292var _v2 = _interopRequireDefault(_dereq_(134));
17293
17294var _v3 = _interopRequireDefault(_dereq_(136));
17295
17296var _v4 = _interopRequireDefault(_dereq_(137));
17297
17298var _nil = _interopRequireDefault(_dereq_(127));
17299
17300var _version = _interopRequireDefault(_dereq_(139));
17301
17302var _validate = _interopRequireDefault(_dereq_(138));
17303
17304var _stringify = _interopRequireDefault(_dereq_(132));
17305
17306var _parse = _interopRequireDefault(_dereq_(128));
17307
17308function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17309},{"127":127,"128":128,"132":132,"133":133,"134":134,"136":136,"137":137,"138":138,"139":139}],126:[function(_dereq_,module,exports){
17310"use strict";
17311
17312Object.defineProperty(exports, "__esModule", {
17313 value: true
17314});
17315exports.default = void 0;
17316
17317/*
17318 * Browser-compatible JavaScript MD5
17319 *
17320 * Modification of JavaScript MD5
17321 * https://github.com/blueimp/JavaScript-MD5
17322 *
17323 * Copyright 2011, Sebastian Tschan
17324 * https://blueimp.net
17325 *
17326 * Licensed under the MIT license:
17327 * https://opensource.org/licenses/MIT
17328 *
17329 * Based on
17330 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
17331 * Digest Algorithm, as defined in RFC 1321.
17332 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
17333 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
17334 * Distributed under the BSD License
17335 * See http://pajhome.org.uk/crypt/md5 for more info.
17336 */
17337function md5(bytes) {
17338 if (typeof bytes === 'string') {
17339 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
17340
17341 bytes = new Uint8Array(msg.length);
17342
17343 for (let i = 0; i < msg.length; ++i) {
17344 bytes[i] = msg.charCodeAt(i);
17345 }
17346 }
17347
17348 return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
17349}
17350/*
17351 * Convert an array of little-endian words to an array of bytes
17352 */
17353
17354
17355function md5ToHexEncodedArray(input) {
17356 const output = [];
17357 const length32 = input.length * 32;
17358 const hexTab = '0123456789abcdef';
17359
17360 for (let i = 0; i < length32; i += 8) {
17361 const x = input[i >> 5] >>> i % 32 & 0xff;
17362 const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
17363 output.push(hex);
17364 }
17365
17366 return output;
17367}
17368/**
17369 * Calculate output length with padding and bit length
17370 */
17371
17372
17373function getOutputLength(inputLength8) {
17374 return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
17375}
17376/*
17377 * Calculate the MD5 of an array of little-endian words, and a bit length.
17378 */
17379
17380
17381function wordsToMd5(x, len) {
17382 /* append padding */
17383 x[len >> 5] |= 0x80 << len % 32;
17384 x[getOutputLength(len) - 1] = len;
17385 let a = 1732584193;
17386 let b = -271733879;
17387 let c = -1732584194;
17388 let d = 271733878;
17389
17390 for (let i = 0; i < x.length; i += 16) {
17391 const olda = a;
17392 const oldb = b;
17393 const oldc = c;
17394 const oldd = d;
17395 a = md5ff(a, b, c, d, x[i], 7, -680876936);
17396 d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
17397 c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
17398 b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
17399 a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
17400 d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
17401 c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
17402 b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
17403 a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
17404 d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
17405 c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
17406 b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
17407 a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
17408 d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
17409 c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
17410 b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
17411 a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
17412 d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
17413 c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
17414 b = md5gg(b, c, d, a, x[i], 20, -373897302);
17415 a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
17416 d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
17417 c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
17418 b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
17419 a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
17420 d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
17421 c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
17422 b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
17423 a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
17424 d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
17425 c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
17426 b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
17427 a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
17428 d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
17429 c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
17430 b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
17431 a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
17432 d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
17433 c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
17434 b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
17435 a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
17436 d = md5hh(d, a, b, c, x[i], 11, -358537222);
17437 c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
17438 b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
17439 a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
17440 d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
17441 c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
17442 b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
17443 a = md5ii(a, b, c, d, x[i], 6, -198630844);
17444 d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
17445 c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
17446 b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
17447 a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
17448 d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
17449 c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
17450 b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
17451 a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
17452 d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
17453 c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
17454 b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
17455 a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
17456 d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
17457 c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
17458 b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
17459 a = safeAdd(a, olda);
17460 b = safeAdd(b, oldb);
17461 c = safeAdd(c, oldc);
17462 d = safeAdd(d, oldd);
17463 }
17464
17465 return [a, b, c, d];
17466}
17467/*
17468 * Convert an array bytes to an array of little-endian words
17469 * Characters >255 have their high-byte silently ignored.
17470 */
17471
17472
17473function bytesToWords(input) {
17474 if (input.length === 0) {
17475 return [];
17476 }
17477
17478 const length8 = input.length * 8;
17479 const output = new Uint32Array(getOutputLength(length8));
17480
17481 for (let i = 0; i < length8; i += 8) {
17482 output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
17483 }
17484
17485 return output;
17486}
17487/*
17488 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
17489 * to work around bugs in some JS interpreters.
17490 */
17491
17492
17493function safeAdd(x, y) {
17494 const lsw = (x & 0xffff) + (y & 0xffff);
17495 const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
17496 return msw << 16 | lsw & 0xffff;
17497}
17498/*
17499 * Bitwise rotate a 32-bit number to the left.
17500 */
17501
17502
17503function bitRotateLeft(num, cnt) {
17504 return num << cnt | num >>> 32 - cnt;
17505}
17506/*
17507 * These functions implement the four basic operations the algorithm uses.
17508 */
17509
17510
17511function md5cmn(q, a, b, x, s, t) {
17512 return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
17513}
17514
17515function md5ff(a, b, c, d, x, s, t) {
17516 return md5cmn(b & c | ~b & d, a, b, x, s, t);
17517}
17518
17519function md5gg(a, b, c, d, x, s, t) {
17520 return md5cmn(b & d | c & ~d, a, b, x, s, t);
17521}
17522
17523function md5hh(a, b, c, d, x, s, t) {
17524 return md5cmn(b ^ c ^ d, a, b, x, s, t);
17525}
17526
17527function md5ii(a, b, c, d, x, s, t) {
17528 return md5cmn(c ^ (b | ~d), a, b, x, s, t);
17529}
17530
17531var _default = md5;
17532exports.default = _default;
17533},{}],127:[function(_dereq_,module,exports){
17534"use strict";
17535
17536Object.defineProperty(exports, "__esModule", {
17537 value: true
17538});
17539exports.default = void 0;
17540var _default = '00000000-0000-0000-0000-000000000000';
17541exports.default = _default;
17542},{}],128:[function(_dereq_,module,exports){
17543"use strict";
17544
17545Object.defineProperty(exports, "__esModule", {
17546 value: true
17547});
17548exports.default = void 0;
17549
17550var _validate = _interopRequireDefault(_dereq_(138));
17551
17552function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17553
17554function parse(uuid) {
17555 if (!(0, _validate.default)(uuid)) {
17556 throw TypeError('Invalid UUID');
17557 }
17558
17559 let v;
17560 const arr = new Uint8Array(16); // Parse ########-....-....-....-............
17561
17562 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
17563 arr[1] = v >>> 16 & 0xff;
17564 arr[2] = v >>> 8 & 0xff;
17565 arr[3] = v & 0xff; // Parse ........-####-....-....-............
17566
17567 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
17568 arr[5] = v & 0xff; // Parse ........-....-####-....-............
17569
17570 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
17571 arr[7] = v & 0xff; // Parse ........-....-....-####-............
17572
17573 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
17574 arr[9] = v & 0xff; // Parse ........-....-....-....-############
17575 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
17576
17577 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
17578 arr[11] = v / 0x100000000 & 0xff;
17579 arr[12] = v >>> 24 & 0xff;
17580 arr[13] = v >>> 16 & 0xff;
17581 arr[14] = v >>> 8 & 0xff;
17582 arr[15] = v & 0xff;
17583 return arr;
17584}
17585
17586var _default = parse;
17587exports.default = _default;
17588},{"138":138}],129:[function(_dereq_,module,exports){
17589"use strict";
17590
17591Object.defineProperty(exports, "__esModule", {
17592 value: true
17593});
17594exports.default = void 0;
17595var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
17596exports.default = _default;
17597},{}],130:[function(_dereq_,module,exports){
17598"use strict";
17599
17600Object.defineProperty(exports, "__esModule", {
17601 value: true
17602});
17603exports.default = rng;
17604// Unique ID creation requires a high quality random # generator. In the browser we therefore
17605// require the crypto API and do not support built-in fallback to lower quality random number
17606// generators (like Math.random()).
17607let getRandomValues;
17608const rnds8 = new Uint8Array(16);
17609
17610function rng() {
17611 // lazy load so that environments that need to polyfill have a chance to do so
17612 if (!getRandomValues) {
17613 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
17614 // find the complete implementation of crypto (msCrypto) on IE11.
17615 getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
17616
17617 if (!getRandomValues) {
17618 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
17619 }
17620 }
17621
17622 return getRandomValues(rnds8);
17623}
17624},{}],131:[function(_dereq_,module,exports){
17625"use strict";
17626
17627Object.defineProperty(exports, "__esModule", {
17628 value: true
17629});
17630exports.default = void 0;
17631
17632// Adapted from Chris Veness' SHA1 code at
17633// http://www.movable-type.co.uk/scripts/sha1.html
17634function f(s, x, y, z) {
17635 switch (s) {
17636 case 0:
17637 return x & y ^ ~x & z;
17638
17639 case 1:
17640 return x ^ y ^ z;
17641
17642 case 2:
17643 return x & y ^ x & z ^ y & z;
17644
17645 case 3:
17646 return x ^ y ^ z;
17647 }
17648}
17649
17650function ROTL(x, n) {
17651 return x << n | x >>> 32 - n;
17652}
17653
17654function sha1(bytes) {
17655 const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
17656 const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
17657
17658 if (typeof bytes === 'string') {
17659 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
17660
17661 bytes = [];
17662
17663 for (let i = 0; i < msg.length; ++i) {
17664 bytes.push(msg.charCodeAt(i));
17665 }
17666 } else if (!Array.isArray(bytes)) {
17667 // Convert Array-like to Array
17668 bytes = Array.prototype.slice.call(bytes);
17669 }
17670
17671 bytes.push(0x80);
17672 const l = bytes.length / 4 + 2;
17673 const N = Math.ceil(l / 16);
17674 const M = new Array(N);
17675
17676 for (let i = 0; i < N; ++i) {
17677 const arr = new Uint32Array(16);
17678
17679 for (let j = 0; j < 16; ++j) {
17680 arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
17681 }
17682
17683 M[i] = arr;
17684 }
17685
17686 M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
17687 M[N - 1][14] = Math.floor(M[N - 1][14]);
17688 M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
17689
17690 for (let i = 0; i < N; ++i) {
17691 const W = new Uint32Array(80);
17692
17693 for (let t = 0; t < 16; ++t) {
17694 W[t] = M[i][t];
17695 }
17696
17697 for (let t = 16; t < 80; ++t) {
17698 W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
17699 }
17700
17701 let a = H[0];
17702 let b = H[1];
17703 let c = H[2];
17704 let d = H[3];
17705 let e = H[4];
17706
17707 for (let t = 0; t < 80; ++t) {
17708 const s = Math.floor(t / 20);
17709 const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
17710 e = d;
17711 d = c;
17712 c = ROTL(b, 30) >>> 0;
17713 b = a;
17714 a = T;
17715 }
17716
17717 H[0] = H[0] + a >>> 0;
17718 H[1] = H[1] + b >>> 0;
17719 H[2] = H[2] + c >>> 0;
17720 H[3] = H[3] + d >>> 0;
17721 H[4] = H[4] + e >>> 0;
17722 }
17723
17724 return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
17725}
17726
17727var _default = sha1;
17728exports.default = _default;
17729},{}],132:[function(_dereq_,module,exports){
17730"use strict";
17731
17732Object.defineProperty(exports, "__esModule", {
17733 value: true
17734});
17735exports.default = void 0;
17736
17737var _validate = _interopRequireDefault(_dereq_(138));
17738
17739function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17740
17741/**
17742 * Convert array of 16 byte values to UUID string format of the form:
17743 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
17744 */
17745const byteToHex = [];
17746
17747for (let i = 0; i < 256; ++i) {
17748 byteToHex.push((i + 0x100).toString(16).substr(1));
17749}
17750
17751function stringify(arr, offset = 0) {
17752 // Note: Be careful editing this code! It's been tuned for performance
17753 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
17754 const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
17755 // of the following:
17756 // - One or more input array values don't map to a hex octet (leading to
17757 // "undefined" in the uuid)
17758 // - Invalid input values for the RFC `version` or `variant` fields
17759
17760 if (!(0, _validate.default)(uuid)) {
17761 throw TypeError('Stringified UUID is invalid');
17762 }
17763
17764 return uuid;
17765}
17766
17767var _default = stringify;
17768exports.default = _default;
17769},{"138":138}],133:[function(_dereq_,module,exports){
17770"use strict";
17771
17772Object.defineProperty(exports, "__esModule", {
17773 value: true
17774});
17775exports.default = void 0;
17776
17777var _rng = _interopRequireDefault(_dereq_(130));
17778
17779var _stringify = _interopRequireDefault(_dereq_(132));
17780
17781function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17782
17783// **`v1()` - Generate time-based UUID**
17784//
17785// Inspired by https://github.com/LiosK/UUID.js
17786// and http://docs.python.org/library/uuid.html
17787let _nodeId;
17788
17789let _clockseq; // Previous uuid creation time
17790
17791
17792let _lastMSecs = 0;
17793let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
17794
17795function v1(options, buf, offset) {
17796 let i = buf && offset || 0;
17797 const b = buf || new Array(16);
17798 options = options || {};
17799 let node = options.node || _nodeId;
17800 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
17801 // specified. We do this lazily to minimize issues related to insufficient
17802 // system entropy. See #189
17803
17804 if (node == null || clockseq == null) {
17805 const seedBytes = options.random || (options.rng || _rng.default)();
17806
17807 if (node == null) {
17808 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
17809 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
17810 }
17811
17812 if (clockseq == null) {
17813 // Per 4.2.2, randomize (14 bit) clockseq
17814 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
17815 }
17816 } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
17817 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
17818 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
17819 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
17820
17821
17822 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
17823 // cycle to simulate higher resolution clock
17824
17825 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
17826
17827 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
17828
17829 if (dt < 0 && options.clockseq === undefined) {
17830 clockseq = clockseq + 1 & 0x3fff;
17831 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
17832 // time interval
17833
17834
17835 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
17836 nsecs = 0;
17837 } // Per 4.2.1.2 Throw error if too many uuids are requested
17838
17839
17840 if (nsecs >= 10000) {
17841 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
17842 }
17843
17844 _lastMSecs = msecs;
17845 _lastNSecs = nsecs;
17846 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
17847
17848 msecs += 12219292800000; // `time_low`
17849
17850 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
17851 b[i++] = tl >>> 24 & 0xff;
17852 b[i++] = tl >>> 16 & 0xff;
17853 b[i++] = tl >>> 8 & 0xff;
17854 b[i++] = tl & 0xff; // `time_mid`
17855
17856 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
17857 b[i++] = tmh >>> 8 & 0xff;
17858 b[i++] = tmh & 0xff; // `time_high_and_version`
17859
17860 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
17861
17862 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
17863
17864 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
17865
17866 b[i++] = clockseq & 0xff; // `node`
17867
17868 for (let n = 0; n < 6; ++n) {
17869 b[i + n] = node[n];
17870 }
17871
17872 return buf || (0, _stringify.default)(b);
17873}
17874
17875var _default = v1;
17876exports.default = _default;
17877},{"130":130,"132":132}],134:[function(_dereq_,module,exports){
17878"use strict";
17879
17880Object.defineProperty(exports, "__esModule", {
17881 value: true
17882});
17883exports.default = void 0;
17884
17885var _v = _interopRequireDefault(_dereq_(135));
17886
17887var _md = _interopRequireDefault(_dereq_(126));
17888
17889function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17890
17891const v3 = (0, _v.default)('v3', 0x30, _md.default);
17892var _default = v3;
17893exports.default = _default;
17894},{"126":126,"135":135}],135:[function(_dereq_,module,exports){
17895"use strict";
17896
17897Object.defineProperty(exports, "__esModule", {
17898 value: true
17899});
17900exports.default = _default;
17901exports.URL = exports.DNS = void 0;
17902
17903var _stringify = _interopRequireDefault(_dereq_(132));
17904
17905var _parse = _interopRequireDefault(_dereq_(128));
17906
17907function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17908
17909function stringToBytes(str) {
17910 str = unescape(encodeURIComponent(str)); // UTF8 escape
17911
17912 const bytes = [];
17913
17914 for (let i = 0; i < str.length; ++i) {
17915 bytes.push(str.charCodeAt(i));
17916 }
17917
17918 return bytes;
17919}
17920
17921const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
17922exports.DNS = DNS;
17923const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
17924exports.URL = URL;
17925
17926function _default(name, version, hashfunc) {
17927 function generateUUID(value, namespace, buf, offset) {
17928 if (typeof value === 'string') {
17929 value = stringToBytes(value);
17930 }
17931
17932 if (typeof namespace === 'string') {
17933 namespace = (0, _parse.default)(namespace);
17934 }
17935
17936 if (namespace.length !== 16) {
17937 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
17938 } // Compute hash of namespace and value, Per 4.3
17939 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
17940 // hashfunc([...namespace, ... value])`
17941
17942
17943 let bytes = new Uint8Array(16 + value.length);
17944 bytes.set(namespace);
17945 bytes.set(value, namespace.length);
17946 bytes = hashfunc(bytes);
17947 bytes[6] = bytes[6] & 0x0f | version;
17948 bytes[8] = bytes[8] & 0x3f | 0x80;
17949
17950 if (buf) {
17951 offset = offset || 0;
17952
17953 for (let i = 0; i < 16; ++i) {
17954 buf[offset + i] = bytes[i];
17955 }
17956
17957 return buf;
17958 }
17959
17960 return (0, _stringify.default)(bytes);
17961 } // Function#name is not settable on some platforms (#270)
17962
17963
17964 try {
17965 generateUUID.name = name; // eslint-disable-next-line no-empty
17966 } catch (err) {} // For CommonJS default export support
17967
17968
17969 generateUUID.DNS = DNS;
17970 generateUUID.URL = URL;
17971 return generateUUID;
17972}
17973},{"128":128,"132":132}],136:[function(_dereq_,module,exports){
17974"use strict";
17975
17976Object.defineProperty(exports, "__esModule", {
17977 value: true
17978});
17979exports.default = void 0;
17980
17981var _rng = _interopRequireDefault(_dereq_(130));
17982
17983var _stringify = _interopRequireDefault(_dereq_(132));
17984
17985function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17986
17987function v4(options, buf, offset) {
17988 options = options || {};
17989
17990 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
17991
17992
17993 rnds[6] = rnds[6] & 0x0f | 0x40;
17994 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
17995
17996 if (buf) {
17997 offset = offset || 0;
17998
17999 for (let i = 0; i < 16; ++i) {
18000 buf[offset + i] = rnds[i];
18001 }
18002
18003 return buf;
18004 }
18005
18006 return (0, _stringify.default)(rnds);
18007}
18008
18009var _default = v4;
18010exports.default = _default;
18011},{"130":130,"132":132}],137:[function(_dereq_,module,exports){
18012"use strict";
18013
18014Object.defineProperty(exports, "__esModule", {
18015 value: true
18016});
18017exports.default = void 0;
18018
18019var _v = _interopRequireDefault(_dereq_(135));
18020
18021var _sha = _interopRequireDefault(_dereq_(131));
18022
18023function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18024
18025const v5 = (0, _v.default)('v5', 0x50, _sha.default);
18026var _default = v5;
18027exports.default = _default;
18028},{"131":131,"135":135}],138:[function(_dereq_,module,exports){
18029"use strict";
18030
18031Object.defineProperty(exports, "__esModule", {
18032 value: true
18033});
18034exports.default = void 0;
18035
18036var _regex = _interopRequireDefault(_dereq_(129));
18037
18038function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18039
18040function validate(uuid) {
18041 return typeof uuid === 'string' && _regex.default.test(uuid);
18042}
18043
18044var _default = validate;
18045exports.default = _default;
18046},{"129":129}],139:[function(_dereq_,module,exports){
18047"use strict";
18048
18049Object.defineProperty(exports, "__esModule", {
18050 value: true
18051});
18052exports.default = void 0;
18053
18054var _validate = _interopRequireDefault(_dereq_(138));
18055
18056function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18057
18058function version(uuid) {
18059 if (!(0, _validate.default)(uuid)) {
18060 throw TypeError('Invalid UUID');
18061 }
18062
18063 return parseInt(uuid.substr(14, 1), 16);
18064}
18065
18066var _default = version;
18067exports.default = _default;
18068},{"138":138}],140:[function(_dereq_,module,exports){
18069'use strict';
18070
18071/**
18072 * Stringify/parse functions that don't operate
18073 * recursively, so they avoid call stack exceeded
18074 * errors.
18075 */
18076exports.stringify = function stringify(input) {
18077 var queue = [];
18078 queue.push({obj: input});
18079
18080 var res = '';
18081 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
18082 while ((next = queue.pop())) {
18083 obj = next.obj;
18084 prefix = next.prefix || '';
18085 val = next.val || '';
18086 res += prefix;
18087 if (val) {
18088 res += val;
18089 } else if (typeof obj !== 'object') {
18090 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
18091 } else if (obj === null) {
18092 res += 'null';
18093 } else if (Array.isArray(obj)) {
18094 queue.push({val: ']'});
18095 for (i = obj.length - 1; i >= 0; i--) {
18096 arrayPrefix = i === 0 ? '' : ',';
18097 queue.push({obj: obj[i], prefix: arrayPrefix});
18098 }
18099 queue.push({val: '['});
18100 } else { // object
18101 keys = [];
18102 for (k in obj) {
18103 if (obj.hasOwnProperty(k)) {
18104 keys.push(k);
18105 }
18106 }
18107 queue.push({val: '}'});
18108 for (i = keys.length - 1; i >= 0; i--) {
18109 key = keys[i];
18110 value = obj[key];
18111 objPrefix = (i > 0 ? ',' : '');
18112 objPrefix += JSON.stringify(key) + ':';
18113 queue.push({obj: value, prefix: objPrefix});
18114 }
18115 queue.push({val: '{'});
18116 }
18117 }
18118 return res;
18119};
18120
18121// Convenience function for the parse function.
18122// This pop function is basically copied from
18123// pouchCollate.parseIndexableString
18124function pop(obj, stack, metaStack) {
18125 var lastMetaElement = metaStack[metaStack.length - 1];
18126 if (obj === lastMetaElement.element) {
18127 // popping a meta-element, e.g. an object whose value is another object
18128 metaStack.pop();
18129 lastMetaElement = metaStack[metaStack.length - 1];
18130 }
18131 var element = lastMetaElement.element;
18132 var lastElementIndex = lastMetaElement.index;
18133 if (Array.isArray(element)) {
18134 element.push(obj);
18135 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
18136 var key = stack.pop();
18137 element[key] = obj;
18138 } else {
18139 stack.push(obj); // obj with key only
18140 }
18141}
18142
18143exports.parse = function (str) {
18144 var stack = [];
18145 var metaStack = []; // stack for arrays and objects
18146 var i = 0;
18147 var collationIndex,parsedNum,numChar;
18148 var parsedString,lastCh,numConsecutiveSlashes,ch;
18149 var arrayElement, objElement;
18150 while (true) {
18151 collationIndex = str[i++];
18152 if (collationIndex === '}' ||
18153 collationIndex === ']' ||
18154 typeof collationIndex === 'undefined') {
18155 if (stack.length === 1) {
18156 return stack.pop();
18157 } else {
18158 pop(stack.pop(), stack, metaStack);
18159 continue;
18160 }
18161 }
18162 switch (collationIndex) {
18163 case ' ':
18164 case '\t':
18165 case '\n':
18166 case ':':
18167 case ',':
18168 break;
18169 case 'n':
18170 i += 3; // 'ull'
18171 pop(null, stack, metaStack);
18172 break;
18173 case 't':
18174 i += 3; // 'rue'
18175 pop(true, stack, metaStack);
18176 break;
18177 case 'f':
18178 i += 4; // 'alse'
18179 pop(false, stack, metaStack);
18180 break;
18181 case '0':
18182 case '1':
18183 case '2':
18184 case '3':
18185 case '4':
18186 case '5':
18187 case '6':
18188 case '7':
18189 case '8':
18190 case '9':
18191 case '-':
18192 parsedNum = '';
18193 i--;
18194 while (true) {
18195 numChar = str[i++];
18196 if (/[\d\.\-e\+]/.test(numChar)) {
18197 parsedNum += numChar;
18198 } else {
18199 i--;
18200 break;
18201 }
18202 }
18203 pop(parseFloat(parsedNum), stack, metaStack);
18204 break;
18205 case '"':
18206 parsedString = '';
18207 lastCh = void 0;
18208 numConsecutiveSlashes = 0;
18209 while (true) {
18210 ch = str[i++];
18211 if (ch !== '"' || (lastCh === '\\' &&
18212 numConsecutiveSlashes % 2 === 1)) {
18213 parsedString += ch;
18214 lastCh = ch;
18215 if (lastCh === '\\') {
18216 numConsecutiveSlashes++;
18217 } else {
18218 numConsecutiveSlashes = 0;
18219 }
18220 } else {
18221 break;
18222 }
18223 }
18224 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
18225 break;
18226 case '[':
18227 arrayElement = { element: [], index: stack.length };
18228 stack.push(arrayElement.element);
18229 metaStack.push(arrayElement);
18230 break;
18231 case '{':
18232 objElement = { element: {}, index: stack.length };
18233 stack.push(objElement.element);
18234 metaStack.push(objElement);
18235 break;
18236 default:
18237 throw new Error(
18238 'unexpectedly reached end of input: ' + collationIndex);
18239 }
18240 }
18241};
18242
18243},{}],141:[function(_dereq_,module,exports){
18244module.exports = extend
18245
18246var hasOwnProperty = Object.prototype.hasOwnProperty;
18247
18248function extend() {
18249 var target = {}
18250
18251 for (var i = 0; i < arguments.length; i++) {
18252 var source = arguments[i]
18253
18254 for (var key in source) {
18255 if (hasOwnProperty.call(source, key)) {
18256 target[key] = source[key]
18257 }
18258 }
18259 }
18260
18261 return target
18262}
18263
18264},{}],142:[function(_dereq_,module,exports){
18265module.exports = extend
18266
18267var hasOwnProperty = Object.prototype.hasOwnProperty;
18268
18269function extend(target) {
18270 for (var i = 1; i < arguments.length; i++) {
18271 var source = arguments[i]
18272
18273 for (var key in source) {
18274 if (hasOwnProperty.call(source, key)) {
18275 target[key] = source[key]
18276 }
18277 }
18278 }
18279
18280 return target
18281}
18282
18283},{}],143:[function(_dereq_,module,exports){
18284'use strict';
18285
18286function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
18287
18288var immediate = _interopDefault(_dereq_(31));
18289var Md5 = _interopDefault(_dereq_(84));
18290var levelup = _interopDefault(_dereq_(61));
18291var ltgt = _interopDefault(_dereq_(70));
18292var Codec = _interopDefault(_dereq_(39));
18293var ReadableStreamCore = _interopDefault(_dereq_(82));
18294var through2 = _dereq_(118);
18295var Deque = _interopDefault(_dereq_(23));
18296var bufferFrom = _interopDefault(_dereq_(12));
18297var EE = _interopDefault(_dereq_(26));
18298var uuid = _dereq_(125);
18299var vuvuzela = _interopDefault(_dereq_(140));
18300var localstoragedown = _interopDefault(_dereq_(63));
18301
18302function isBinaryObject(object) {
18303 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
18304 (typeof Blob !== 'undefined' && object instanceof Blob);
18305}
18306
18307function cloneArrayBuffer(buff) {
18308 if (typeof buff.slice === 'function') {
18309 return buff.slice(0);
18310 }
18311 // IE10-11 slice() polyfill
18312 var target = new ArrayBuffer(buff.byteLength);
18313 var targetArray = new Uint8Array(target);
18314 var sourceArray = new Uint8Array(buff);
18315 targetArray.set(sourceArray);
18316 return target;
18317}
18318
18319function cloneBinaryObject(object) {
18320 if (object instanceof ArrayBuffer) {
18321 return cloneArrayBuffer(object);
18322 }
18323 var size = object.size;
18324 var type = object.type;
18325 // Blob
18326 if (typeof object.slice === 'function') {
18327 return object.slice(0, size, type);
18328 }
18329 // PhantomJS slice() replacement
18330 return object.webkitSlice(0, size, type);
18331}
18332
18333// most of this is borrowed from lodash.isPlainObject:
18334// https://github.com/fis-components/lodash.isplainobject/
18335// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
18336
18337var funcToString = Function.prototype.toString;
18338var objectCtorString = funcToString.call(Object);
18339
18340function isPlainObject(value) {
18341 var proto = Object.getPrototypeOf(value);
18342 /* istanbul ignore if */
18343 if (proto === null) { // not sure when this happens, but I guess it can
18344 return true;
18345 }
18346 var Ctor = proto.constructor;
18347 return (typeof Ctor == 'function' &&
18348 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
18349}
18350
18351function clone(object) {
18352 var newObject;
18353 var i;
18354 var len;
18355
18356 if (!object || typeof object !== 'object') {
18357 return object;
18358 }
18359
18360 if (Array.isArray(object)) {
18361 newObject = [];
18362 for (i = 0, len = object.length; i < len; i++) {
18363 newObject[i] = clone(object[i]);
18364 }
18365 return newObject;
18366 }
18367
18368 // special case: to avoid inconsistencies between IndexedDB
18369 // and other backends, we automatically stringify Dates
18370 if (object instanceof Date && isFinite(object)) {
18371 return object.toISOString();
18372 }
18373
18374 if (isBinaryObject(object)) {
18375 return cloneBinaryObject(object);
18376 }
18377
18378 if (!isPlainObject(object)) {
18379 return object; // don't clone objects like Workers
18380 }
18381
18382 newObject = {};
18383 for (i in object) {
18384 /* istanbul ignore else */
18385 if (Object.prototype.hasOwnProperty.call(object, i)) {
18386 var value = clone(object[i]);
18387 if (typeof value !== 'undefined') {
18388 newObject[i] = value;
18389 }
18390 }
18391 }
18392 return newObject;
18393}
18394
18395function once(fun) {
18396 var called = false;
18397 return function (...args) {
18398 /* istanbul ignore if */
18399 if (called) {
18400 // this is a smoke test and should never actually happen
18401 throw new Error('once called more than once');
18402 } else {
18403 called = true;
18404 fun.apply(this, args);
18405 }
18406 };
18407}
18408
18409function toPromise(func) {
18410 //create the function we will be returning
18411 return function (...args) {
18412 // Clone arguments
18413 args = clone(args);
18414 var self = this;
18415 // if the last argument is a function, assume its a callback
18416 var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
18417 var promise = new Promise(function (fulfill, reject) {
18418 var resp;
18419 try {
18420 var callback = once(function (err, mesg) {
18421 if (err) {
18422 reject(err);
18423 } else {
18424 fulfill(mesg);
18425 }
18426 });
18427 // create a callback for this invocation
18428 // apply the function in the orig context
18429 args.push(callback);
18430 resp = func.apply(self, args);
18431 if (resp && typeof resp.then === 'function') {
18432 fulfill(resp);
18433 }
18434 } catch (e) {
18435 reject(e);
18436 }
18437 });
18438 // if there is a callback, call it back
18439 if (usedCB) {
18440 promise.then(function (result) {
18441 usedCB(null, result);
18442 }, usedCB);
18443 }
18444 return promise;
18445 };
18446}
18447
18448function logApiCall(self, name, args) {
18449 /* istanbul ignore if */
18450 if (self.constructor.listeners('debug').length) {
18451 var logArgs = ['api', self.name, name];
18452 for (var i = 0; i < args.length - 1; i++) {
18453 logArgs.push(args[i]);
18454 }
18455 self.constructor.emit('debug', logArgs);
18456
18457 // override the callback itself to log the response
18458 var origCallback = args[args.length - 1];
18459 args[args.length - 1] = function (err, res) {
18460 var responseArgs = ['api', self.name, name];
18461 responseArgs = responseArgs.concat(
18462 err ? ['error', err] : ['success', res]
18463 );
18464 self.constructor.emit('debug', responseArgs);
18465 origCallback(err, res);
18466 };
18467 }
18468}
18469
18470function adapterFun(name, callback) {
18471 return toPromise(function (...args) {
18472 if (this._closed) {
18473 return Promise.reject(new Error('database is closed'));
18474 }
18475 if (this._destroyed) {
18476 return Promise.reject(new Error('database is destroyed'));
18477 }
18478 var self = this;
18479 logApiCall(self, name, args);
18480 if (!this.taskqueue.isReady) {
18481 return new Promise(function (fulfill, reject) {
18482 self.taskqueue.addTask(function (failed) {
18483 if (failed) {
18484 reject(failed);
18485 } else {
18486 fulfill(self[name].apply(self, args));
18487 }
18488 });
18489 });
18490 }
18491 return callback.apply(this, args);
18492 });
18493}
18494
18495function mangle(key) {
18496 return '$' + key;
18497}
18498function unmangle(key) {
18499 return key.substring(1);
18500}
18501function Map$1() {
18502 this._store = {};
18503}
18504Map$1.prototype.get = function (key) {
18505 var mangled = mangle(key);
18506 return this._store[mangled];
18507};
18508Map$1.prototype.set = function (key, value) {
18509 var mangled = mangle(key);
18510 this._store[mangled] = value;
18511 return true;
18512};
18513Map$1.prototype.has = function (key) {
18514 var mangled = mangle(key);
18515 return mangled in this._store;
18516};
18517Map$1.prototype.keys = function () {
18518 return Object.keys(this._store).map(k => unmangle(k));
18519};
18520Map$1.prototype["delete"] = function (key) {
18521 var mangled = mangle(key);
18522 var res = mangled in this._store;
18523 delete this._store[mangled];
18524 return res;
18525};
18526Map$1.prototype.forEach = function (cb) {
18527 var keys = Object.keys(this._store);
18528 for (var i = 0, len = keys.length; i < len; i++) {
18529 var key = keys[i];
18530 var value = this._store[key];
18531 key = unmangle(key);
18532 cb(value, key);
18533 }
18534};
18535Object.defineProperty(Map$1.prototype, 'size', {
18536 get: function () {
18537 return Object.keys(this._store).length;
18538 }
18539});
18540
18541function Set$1(array) {
18542 this._store = new Map$1();
18543
18544 // init with an array
18545 if (array && Array.isArray(array)) {
18546 for (var i = 0, len = array.length; i < len; i++) {
18547 this.add(array[i]);
18548 }
18549 }
18550}
18551Set$1.prototype.add = function (key) {
18552 return this._store.set(key, true);
18553};
18554Set$1.prototype.has = function (key) {
18555 return this._store.has(key);
18556};
18557Set$1.prototype.forEach = function (cb) {
18558 this._store.forEach(function (value, key) {
18559 cb(key);
18560 });
18561};
18562Object.defineProperty(Set$1.prototype, 'size', {
18563 get: function () {
18564 return this._store.size;
18565 }
18566});
18567
18568// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
18569// incomplete Map/Set implementations which would otherwise cause our tests to fail.
18570// Notably they fail in IE11 and iOS 8.4, which this prevents.
18571function supportsMapAndSet() {
18572 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
18573 return false;
18574 }
18575 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
18576 return prop && 'get' in prop && Map[Symbol.species] === Map;
18577}
18578
18579// based on https://github.com/montagejs/collections
18580
18581var ExportedSet;
18582var ExportedMap;
18583
18584{
18585 if (supportsMapAndSet()) { // prefer built-in Map/Set
18586 ExportedSet = Set;
18587 ExportedMap = Map;
18588 } else { // fall back to our polyfill
18589 ExportedSet = Set$1;
18590 ExportedMap = Map$1;
18591 }
18592}
18593
18594// like underscore/lodash _.pick()
18595function pick(obj, arr) {
18596 var res = {};
18597 for (var i = 0, len = arr.length; i < len; i++) {
18598 var prop = arr[i];
18599 if (prop in obj) {
18600 res[prop] = obj[prop];
18601 }
18602 }
18603 return res;
18604}
18605
18606// Most browsers throttle concurrent requests at 6, so it's silly
18607// to shim _bulk_get by trying to launch potentially hundreds of requests
18608// and then letting the majority time out. We can handle this ourselves.
18609var MAX_NUM_CONCURRENT_REQUESTS = 6;
18610
18611function identityFunction(x) {
18612 return x;
18613}
18614
18615function formatResultForOpenRevsGet(result) {
18616 return [{
18617 ok: result
18618 }];
18619}
18620
18621// shim for P/CouchDB adapters that don't directly implement _bulk_get
18622function bulkGet(db, opts, callback) {
18623 var requests = opts.docs;
18624
18625 // consolidate into one request per doc if possible
18626 var requestsById = new ExportedMap();
18627 requests.forEach(function (request) {
18628 if (requestsById.has(request.id)) {
18629 requestsById.get(request.id).push(request);
18630 } else {
18631 requestsById.set(request.id, [request]);
18632 }
18633 });
18634
18635 var numDocs = requestsById.size;
18636 var numDone = 0;
18637 var perDocResults = new Array(numDocs);
18638
18639 function collapseResultsAndFinish() {
18640 var results = [];
18641 perDocResults.forEach(function (res) {
18642 res.docs.forEach(function (info) {
18643 results.push({
18644 id: res.id,
18645 docs: [info]
18646 });
18647 });
18648 });
18649 callback(null, {results: results});
18650 }
18651
18652 function checkDone() {
18653 if (++numDone === numDocs) {
18654 collapseResultsAndFinish();
18655 }
18656 }
18657
18658 function gotResult(docIndex, id, docs) {
18659 perDocResults[docIndex] = {id: id, docs: docs};
18660 checkDone();
18661 }
18662
18663 var allRequests = [];
18664 requestsById.forEach(function (value, key) {
18665 allRequests.push(key);
18666 });
18667
18668 var i = 0;
18669
18670 function nextBatch() {
18671
18672 if (i >= allRequests.length) {
18673 return;
18674 }
18675
18676 var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
18677 var batch = allRequests.slice(i, upTo);
18678 processBatch(batch, i);
18679 i += batch.length;
18680 }
18681
18682 function processBatch(batch, offset) {
18683 batch.forEach(function (docId, j) {
18684 var docIdx = offset + j;
18685 var docRequests = requestsById.get(docId);
18686
18687 // just use the first request as the "template"
18688 // TODO: The _bulk_get API allows for more subtle use cases than this,
18689 // but for now it is unlikely that there will be a mix of different
18690 // "atts_since" or "attachments" in the same request, since it's just
18691 // replicate.js that is using this for the moment.
18692 // Also, atts_since is aspirational, since we don't support it yet.
18693 var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
18694 docOpts.open_revs = docRequests.map(function (request) {
18695 // rev is optional, open_revs disallowed
18696 return request.rev;
18697 });
18698
18699 // remove falsey / undefined revisions
18700 docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
18701
18702 var formatResult = identityFunction;
18703
18704 if (docOpts.open_revs.length === 0) {
18705 delete docOpts.open_revs;
18706
18707 // when fetching only the "winning" leaf,
18708 // transform the result so it looks like an open_revs
18709 // request
18710 formatResult = formatResultForOpenRevsGet;
18711 }
18712
18713 // globally-supplied options
18714 ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {
18715 if (param in opts) {
18716 docOpts[param] = opts[param];
18717 }
18718 });
18719 db.get(docId, docOpts, function (err, res) {
18720 var result;
18721 /* istanbul ignore if */
18722 if (err) {
18723 result = [{error: err}];
18724 } else {
18725 result = formatResult(res);
18726 }
18727 gotResult(docIdx, docId, result);
18728 nextBatch();
18729 });
18730 });
18731 }
18732
18733 nextBatch();
18734
18735}
18736
18737var hasLocal;
18738
18739try {
18740 localStorage.setItem('_pouch_check_localstorage', 1);
18741 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
18742} catch (e) {
18743 hasLocal = false;
18744}
18745
18746function hasLocalStorage() {
18747 return hasLocal;
18748}
18749
18750// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
18751
18752class Changes extends EE {
18753 constructor() {
18754 super();
18755
18756 this._listeners = {};
18757
18758 if (hasLocalStorage()) {
18759 addEventListener("storage", function (e) {
18760 this.emit(e.key);
18761 });
18762 }
18763 }
18764
18765 addListener(dbName, id, db, opts) {
18766 if (this._listeners[id]) {
18767 return;
18768 }
18769 var inprogress = false;
18770 var self = this;
18771 function eventFunction() {
18772 if (!self._listeners[id]) {
18773 return;
18774 }
18775 if (inprogress) {
18776 inprogress = 'waiting';
18777 return;
18778 }
18779 inprogress = true;
18780 var changesOpts = pick(opts, [
18781 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
18782 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
18783 ]);
18784
18785 function onError() {
18786 inprogress = false;
18787 }
18788
18789 db.changes(changesOpts).on('change', function (c) {
18790 if (c.seq > opts.since && !opts.cancelled) {
18791 opts.since = c.seq;
18792 opts.onChange(c);
18793 }
18794 }).on('complete', function () {
18795 if (inprogress === 'waiting') {
18796 immediate(eventFunction);
18797 }
18798 inprogress = false;
18799 }).on('error', onError);
18800 }
18801 this._listeners[id] = eventFunction;
18802 this.on(dbName, eventFunction);
18803 }
18804
18805 removeListener(dbName, id) {
18806 if (!(id in this._listeners)) {
18807 return;
18808 }
18809 super.removeListener(dbName, this._listeners[id]);
18810 delete this._listeners[id];
18811 }
18812
18813 notifyLocalWindows(dbName) {
18814 //do a useless change on a storage thing
18815 //in order to get other windows's listeners to activate
18816 if (hasLocalStorage()) {
18817 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
18818 }
18819 }
18820
18821 notify(dbName) {
18822 this.emit(dbName);
18823 this.notifyLocalWindows(dbName);
18824 }
18825}
18826
18827function guardedConsole(method) {
18828 /* istanbul ignore else */
18829 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
18830 var args = Array.prototype.slice.call(arguments, 1);
18831 console[method].apply(console, args);
18832 }
18833}
18834
18835var assign;
18836{
18837 if (typeof Object.assign === 'function') {
18838 assign = Object.assign;
18839 } else {
18840 // lite Object.assign polyfill based on
18841 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
18842 assign = function (target) {
18843 var to = Object(target);
18844
18845 for (var index = 1; index < arguments.length; index++) {
18846 var nextSource = arguments[index];
18847
18848 if (nextSource != null) { // Skip over if undefined or null
18849 for (var nextKey in nextSource) {
18850 // Avoid bugs when hasOwnProperty is shadowed
18851 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
18852 to[nextKey] = nextSource[nextKey];
18853 }
18854 }
18855 }
18856 }
18857 return to;
18858 };
18859 }
18860}
18861
18862var $inject_Object_assign = assign;
18863
18864class PouchError extends Error {
18865 constructor(status, error, reason) {
18866 super();
18867 this.status = status;
18868 this.name = error;
18869 this.message = reason;
18870 this.error = true;
18871 }
18872
18873 toString() {
18874 return JSON.stringify({
18875 status: this.status,
18876 name: this.name,
18877 message: this.message,
18878 reason: this.reason
18879 });
18880 }
18881}
18882
18883var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
18884var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
18885var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
18886var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
18887var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
18888var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
18889var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
18890var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
18891var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
18892var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
18893var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
18894var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
18895var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
18896var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
18897var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
18898var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
18899var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
18900var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
18901var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
18902var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
18903var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
18904var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
18905var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
18906var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
18907
18908function createError(error, reason) {
18909 function CustomPouchError(reason) {
18910 // inherit error properties from our parent error manually
18911 // so as to allow proper JSON parsing.
18912 /* jshint ignore:start */
18913 var names = Object.getOwnPropertyNames(error);
18914 for (var i = 0, len = names.length; i < len; i++) {
18915 if (typeof error[names[i]] !== 'function') {
18916 this[names[i]] = error[names[i]];
18917 }
18918 }
18919
18920 if (this.stack === undefined) {
18921 this.stack = (new Error()).stack;
18922 }
18923
18924 /* jshint ignore:end */
18925 if (reason !== undefined) {
18926 this.reason = reason;
18927 }
18928 }
18929 CustomPouchError.prototype = PouchError.prototype;
18930 return new CustomPouchError(reason);
18931}
18932
18933function generateErrorFromResponse(err) {
18934
18935 if (typeof err !== 'object') {
18936 var data = err;
18937 err = UNKNOWN_ERROR;
18938 err.data = data;
18939 }
18940
18941 if ('error' in err && err.error === 'conflict') {
18942 err.name = 'conflict';
18943 err.status = 409;
18944 }
18945
18946 if (!('name' in err)) {
18947 err.name = err.error || 'unknown';
18948 }
18949
18950 if (!('status' in err)) {
18951 err.status = 500;
18952 }
18953
18954 if (!('message' in err)) {
18955 err.message = err.message || err.reason;
18956 }
18957
18958 if (!('stack' in err)) {
18959 err.stack = (new Error()).stack;
18960 }
18961
18962 return err;
18963}
18964
18965function tryFilter(filter, doc, req) {
18966 try {
18967 return !filter(doc, req);
18968 } catch (err) {
18969 var msg = 'Filter function threw: ' + err.toString();
18970 return createError(BAD_REQUEST, msg);
18971 }
18972}
18973
18974function filterChange(opts) {
18975 var req = {};
18976 var hasFilter = opts.filter && typeof opts.filter === 'function';
18977 req.query = opts.query_params;
18978
18979 return function filter(change) {
18980 if (!change.doc) {
18981 // CSG sends events on the changes feed that don't have documents,
18982 // this hack makes a whole lot of existing code robust.
18983 change.doc = {};
18984 }
18985
18986 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
18987
18988 if (typeof filterReturn === 'object') {
18989 return filterReturn;
18990 }
18991
18992 if (filterReturn) {
18993 return false;
18994 }
18995
18996 if (!opts.include_docs) {
18997 delete change.doc;
18998 } else if (!opts.attachments) {
18999 for (var att in change.doc._attachments) {
19000 /* istanbul ignore else */
19001 if (Object.prototype.hasOwnProperty.call(change.doc._attachments, att)) {
19002 change.doc._attachments[att].stub = true;
19003 }
19004 }
19005 }
19006 return true;
19007 };
19008}
19009
19010// shim for Function.prototype.name,
19011// for browsers that don't support it like IE
19012
19013/* istanbul ignore next */
19014function f() {}
19015
19016var hasName = f.name;
19017var res;
19018
19019// We dont run coverage in IE
19020/* istanbul ignore else */
19021if (hasName) {
19022 res = function (fun) {
19023 return fun.name;
19024 };
19025} else {
19026 res = function (fun) {
19027 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
19028 if (match && match[1]) {
19029 return match[1];
19030 }
19031 else {
19032 return '';
19033 }
19034 };
19035}
19036
19037var functionName = res;
19038
19039// Determine id an ID is valid
19040// - invalid IDs begin with an underescore that does not begin '_design' or
19041// '_local'
19042// - any other string value is a valid id
19043// Returns the specific error object for each case
19044function invalidIdError(id) {
19045 var err;
19046 if (!id) {
19047 err = createError(MISSING_ID);
19048 } else if (typeof id !== 'string') {
19049 err = createError(INVALID_ID);
19050 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
19051 err = createError(RESERVED_ID);
19052 }
19053 if (err) {
19054 throw err;
19055 }
19056}
19057
19058// Checks if a PouchDB object is "remote" or not. This is
19059
19060function isRemote(db) {
19061 if (typeof db._remote === 'boolean') {
19062 return db._remote;
19063 }
19064 /* istanbul ignore next */
19065 if (typeof db.type === 'function') {
19066 guardedConsole('warn',
19067 'db.type() is deprecated and will be removed in ' +
19068 'a future version of PouchDB');
19069 return db.type() === 'http';
19070 }
19071 /* istanbul ignore next */
19072 return false;
19073}
19074
19075function listenerCount(ee, type) {
19076 return 'listenerCount' in ee ? ee.listenerCount(type) :
19077 EE.listenerCount(ee, type);
19078}
19079
19080function parseDesignDocFunctionName(s) {
19081 if (!s) {
19082 return null;
19083 }
19084 var parts = s.split('/');
19085 if (parts.length === 2) {
19086 return parts;
19087 }
19088 if (parts.length === 1) {
19089 return [s, s];
19090 }
19091 return null;
19092}
19093
19094function normalizeDesignDocFunctionName(s) {
19095 var normalized = parseDesignDocFunctionName(s);
19096 return normalized ? normalized.join('/') : null;
19097}
19098
19099// originally parseUri 1.2.2, now patched by us
19100
19101// Based on https://github.com/alexdavid/scope-eval v0.0.3
19102// (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js)
19103// This is basically just a wrapper around new Function()
19104
19105function scopeEval(source, scope) {
19106 var keys = [];
19107 var values = [];
19108 for (var key in scope) {
19109 if (Object.prototype.hasOwnProperty.call(scope, key)) {
19110 keys.push(key);
19111 values.push(scope[key]);
19112 }
19113 }
19114 keys.push(source);
19115 return Function.apply(null, keys).apply(null, values);
19116}
19117
19118// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
19119// the diffFun tells us what delta to apply to the doc. it either returns
19120// the doc, or false if it doesn't need to do an update after all
19121function upsert(db, docId, diffFun) {
19122 return db.get(docId)[
19123 "catch"](function (err) {
19124 /* istanbul ignore next */
19125 if (err.status !== 404) {
19126 throw err;
19127 }
19128 return {};
19129 })
19130 .then(function (doc) {
19131 // the user might change the _rev, so save it for posterity
19132 var docRev = doc._rev;
19133 var newDoc = diffFun(doc);
19134
19135 if (!newDoc) {
19136 // if the diffFun returns falsy, we short-circuit as
19137 // an optimization
19138 return {updated: false, rev: docRev};
19139 }
19140
19141 // users aren't allowed to modify these values,
19142 // so reset them here
19143 newDoc._id = docId;
19144 newDoc._rev = docRev;
19145 return tryAndPut(db, newDoc, diffFun);
19146 });
19147}
19148
19149function tryAndPut(db, doc, diffFun) {
19150 return db.put(doc).then(function (res) {
19151 return {
19152 updated: true,
19153 rev: res.rev
19154 };
19155 }, function (err) {
19156 /* istanbul ignore next */
19157 if (err.status !== 409) {
19158 throw err;
19159 }
19160 return upsert(db, doc._id, diffFun);
19161 });
19162}
19163
19164var thisAtob = function (str) {
19165 return atob(str);
19166};
19167
19168var thisBtoa = function (str) {
19169 return btoa(str);
19170};
19171
19172// Abstracts constructing a Blob object, so it also works in older
19173// browsers that don't support the native Blob constructor (e.g.
19174// old QtWebKit versions, Android < 4.4).
19175function createBlob(parts, properties) {
19176 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
19177 parts = parts || [];
19178 properties = properties || {};
19179 try {
19180 return new Blob(parts, properties);
19181 } catch (e) {
19182 if (e.name !== "TypeError") {
19183 throw e;
19184 }
19185 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
19186 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
19187 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
19188 WebKitBlobBuilder;
19189 var builder = new Builder();
19190 for (var i = 0; i < parts.length; i += 1) {
19191 builder.append(parts[i]);
19192 }
19193 return builder.getBlob(properties.type);
19194 }
19195}
19196
19197// From http://stackoverflow.com/questions/14967647/ (continues on next line)
19198// encode-decode-image-with-base64-breaks-image (2013-04-21)
19199function binaryStringToArrayBuffer(bin) {
19200 var length = bin.length;
19201 var buf = new ArrayBuffer(length);
19202 var arr = new Uint8Array(buf);
19203 for (var i = 0; i < length; i++) {
19204 arr[i] = bin.charCodeAt(i);
19205 }
19206 return buf;
19207}
19208
19209function binStringToBluffer(binString, type) {
19210 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
19211}
19212
19213//Can't find original post, but this is close
19214//http://stackoverflow.com/questions/6965107/ (continues on next line)
19215//converting-between-strings-and-arraybuffers
19216function arrayBufferToBinaryString(buffer) {
19217 var binary = '';
19218 var bytes = new Uint8Array(buffer);
19219 var length = bytes.byteLength;
19220 for (var i = 0; i < length; i++) {
19221 binary += String.fromCharCode(bytes[i]);
19222 }
19223 return binary;
19224}
19225
19226// shim for browsers that don't support it
19227function readAsBinaryString(blob, callback) {
19228 var reader = new FileReader();
19229 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
19230 reader.onloadend = function (e) {
19231 var result = e.target.result || '';
19232 if (hasBinaryString) {
19233 return callback(result);
19234 }
19235 callback(arrayBufferToBinaryString(result));
19236 };
19237 if (hasBinaryString) {
19238 reader.readAsBinaryString(blob);
19239 } else {
19240 reader.readAsArrayBuffer(blob);
19241 }
19242}
19243
19244// simplified API. universal browser support is assumed
19245function readAsArrayBuffer(blob, callback) {
19246 var reader = new FileReader();
19247 reader.onloadend = function (e) {
19248 var result = e.target.result || new ArrayBuffer(0);
19249 callback(result);
19250 };
19251 reader.readAsArrayBuffer(blob);
19252}
19253
19254// this is not used in the browser
19255
19256var setImmediateShim = self.setImmediate || self.setTimeout;
19257var MD5_CHUNK_SIZE = 32768;
19258
19259function rawToBase64(raw) {
19260 return thisBtoa(raw);
19261}
19262
19263function sliceBlob(blob, start, end) {
19264 if (blob.webkitSlice) {
19265 return blob.webkitSlice(start, end);
19266 }
19267 return blob.slice(start, end);
19268}
19269
19270function appendBlob(buffer, blob, start, end, callback) {
19271 if (start > 0 || end < blob.size) {
19272 // only slice blob if we really need to
19273 blob = sliceBlob(blob, start, end);
19274 }
19275 readAsArrayBuffer(blob, function (arrayBuffer) {
19276 buffer.append(arrayBuffer);
19277 callback();
19278 });
19279}
19280
19281function appendString(buffer, string, start, end, callback) {
19282 if (start > 0 || end < string.length) {
19283 // only create a substring if we really need to
19284 string = string.substring(start, end);
19285 }
19286 buffer.appendBinary(string);
19287 callback();
19288}
19289
19290function binaryMd5(data, callback) {
19291 var inputIsString = typeof data === 'string';
19292 var len = inputIsString ? data.length : data.size;
19293 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
19294 var chunks = Math.ceil(len / chunkSize);
19295 var currentChunk = 0;
19296 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
19297
19298 var append = inputIsString ? appendString : appendBlob;
19299
19300 function next() {
19301 setImmediateShim(loadNextChunk);
19302 }
19303
19304 function done() {
19305 var raw = buffer.end(true);
19306 var base64 = rawToBase64(raw);
19307 callback(base64);
19308 buffer.destroy();
19309 }
19310
19311 function loadNextChunk() {
19312 var start = currentChunk * chunkSize;
19313 var end = start + chunkSize;
19314 currentChunk++;
19315 if (currentChunk < chunks) {
19316 append(buffer, data, start, end, next);
19317 } else {
19318 append(buffer, data, start, end, done);
19319 }
19320 }
19321 loadNextChunk();
19322}
19323
19324function stringMd5(string) {
19325 return Md5.hash(string);
19326}
19327
19328/**
19329 * Creates a new revision string that does NOT include the revision height
19330 * For example '56649f1b0506c6ca9fda0746eb0cacdf'
19331 */
19332function rev$$1(doc, deterministic_revs) {
19333 if (!deterministic_revs) {
19334 return uuid.v4().replace(/-/g, '').toLowerCase();
19335 }
19336
19337 var mutateableDoc = $inject_Object_assign({}, doc);
19338 delete mutateableDoc._rev_tree;
19339 return stringMd5(JSON.stringify(mutateableDoc));
19340}
19341
19342var uuid$1 = uuid.v4; // mimic old import, only v4 is ever used elsewhere
19343
19344function isFunction(f) {
19345 return 'function' === typeof f;
19346}
19347
19348function getPrefix(db) {
19349 if (isFunction(db.prefix)) {
19350 return db.prefix();
19351 }
19352 return db;
19353}
19354
19355function clone$1(_obj) {
19356 var obj = {};
19357 for (var k in _obj) {
19358 obj[k] = _obj[k];
19359 }
19360 return obj;
19361}
19362
19363function nut(db, precodec, codec) {
19364 function encodePrefix(prefix, key, opts1, opts2) {
19365 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
19366 }
19367
19368 function addEncodings(op, prefix) {
19369 if (prefix && prefix.options) {
19370 op.keyEncoding =
19371 op.keyEncoding || prefix.options.keyEncoding;
19372 op.valueEncoding =
19373 op.valueEncoding || prefix.options.valueEncoding;
19374 }
19375 return op;
19376 }
19377
19378 db.open(function () { /* no-op */});
19379
19380 return {
19381 apply: function (ops, opts, cb) {
19382 opts = opts || {};
19383
19384 var batch = [];
19385 var i = -1;
19386 var len = ops.length;
19387
19388 while (++i < len) {
19389 var op = ops[i];
19390 addEncodings(op, op.prefix);
19391 op.prefix = getPrefix(op.prefix);
19392 batch.push({
19393 key: encodePrefix(op.prefix, op.key, opts, op),
19394 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
19395 type: op.type
19396 });
19397 }
19398 db.db.batch(batch, opts, cb);
19399 },
19400 get: function (key, prefix, opts, cb) {
19401 opts.asBuffer = codec.valueAsBuffer(opts);
19402 return db.db.get(
19403 encodePrefix(prefix, key, opts),
19404 opts,
19405 function (err, value) {
19406 if (err) {
19407 cb(err);
19408 } else {
19409 cb(null, codec.decodeValue(value, opts));
19410 }
19411 }
19412 );
19413 },
19414 createDecoder: function (opts) {
19415 return function (key, value) {
19416 return {
19417 key: codec.decodeKey(precodec.decode(key)[1], opts),
19418 value: codec.decodeValue(value, opts)
19419 };
19420 };
19421 },
19422 isClosed: function isClosed() {
19423 return db.isClosed();
19424 },
19425 close: function close(cb) {
19426 return db.close(cb);
19427 },
19428 iterator: function (_opts) {
19429 var opts = clone$1(_opts || {});
19430 var prefix = _opts.prefix || [];
19431
19432 function encodeKey(key) {
19433 return encodePrefix(prefix, key, opts, {});
19434 }
19435
19436 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
19437
19438 // if these legacy values are in the options, remove them
19439
19440 opts.prefix = null;
19441
19442 //************************************************
19443 //hard coded defaults, for now...
19444 //TODO: pull defaults and encoding out of levelup.
19445 opts.keyAsBuffer = opts.valueAsBuffer = false;
19446 //************************************************
19447
19448
19449 //this is vital, otherwise limit: undefined will
19450 //create an empty stream.
19451 /* istanbul ignore next */
19452 if ('number' !== typeof opts.limit) {
19453 opts.limit = -1;
19454 }
19455
19456 opts.keyAsBuffer = precodec.buffer;
19457 opts.valueAsBuffer = codec.valueAsBuffer(opts);
19458
19459 function wrapIterator(iterator) {
19460 return {
19461 next: function (cb) {
19462 return iterator.next(cb);
19463 },
19464 end: function (cb) {
19465 iterator.end(cb);
19466 }
19467 };
19468 }
19469
19470 return wrapIterator(db.db.iterator(opts));
19471 }
19472 };
19473}
19474
19475class NotFoundError extends Error {
19476 constructor() {
19477 super();
19478 this.name = 'NotFoundError';
19479 }
19480}
19481
19482var EventEmitter = EE.EventEmitter;
19483var version = "6.5.4";
19484
19485var NOT_FOUND_ERROR = new NotFoundError();
19486
19487var sublevel = function (nut, prefix, createStream, options) {
19488 var emitter = new EventEmitter();
19489 emitter.sublevels = {};
19490 emitter.options = options;
19491
19492 emitter.version = version;
19493
19494 emitter.methods = {};
19495 prefix = prefix || [];
19496
19497 function mergeOpts(opts) {
19498 var o = {};
19499 var k;
19500 if (options) {
19501 for (k in options) {
19502 if (typeof options[k] !== 'undefined') {
19503 o[k] = options[k];
19504 }
19505 }
19506 }
19507 if (opts) {
19508 for (k in opts) {
19509 if (typeof opts[k] !== 'undefined') {
19510 o[k] = opts[k];
19511 }
19512 }
19513 }
19514 return o;
19515 }
19516
19517 emitter.put = function (key, value, opts, cb) {
19518 if ('function' === typeof opts) {
19519 cb = opts;
19520 opts = {};
19521 }
19522
19523 nut.apply([{
19524 key: key, value: value,
19525 prefix: prefix.slice(), type: 'put'
19526 }], mergeOpts(opts), function (err) {
19527 /* istanbul ignore next */
19528 if (err) {
19529 return cb(err);
19530 }
19531 emitter.emit('put', key, value);
19532 cb(null);
19533 });
19534 };
19535
19536 emitter.prefix = function () {
19537 return prefix.slice();
19538 };
19539
19540 emitter.batch = function (ops, opts, cb) {
19541 if ('function' === typeof opts) {
19542 cb = opts;
19543 opts = {};
19544 }
19545
19546 ops = ops.map(function (op) {
19547 return {
19548 key: op.key,
19549 value: op.value,
19550 prefix: op.prefix || prefix,
19551 keyEncoding: op.keyEncoding, // *
19552 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
19553 type: op.type
19554 };
19555 });
19556
19557 nut.apply(ops, mergeOpts(opts), function (err) {
19558 /* istanbul ignore next */
19559 if (err) {
19560 return cb(err);
19561 }
19562 emitter.emit('batch', ops);
19563 cb(null);
19564 });
19565 };
19566
19567 emitter.get = function (key, opts, cb) {
19568 /* istanbul ignore else */
19569 if ('function' === typeof opts) {
19570 cb = opts;
19571 opts = {};
19572 }
19573 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
19574 if (err) {
19575 cb(NOT_FOUND_ERROR);
19576 } else {
19577 cb(null, value);
19578 }
19579 });
19580 };
19581
19582 emitter.sublevel = function (name, opts) {
19583 return emitter.sublevels[name] =
19584 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
19585 };
19586
19587 emitter.readStream = emitter.createReadStream = function (opts) {
19588 opts = mergeOpts(opts);
19589 opts.prefix = prefix;
19590 var stream;
19591 var it = nut.iterator(opts);
19592
19593 stream = createStream(opts, nut.createDecoder(opts));
19594 stream.setIterator(it);
19595
19596 return stream;
19597 };
19598
19599 emitter.close = function (cb) {
19600 nut.close(cb);
19601 };
19602
19603 emitter.isOpen = nut.isOpen;
19604 emitter.isClosed = nut.isClosed;
19605
19606 return emitter;
19607};
19608
19609/* Copyright (c) 2012-2014 LevelUP contributors
19610 * See list at <https://github.com/rvagg/node-levelup#contributing>
19611 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
19612 */
19613
19614var Readable = ReadableStreamCore.Readable;
19615
19616function createClass(parent, init) {
19617 let klass = function (...args) {
19618 if (!(this instanceof klass)) {
19619 return new klass(...args);
19620 }
19621 init.apply(this, args);
19622 };
19623 klass.prototype = Object.create(parent.prototype, {
19624 constructor: { value: klass }
19625 });
19626 return klass;
19627}
19628
19629class ReadStreamInternal extends Readable {
19630 constructor(options, makeData) {
19631 super({ objectMode: true, highWaterMark: options.highWaterMark });
19632 this._setup(options, makeData);
19633 }
19634
19635 _setup(options, makeData) {
19636 super.constructor({ objectMode: true, highWaterMark: options.highWaterMark });
19637
19638 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
19639 this._waiting = false;
19640 this._options = options;
19641 this._makeData = makeData;
19642 }
19643
19644 setIterator(it) {
19645 this._iterator = it;
19646 /* istanbul ignore if */
19647 if (this._destroyed) {
19648 return it.end(function () {});
19649 }
19650 /* istanbul ignore if */
19651 if (this._waiting) {
19652 this._waiting = false;
19653 return this._read();
19654 }
19655 return this;
19656 }
19657
19658 _cleanup(err) {
19659 if (this._destroyed) {
19660 return;
19661 }
19662
19663 this._destroyed = true;
19664
19665 var self = this;
19666 /* istanbul ignore if */
19667 if (err && err.message !== 'iterator has ended') {
19668 self.emit('error', err);
19669 }
19670
19671 /* istanbul ignore else */
19672 if (self._iterator) {
19673 self._iterator.end(function () {
19674 self._iterator = null;
19675 self.emit('close');
19676 });
19677 } else {
19678 self.emit('close');
19679 }
19680 }
19681
19682 destroy() {
19683 this._cleanup();
19684 }
19685
19686 _read() {
19687 var self = this;
19688 /* istanbul ignore if */
19689 if (self._destroyed) {
19690 return;
19691 }
19692 /* istanbul ignore if */
19693 if (!self._iterator) {
19694 return this._waiting = true;
19695 }
19696
19697 self._iterator.next(function (err, key, value) {
19698 if (err || (key === undefined && value === undefined)) {
19699 if (!err && !self._destroyed) {
19700 self.push(null);
19701 }
19702 return self._cleanup(err);
19703 }
19704
19705
19706 value = self._makeData(key, value);
19707 if (!self._destroyed) {
19708 self.push(value);
19709 }
19710 });
19711 }
19712}
19713
19714const ReadStream = createClass(ReadStreamInternal, function (options, makeData) {
19715 ReadStreamInternal.prototype._setup.call(this, options, makeData);
19716});
19717
19718var precodec = {
19719 encode: function (decodedKey) {
19720 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
19721 },
19722 decode: function (encodedKeyAsBuffer) {
19723 var str = encodedKeyAsBuffer.toString();
19724 var idx = str.indexOf('\xff', 1);
19725 return [str.substring(1, idx), str.substring(idx + 1)];
19726 },
19727 lowerBound: '\x00',
19728 upperBound: '\xff'
19729};
19730
19731var codec = new Codec();
19732
19733function sublevelPouch(db) {
19734 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
19735}
19736
19737// We fetch all leafs of the revision tree, and sort them based on tree length
19738// and whether they were deleted, undeleted documents with the longest revision
19739// tree (most edits) win
19740// The final sort algorithm is slightly documented in a sidebar here:
19741// http://guide.couchdb.org/draft/conflicts.html
19742function winningRev(metadata) {
19743 var winningId;
19744 var winningPos;
19745 var winningDeleted;
19746 var toVisit = metadata.rev_tree.slice();
19747 var node;
19748 while ((node = toVisit.pop())) {
19749 var tree = node.ids;
19750 var branches = tree[2];
19751 var pos = node.pos;
19752 if (branches.length) { // non-leaf
19753 for (var i = 0, len = branches.length; i < len; i++) {
19754 toVisit.push({pos: pos + 1, ids: branches[i]});
19755 }
19756 continue;
19757 }
19758 var deleted = !!tree[1].deleted;
19759 var id = tree[0];
19760 // sort by deleted, then pos, then id
19761 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
19762 winningPos !== pos ? winningPos < pos : winningId < id)) {
19763 winningId = id;
19764 winningPos = pos;
19765 winningDeleted = deleted;
19766 }
19767 }
19768
19769 return winningPos + '-' + winningId;
19770}
19771
19772// Pretty much all below can be combined into a higher order function to
19773// traverse revisions
19774// The return value from the callback will be passed as context to all
19775// children of that node
19776function traverseRevTree(revs, callback) {
19777 var toVisit = revs.slice();
19778
19779 var node;
19780 while ((node = toVisit.pop())) {
19781 var pos = node.pos;
19782 var tree = node.ids;
19783 var branches = tree[2];
19784 var newCtx =
19785 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
19786 for (var i = 0, len = branches.length; i < len; i++) {
19787 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
19788 }
19789 }
19790}
19791
19792function sortByPos(a, b) {
19793 return a.pos - b.pos;
19794}
19795
19796function collectLeaves(revs) {
19797 var leaves = [];
19798 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
19799 if (isLeaf) {
19800 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
19801 }
19802 });
19803 leaves.sort(sortByPos).reverse();
19804 for (var i = 0, len = leaves.length; i < len; i++) {
19805 delete leaves[i].pos;
19806 }
19807 return leaves;
19808}
19809
19810// returns revs of all conflicts that is leaves such that
19811// 1. are not deleted and
19812// 2. are different than winning revision
19813function collectConflicts(metadata) {
19814 var win = winningRev(metadata);
19815 var leaves = collectLeaves(metadata.rev_tree);
19816 var conflicts = [];
19817 for (var i = 0, len = leaves.length; i < len; i++) {
19818 var leaf = leaves[i];
19819 if (leaf.rev !== win && !leaf.opts.deleted) {
19820 conflicts.push(leaf.rev);
19821 }
19822 }
19823 return conflicts;
19824}
19825
19826// compact a tree by marking its non-leafs as missing,
19827// and return a list of revs to delete
19828function compactTree(metadata) {
19829 var revs = [];
19830 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
19831 revHash, ctx, opts) {
19832 if (opts.status === 'available' && !isLeaf) {
19833 revs.push(pos + '-' + revHash);
19834 opts.status = 'missing';
19835 }
19836 });
19837 return revs;
19838}
19839
19840// `findPathToLeaf()` returns an array of revs that goes from the specified
19841// leaf rev to the root of that leaf’s branch.
19842//
19843// eg. for this rev tree:
19844// 1-9692 ▶ 2-37aa ▶ 3-df22 ▶ 4-6e94 ▶ 5-df4a ▶ 6-6a3a ▶ 7-57e5
19845// ┃ ┗━━━━━━▶ 5-8d8c ▶ 6-65e0
19846// ┗━━━━━━▶ 3-43f6 ▶ 4-a3b4
19847//
19848// For a `targetRev` of '7-57e5', `findPathToLeaf()` would return ['7-57e5', '6-6a3a', '5-df4a']
19849// The `revs` arument has the same structure as what `revs_tree` has on e.g.
19850// the IndexedDB representation of the rev tree datastructure. Please refer to
19851// tests/unit/test.purge.js for examples of what these look like.
19852//
19853// This function will throw an error if:
19854// - The requested revision does not exist
19855// - The requested revision is not a leaf
19856function findPathToLeaf(revs, targetRev) {
19857 let path = [];
19858 const toVisit = revs.slice();
19859
19860 let node;
19861 while ((node = toVisit.pop())) {
19862 const { pos, ids: tree } = node;
19863 const rev = `${pos}-${tree[0]}`;
19864 const branches = tree[2];
19865
19866 // just assuming we're already working on the path up towards our desired leaf.
19867 path.push(rev);
19868
19869 // we've reached the leaf of our dreams, so return the computed path.
19870 if (rev === targetRev) {
19871 //…unleeeeess
19872 if (branches.length !== 0) {
19873 throw new Error('The requested revision is not a leaf');
19874 }
19875 return path.reverse();
19876 }
19877
19878 // this is based on the assumption that after we have a leaf (`branches.length == 0`), we handle the next
19879 // branch. this is true for all branches other than the path leading to the winning rev (which is 7-57e5 in
19880 // the example above. i've added a reset condition for branching nodes (`branches.length > 1`) as well.
19881 if (branches.length === 0 || branches.length > 1) {
19882 path = [];
19883 }
19884
19885 // as a next step, we push the branches of this node to `toVisit` for visiting it during the next iteration
19886 for (let i = 0, len = branches.length; i < len; i++) {
19887 toVisit.push({ pos: pos + 1, ids: branches[i] });
19888 }
19889 }
19890 if (path.length === 0) {
19891 throw new Error('The requested revision does not exist');
19892 }
19893 return path.reverse();
19894}
19895
19896// build up a list of all the paths to the leafs in this revision tree
19897function rootToLeaf(revs) {
19898 var paths = [];
19899 var toVisit = revs.slice();
19900 var node;
19901 while ((node = toVisit.pop())) {
19902 var pos = node.pos;
19903 var tree = node.ids;
19904 var id = tree[0];
19905 var opts = tree[1];
19906 var branches = tree[2];
19907 var isLeaf = branches.length === 0;
19908
19909 var history = node.history ? node.history.slice() : [];
19910 history.push({id: id, opts: opts});
19911 if (isLeaf) {
19912 paths.push({pos: (pos + 1 - history.length), ids: history});
19913 }
19914 for (var i = 0, len = branches.length; i < len; i++) {
19915 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
19916 }
19917 }
19918 return paths.reverse();
19919}
19920
19921// for a better overview of what this is doing, read:
19922
19923function sortByPos$1(a, b) {
19924 return a.pos - b.pos;
19925}
19926
19927// classic binary search
19928function binarySearch(arr, item, comparator) {
19929 var low = 0;
19930 var high = arr.length;
19931 var mid;
19932 while (low < high) {
19933 mid = (low + high) >>> 1;
19934 if (comparator(arr[mid], item) < 0) {
19935 low = mid + 1;
19936 } else {
19937 high = mid;
19938 }
19939 }
19940 return low;
19941}
19942
19943// assuming the arr is sorted, insert the item in the proper place
19944function insertSorted(arr, item, comparator) {
19945 var idx = binarySearch(arr, item, comparator);
19946 arr.splice(idx, 0, item);
19947}
19948
19949// Turn a path as a flat array into a tree with a single branch.
19950// If any should be stemmed from the beginning of the array, that's passed
19951// in as the second argument
19952function pathToTree(path, numStemmed) {
19953 var root;
19954 var leaf;
19955 for (var i = numStemmed, len = path.length; i < len; i++) {
19956 var node = path[i];
19957 var currentLeaf = [node.id, node.opts, []];
19958 if (leaf) {
19959 leaf[2].push(currentLeaf);
19960 leaf = currentLeaf;
19961 } else {
19962 root = leaf = currentLeaf;
19963 }
19964 }
19965 return root;
19966}
19967
19968// compare the IDs of two trees
19969function compareTree(a, b) {
19970 return a[0] < b[0] ? -1 : 1;
19971}
19972
19973// Merge two trees together
19974// The roots of tree1 and tree2 must be the same revision
19975function mergeTree(in_tree1, in_tree2) {
19976 var queue = [{tree1: in_tree1, tree2: in_tree2}];
19977 var conflicts = false;
19978 while (queue.length > 0) {
19979 var item = queue.pop();
19980 var tree1 = item.tree1;
19981 var tree2 = item.tree2;
19982
19983 if (tree1[1].status || tree2[1].status) {
19984 tree1[1].status =
19985 (tree1[1].status === 'available' ||
19986 tree2[1].status === 'available') ? 'available' : 'missing';
19987 }
19988
19989 for (var i = 0; i < tree2[2].length; i++) {
19990 if (!tree1[2][0]) {
19991 conflicts = 'new_leaf';
19992 tree1[2][0] = tree2[2][i];
19993 continue;
19994 }
19995
19996 var merged = false;
19997 for (var j = 0; j < tree1[2].length; j++) {
19998 if (tree1[2][j][0] === tree2[2][i][0]) {
19999 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
20000 merged = true;
20001 }
20002 }
20003 if (!merged) {
20004 conflicts = 'new_branch';
20005 insertSorted(tree1[2], tree2[2][i], compareTree);
20006 }
20007 }
20008 }
20009 return {conflicts: conflicts, tree: in_tree1};
20010}
20011
20012function doMerge(tree, path, dontExpand) {
20013 var restree = [];
20014 var conflicts = false;
20015 var merged = false;
20016 var res;
20017
20018 if (!tree.length) {
20019 return {tree: [path], conflicts: 'new_leaf'};
20020 }
20021
20022 for (var i = 0, len = tree.length; i < len; i++) {
20023 var branch = tree[i];
20024 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
20025 // Paths start at the same position and have the same root, so they need
20026 // merged
20027 res = mergeTree(branch.ids, path.ids);
20028 restree.push({pos: branch.pos, ids: res.tree});
20029 conflicts = conflicts || res.conflicts;
20030 merged = true;
20031 } else if (dontExpand !== true) {
20032 // The paths start at a different position, take the earliest path and
20033 // traverse up until it as at the same point from root as the path we
20034 // want to merge. If the keys match we return the longer path with the
20035 // other merged After stemming we dont want to expand the trees
20036
20037 var t1 = branch.pos < path.pos ? branch : path;
20038 var t2 = branch.pos < path.pos ? path : branch;
20039 var diff = t2.pos - t1.pos;
20040
20041 var candidateParents = [];
20042
20043 var trees = [];
20044 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
20045 while (trees.length > 0) {
20046 var item = trees.pop();
20047 if (item.diff === 0) {
20048 if (item.ids[0] === t2.ids[0]) {
20049 candidateParents.push(item);
20050 }
20051 continue;
20052 }
20053 var elements = item.ids[2];
20054 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
20055 trees.push({
20056 ids: elements[j],
20057 diff: item.diff - 1,
20058 parent: item.ids,
20059 parentIdx: j
20060 });
20061 }
20062 }
20063
20064 var el = candidateParents[0];
20065
20066 if (!el) {
20067 restree.push(branch);
20068 } else {
20069 res = mergeTree(el.ids, t2.ids);
20070 el.parent[2][el.parentIdx] = res.tree;
20071 restree.push({pos: t1.pos, ids: t1.ids});
20072 conflicts = conflicts || res.conflicts;
20073 merged = true;
20074 }
20075 } else {
20076 restree.push(branch);
20077 }
20078 }
20079
20080 // We didnt find
20081 if (!merged) {
20082 restree.push(path);
20083 }
20084
20085 restree.sort(sortByPos$1);
20086
20087 return {
20088 tree: restree,
20089 conflicts: conflicts || 'internal_node'
20090 };
20091}
20092
20093// To ensure we dont grow the revision tree infinitely, we stem old revisions
20094function stem(tree, depth) {
20095 // First we break out the tree into a complete list of root to leaf paths
20096 var paths = rootToLeaf(tree);
20097 var stemmedRevs;
20098
20099 var result;
20100 for (var i = 0, len = paths.length; i < len; i++) {
20101 // Then for each path, we cut off the start of the path based on the
20102 // `depth` to stem to, and generate a new set of flat trees
20103 var path = paths[i];
20104 var stemmed = path.ids;
20105 var node;
20106 if (stemmed.length > depth) {
20107 // only do the stemming work if we actually need to stem
20108 if (!stemmedRevs) {
20109 stemmedRevs = {}; // avoid allocating this object unnecessarily
20110 }
20111 var numStemmed = stemmed.length - depth;
20112 node = {
20113 pos: path.pos + numStemmed,
20114 ids: pathToTree(stemmed, numStemmed)
20115 };
20116
20117 for (var s = 0; s < numStemmed; s++) {
20118 var rev = (path.pos + s) + '-' + stemmed[s].id;
20119 stemmedRevs[rev] = true;
20120 }
20121 } else { // no need to actually stem
20122 node = {
20123 pos: path.pos,
20124 ids: pathToTree(stemmed, 0)
20125 };
20126 }
20127
20128 // Then we remerge all those flat trees together, ensuring that we dont
20129 // connect trees that would go beyond the depth limit
20130 if (result) {
20131 result = doMerge(result, node, true).tree;
20132 } else {
20133 result = [node];
20134 }
20135 }
20136
20137 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
20138 if (stemmedRevs) {
20139 traverseRevTree(result, function (isLeaf, pos, revHash) {
20140 // some revisions may have been removed in a branch but not in another
20141 delete stemmedRevs[pos + '-' + revHash];
20142 });
20143 }
20144
20145 return {
20146 tree: result,
20147 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
20148 };
20149}
20150
20151function merge(tree, path, depth) {
20152 var newTree = doMerge(tree, path);
20153 var stemmed = stem(newTree.tree, depth);
20154 return {
20155 tree: stemmed.tree,
20156 stemmedRevs: stemmed.revs,
20157 conflicts: newTree.conflicts
20158 };
20159}
20160
20161// return true if a rev exists in the rev tree, false otherwise
20162function revExists(revs, rev) {
20163 var toVisit = revs.slice();
20164 var splitRev = rev.split('-');
20165 var targetPos = parseInt(splitRev[0], 10);
20166 var targetId = splitRev[1];
20167
20168 var node;
20169 while ((node = toVisit.pop())) {
20170 if (node.pos === targetPos && node.ids[0] === targetId) {
20171 return true;
20172 }
20173 var branches = node.ids[2];
20174 for (var i = 0, len = branches.length; i < len; i++) {
20175 toVisit.push({pos: node.pos + 1, ids: branches[i]});
20176 }
20177 }
20178 return false;
20179}
20180
20181function getTrees(node) {
20182 return node.ids;
20183}
20184
20185// check if a specific revision of a doc has been deleted
20186// - metadata: the metadata object from the doc store
20187// - rev: (optional) the revision to check. defaults to winning revision
20188function isDeleted(metadata, rev) {
20189 if (!rev) {
20190 rev = winningRev(metadata);
20191 }
20192 var id = rev.substring(rev.indexOf('-') + 1);
20193 var toVisit = metadata.rev_tree.map(getTrees);
20194
20195 var tree;
20196 while ((tree = toVisit.pop())) {
20197 if (tree[0] === id) {
20198 return !!tree[1].deleted;
20199 }
20200 toVisit = toVisit.concat(tree[2]);
20201 }
20202}
20203
20204function isLocalId(id) {
20205 return (/^_local/).test(id);
20206}
20207
20208// returns the current leaf node for a given revision
20209function latest(rev, metadata) {
20210 var toVisit = metadata.rev_tree.slice();
20211 var node;
20212 while ((node = toVisit.pop())) {
20213 var pos = node.pos;
20214 var tree = node.ids;
20215 var id = tree[0];
20216 var opts = tree[1];
20217 var branches = tree[2];
20218 var isLeaf = branches.length === 0;
20219
20220 var history = node.history ? node.history.slice() : [];
20221 history.push({id: id, pos: pos, opts: opts});
20222
20223 if (isLeaf) {
20224 for (var i = 0, len = history.length; i < len; i++) {
20225 var historyNode = history[i];
20226 var historyRev = historyNode.pos + '-' + historyNode.id;
20227
20228 if (historyRev === rev) {
20229 // return the rev of this leaf
20230 return pos + '-' + id;
20231 }
20232 }
20233 }
20234
20235 for (var j = 0, l = branches.length; j < l; j++) {
20236 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
20237 }
20238 }
20239
20240 /* istanbul ignore next */
20241 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
20242}
20243
20244function tryCatchInChangeListener(self, change, pending, lastSeq) {
20245 // isolate try/catches to avoid V8 deoptimizations
20246 try {
20247 self.emit('change', change, pending, lastSeq);
20248 } catch (e) {
20249 guardedConsole('error', 'Error in .on("change", function):', e);
20250 }
20251}
20252
20253function processChange(doc, metadata, opts) {
20254 var changeList = [{rev: doc._rev}];
20255 if (opts.style === 'all_docs') {
20256 changeList = collectLeaves(metadata.rev_tree)
20257 .map(function (x) { return {rev: x.rev}; });
20258 }
20259 var change = {
20260 id: metadata.id,
20261 changes: changeList,
20262 doc: doc
20263 };
20264
20265 if (isDeleted(metadata, doc._rev)) {
20266 change.deleted = true;
20267 }
20268 if (opts.conflicts) {
20269 change.doc._conflicts = collectConflicts(metadata);
20270 if (!change.doc._conflicts.length) {
20271 delete change.doc._conflicts;
20272 }
20273 }
20274 return change;
20275}
20276
20277class Changes$1 extends EE {
20278 constructor(db, opts, callback) {
20279 super();
20280 this.db = db;
20281 opts = opts ? clone(opts) : {};
20282 var complete = opts.complete = once((err, resp) => {
20283 if (err) {
20284 if (listenerCount(this, 'error') > 0) {
20285 this.emit('error', err);
20286 }
20287 } else {
20288 this.emit('complete', resp);
20289 }
20290 this.removeAllListeners();
20291 db.removeListener('destroyed', onDestroy);
20292 });
20293 if (callback) {
20294 this.on('complete', function (resp) {
20295 callback(null, resp);
20296 });
20297 this.on('error', callback);
20298 }
20299 const onDestroy = () => {
20300 this.cancel();
20301 };
20302 db.once('destroyed', onDestroy);
20303
20304 opts.onChange = (change, pending, lastSeq) => {
20305 /* istanbul ignore if */
20306 if (this.isCancelled) {
20307 return;
20308 }
20309 tryCatchInChangeListener(this, change, pending, lastSeq);
20310 };
20311
20312 var promise = new Promise(function (fulfill, reject) {
20313 opts.complete = function (err, res) {
20314 if (err) {
20315 reject(err);
20316 } else {
20317 fulfill(res);
20318 }
20319 };
20320 });
20321 this.once('cancel', function () {
20322 db.removeListener('destroyed', onDestroy);
20323 opts.complete(null, {status: 'cancelled'});
20324 });
20325 this.then = promise.then.bind(promise);
20326 this['catch'] = promise['catch'].bind(promise);
20327 this.then(function (result) {
20328 complete(null, result);
20329 }, complete);
20330
20331
20332
20333 if (!db.taskqueue.isReady) {
20334 db.taskqueue.addTask((failed) => {
20335 if (failed) {
20336 opts.complete(failed);
20337 } else if (this.isCancelled) {
20338 this.emit('cancel');
20339 } else {
20340 this.validateChanges(opts);
20341 }
20342 });
20343 } else {
20344 this.validateChanges(opts);
20345 }
20346 }
20347
20348 cancel() {
20349 this.isCancelled = true;
20350 if (this.db.taskqueue.isReady) {
20351 this.emit('cancel');
20352 }
20353 }
20354
20355 validateChanges(opts) {
20356 var callback = opts.complete;
20357
20358 /* istanbul ignore else */
20359 if (PouchDB$1._changesFilterPlugin) {
20360 PouchDB$1._changesFilterPlugin.validate(opts, (err) => {
20361 if (err) {
20362 return callback(err);
20363 }
20364 this.doChanges(opts);
20365 });
20366 } else {
20367 this.doChanges(opts);
20368 }
20369 }
20370
20371 doChanges(opts) {
20372 var callback = opts.complete;
20373
20374 opts = clone(opts);
20375 if ('live' in opts && !('continuous' in opts)) {
20376 opts.continuous = opts.live;
20377 }
20378 opts.processChange = processChange;
20379
20380 if (opts.since === 'latest') {
20381 opts.since = 'now';
20382 }
20383 if (!opts.since) {
20384 opts.since = 0;
20385 }
20386 if (opts.since === 'now') {
20387 this.db.info().then((info) => {
20388 /* istanbul ignore if */
20389 if (this.isCancelled) {
20390 callback(null, {status: 'cancelled'});
20391 return;
20392 }
20393 opts.since = info.update_seq;
20394 this.doChanges(opts);
20395 }, callback);
20396 return;
20397 }
20398
20399 /* istanbul ignore else */
20400 if (PouchDB$1._changesFilterPlugin) {
20401 PouchDB$1._changesFilterPlugin.normalize(opts);
20402 if (PouchDB$1._changesFilterPlugin.shouldFilter(this, opts)) {
20403 return PouchDB$1._changesFilterPlugin.filter(this, opts);
20404 }
20405 } else {
20406 ['doc_ids', 'filter', 'selector', 'view'].forEach(function (key) {
20407 if (key in opts) {
20408 guardedConsole('warn',
20409 'The "' + key + '" option was passed in to changes/replicate, ' +
20410 'but pouchdb-changes-filter plugin is not installed, so it ' +
20411 'was ignored. Please install the plugin to enable filtering.'
20412 );
20413 }
20414 });
20415 }
20416
20417 if (!('descending' in opts)) {
20418 opts.descending = false;
20419 }
20420
20421 // 0 and 1 should return 1 document
20422 opts.limit = opts.limit === 0 ? 1 : opts.limit;
20423 opts.complete = callback;
20424 var newPromise = this.db._changes(opts);
20425 /* istanbul ignore else */
20426 if (newPromise && typeof newPromise.cancel === 'function') {
20427 const cancel = this.cancel;
20428 this.cancel = (...args) => {
20429 newPromise.cancel();
20430 cancel.apply(this, args);
20431 };
20432 }
20433 }
20434}
20435
20436/*
20437 * A generic pouch adapter
20438 */
20439
20440function compare(left, right) {
20441 return left < right ? -1 : left > right ? 1 : 0;
20442}
20443
20444// Wrapper for functions that call the bulkdocs api with a single doc,
20445// if the first result is an error, return an error
20446function yankError(callback, docId) {
20447 return function (err, results) {
20448 if (err || (results[0] && results[0].error)) {
20449 err = err || results[0];
20450 err.docId = docId;
20451 callback(err);
20452 } else {
20453 callback(null, results.length ? results[0] : results);
20454 }
20455 };
20456}
20457
20458// clean docs given to us by the user
20459function cleanDocs(docs) {
20460 for (var i = 0; i < docs.length; i++) {
20461 var doc = docs[i];
20462 if (doc._deleted) {
20463 delete doc._attachments; // ignore atts for deleted docs
20464 } else if (doc._attachments) {
20465 // filter out extraneous keys from _attachments
20466 var atts = Object.keys(doc._attachments);
20467 for (var j = 0; j < atts.length; j++) {
20468 var att = atts[j];
20469 doc._attachments[att] = pick(doc._attachments[att],
20470 ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
20471 }
20472 }
20473 }
20474}
20475
20476// compare two docs, first by _id then by _rev
20477function compareByIdThenRev(a, b) {
20478 var idCompare = compare(a._id, b._id);
20479 if (idCompare !== 0) {
20480 return idCompare;
20481 }
20482 var aStart = a._revisions ? a._revisions.start : 0;
20483 var bStart = b._revisions ? b._revisions.start : 0;
20484 return compare(aStart, bStart);
20485}
20486
20487// for every node in a revision tree computes its distance from the closest
20488// leaf
20489function computeHeight(revs) {
20490 var height = {};
20491 var edges = [];
20492 traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
20493 var rev = pos + "-" + id;
20494 if (isLeaf) {
20495 height[rev] = 0;
20496 }
20497 if (prnt !== undefined) {
20498 edges.push({from: prnt, to: rev});
20499 }
20500 return rev;
20501 });
20502
20503 edges.reverse();
20504 edges.forEach(function (edge) {
20505 if (height[edge.from] === undefined) {
20506 height[edge.from] = 1 + height[edge.to];
20507 } else {
20508 height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
20509 }
20510 });
20511 return height;
20512}
20513
20514function allDocsKeysParse(opts) {
20515 var keys = ('limit' in opts) ?
20516 opts.keys.slice(opts.skip, opts.limit + opts.skip) :
20517 (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;
20518 opts.keys = keys;
20519 opts.skip = 0;
20520 delete opts.limit;
20521 if (opts.descending) {
20522 keys.reverse();
20523 opts.descending = false;
20524 }
20525}
20526
20527// all compaction is done in a queue, to avoid attaching
20528// too many listeners at once
20529function doNextCompaction(self) {
20530 var task = self._compactionQueue[0];
20531 var opts = task.opts;
20532 var callback = task.callback;
20533 self.get('_local/compaction')["catch"](function () {
20534 return false;
20535 }).then(function (doc) {
20536 if (doc && doc.last_seq) {
20537 opts.last_seq = doc.last_seq;
20538 }
20539 self._compact(opts, function (err, res) {
20540 /* istanbul ignore if */
20541 if (err) {
20542 callback(err);
20543 } else {
20544 callback(null, res);
20545 }
20546 immediate(function () {
20547 self._compactionQueue.shift();
20548 if (self._compactionQueue.length) {
20549 doNextCompaction(self);
20550 }
20551 });
20552 });
20553 });
20554}
20555
20556function appendPurgeSeq(db, docId, rev) {
20557 return db.get('_local/purges').then(function (doc) {
20558 const purgeSeq = doc.purgeSeq + 1;
20559 doc.purges.push({
20560 docId,
20561 rev,
20562 purgeSeq
20563 });
20564 if (doc.purges.length > self.purged_infos_limit) {
20565 doc.purges.splice(0, doc.purges.length - self.purged_infos_limit);
20566 }
20567 doc.purgeSeq = purgeSeq;
20568 return doc;
20569 })["catch"](function (err) {
20570 if (err.status !== 404) {
20571 throw err;
20572 }
20573 return {
20574 _id: '_local/purges',
20575 purges: [{
20576 docId,
20577 rev,
20578 purgeSeq: 0
20579 }],
20580 purgeSeq: 0
20581 };
20582 }).then(function (doc) {
20583 return db.put(doc);
20584 });
20585}
20586
20587function attachmentNameError(name) {
20588 if (name.charAt(0) === '_') {
20589 return name + ' is not a valid attachment name, attachment ' +
20590 'names cannot start with \'_\'';
20591 }
20592 return false;
20593}
20594
20595class AbstractPouchDB extends EE {
20596 _setup() {
20597 this.post = adapterFun('post', function (doc, opts, callback) {
20598 if (typeof opts === 'function') {
20599 callback = opts;
20600 opts = {};
20601 }
20602 if (typeof doc !== 'object' || Array.isArray(doc)) {
20603 return callback(createError(NOT_AN_OBJECT));
20604 }
20605 this.bulkDocs({docs: [doc]}, opts, yankError(callback, doc._id));
20606 }).bind(this);
20607
20608 this.put = adapterFun('put', function (doc, opts, cb) {
20609 if (typeof opts === 'function') {
20610 cb = opts;
20611 opts = {};
20612 }
20613 if (typeof doc !== 'object' || Array.isArray(doc)) {
20614 return cb(createError(NOT_AN_OBJECT));
20615 }
20616 invalidIdError(doc._id);
20617 if (isLocalId(doc._id) && typeof this._putLocal === 'function') {
20618 if (doc._deleted) {
20619 return this._removeLocal(doc, cb);
20620 } else {
20621 return this._putLocal(doc, cb);
20622 }
20623 }
20624
20625 const putDoc = (next) => {
20626 if (typeof this._put === 'function' && opts.new_edits !== false) {
20627 this._put(doc, opts, next);
20628 } else {
20629 this.bulkDocs({docs: [doc]}, opts, yankError(next, doc._id));
20630 }
20631 };
20632
20633 if (opts.force && doc._rev) {
20634 transformForceOptionToNewEditsOption();
20635 putDoc(function (err) {
20636 var result = err ? null : {ok: true, id: doc._id, rev: doc._rev};
20637 cb(err, result);
20638 });
20639 } else {
20640 putDoc(cb);
20641 }
20642
20643 function transformForceOptionToNewEditsOption() {
20644 var parts = doc._rev.split('-');
20645 var oldRevId = parts[1];
20646 var oldRevNum = parseInt(parts[0], 10);
20647
20648 var newRevNum = oldRevNum + 1;
20649 var newRevId = rev$$1();
20650
20651 doc._revisions = {
20652 start: newRevNum,
20653 ids: [newRevId, oldRevId]
20654 };
20655 doc._rev = newRevNum + '-' + newRevId;
20656 opts.new_edits = false;
20657 }
20658 }).bind(this);
20659
20660 this.putAttachment = adapterFun('putAttachment', function (docId, attachmentId, rev, blob, type) {
20661 var api = this;
20662 if (typeof type === 'function') {
20663 type = blob;
20664 blob = rev;
20665 rev = null;
20666 }
20667 // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267
20668 /* istanbul ignore if */
20669 if (typeof type === 'undefined') {
20670 type = blob;
20671 blob = rev;
20672 rev = null;
20673 }
20674 if (!type) {
20675 guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');
20676 }
20677
20678 function createAttachment(doc) {
20679 var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;
20680 doc._attachments = doc._attachments || {};
20681 doc._attachments[attachmentId] = {
20682 content_type: type,
20683 data: blob,
20684 revpos: ++prevrevpos
20685 };
20686 return api.put(doc);
20687 }
20688
20689 return api.get(docId).then(function (doc) {
20690 if (doc._rev !== rev) {
20691 throw createError(REV_CONFLICT);
20692 }
20693
20694 return createAttachment(doc);
20695 }, function (err) {
20696 // create new doc
20697 /* istanbul ignore else */
20698 if (err.reason === MISSING_DOC.message) {
20699 return createAttachment({_id: docId});
20700 } else {
20701 throw err;
20702 }
20703 });
20704 }).bind(this);
20705
20706 this.removeAttachment = adapterFun('removeAttachment', function (docId, attachmentId, rev, callback) {
20707 this.get(docId, (err, obj) => {
20708 /* istanbul ignore if */
20709 if (err) {
20710 callback(err);
20711 return;
20712 }
20713 if (obj._rev !== rev) {
20714 callback(createError(REV_CONFLICT));
20715 return;
20716 }
20717 /* istanbul ignore if */
20718 if (!obj._attachments) {
20719 return callback();
20720 }
20721 delete obj._attachments[attachmentId];
20722 if (Object.keys(obj._attachments).length === 0) {
20723 delete obj._attachments;
20724 }
20725 this.put(obj, callback);
20726 });
20727 }).bind(this);
20728
20729 this.remove = adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
20730 var doc;
20731 if (typeof optsOrRev === 'string') {
20732 // id, rev, opts, callback style
20733 doc = {
20734 _id: docOrId,
20735 _rev: optsOrRev
20736 };
20737 if (typeof opts === 'function') {
20738 callback = opts;
20739 opts = {};
20740 }
20741 } else {
20742 // doc, opts, callback style
20743 doc = docOrId;
20744 if (typeof optsOrRev === 'function') {
20745 callback = optsOrRev;
20746 opts = {};
20747 } else {
20748 callback = opts;
20749 opts = optsOrRev;
20750 }
20751 }
20752 opts = opts || {};
20753 opts.was_delete = true;
20754 var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};
20755 newDoc._deleted = true;
20756 if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {
20757 return this._removeLocal(doc, callback);
20758 }
20759 this.bulkDocs({docs: [newDoc]}, opts, yankError(callback, newDoc._id));
20760 }).bind(this);
20761
20762 this.revsDiff = adapterFun('revsDiff', function (req, opts, callback) {
20763 if (typeof opts === 'function') {
20764 callback = opts;
20765 opts = {};
20766 }
20767 var ids = Object.keys(req);
20768
20769 if (!ids.length) {
20770 return callback(null, {});
20771 }
20772
20773 var count = 0;
20774 var missing = new ExportedMap();
20775
20776 function addToMissing(id, revId) {
20777 if (!missing.has(id)) {
20778 missing.set(id, {missing: []});
20779 }
20780 missing.get(id).missing.push(revId);
20781 }
20782
20783 function processDoc(id, rev_tree) {
20784 // Is this fast enough? Maybe we should switch to a set simulated by a map
20785 var missingForId = req[id].slice(0);
20786 traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,
20787 opts) {
20788 var rev = pos + '-' + revHash;
20789 var idx = missingForId.indexOf(rev);
20790 if (idx === -1) {
20791 return;
20792 }
20793
20794 missingForId.splice(idx, 1);
20795 /* istanbul ignore if */
20796 if (opts.status !== 'available') {
20797 addToMissing(id, rev);
20798 }
20799 });
20800
20801 // Traversing the tree is synchronous, so now `missingForId` contains
20802 // revisions that were not found in the tree
20803 missingForId.forEach(function (rev) {
20804 addToMissing(id, rev);
20805 });
20806 }
20807
20808 ids.map(function (id) {
20809 this._getRevisionTree(id, function (err, rev_tree) {
20810 if (err && err.status === 404 && err.message === 'missing') {
20811 missing.set(id, {missing: req[id]});
20812 } else if (err) {
20813 /* istanbul ignore next */
20814 return callback(err);
20815 } else {
20816 processDoc(id, rev_tree);
20817 }
20818
20819 if (++count === ids.length) {
20820 // convert LazyMap to object
20821 var missingObj = {};
20822 missing.forEach(function (value, key) {
20823 missingObj[key] = value;
20824 });
20825 return callback(null, missingObj);
20826 }
20827 });
20828 }, this);
20829 }).bind(this);
20830
20831 // _bulk_get API for faster replication, as described in
20832 // https://github.com/apache/couchdb-chttpd/pull/33
20833 // At the "abstract" level, it will just run multiple get()s in
20834 // parallel, because this isn't much of a performance cost
20835 // for local databases (except the cost of multiple transactions, which is
20836 // small). The http adapter overrides this in order
20837 // to do a more efficient single HTTP request.
20838 this.bulkGet = adapterFun('bulkGet', function (opts, callback) {
20839 bulkGet(this, opts, callback);
20840 }).bind(this);
20841
20842 // compact one document and fire callback
20843 // by compacting we mean removing all revisions which
20844 // are further from the leaf in revision tree than max_height
20845 this.compactDocument = adapterFun('compactDocument', function (docId, maxHeight, callback) {
20846 this._getRevisionTree(docId, (err, revTree) => {
20847 /* istanbul ignore if */
20848 if (err) {
20849 return callback(err);
20850 }
20851 var height = computeHeight(revTree);
20852 var candidates = [];
20853 var revs = [];
20854 Object.keys(height).forEach(function (rev) {
20855 if (height[rev] > maxHeight) {
20856 candidates.push(rev);
20857 }
20858 });
20859
20860 traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {
20861 var rev = pos + '-' + revHash;
20862 if (opts.status === 'available' && candidates.indexOf(rev) !== -1) {
20863 revs.push(rev);
20864 }
20865 });
20866 this._doCompaction(docId, revs, callback);
20867 });
20868 }).bind(this);
20869
20870 // compact the whole database using single document
20871 // compaction
20872 this.compact = adapterFun('compact', function (opts, callback) {
20873 if (typeof opts === 'function') {
20874 callback = opts;
20875 opts = {};
20876 }
20877
20878 opts = opts || {};
20879
20880 this._compactionQueue = this._compactionQueue || [];
20881 this._compactionQueue.push({opts: opts, callback: callback});
20882 if (this._compactionQueue.length === 1) {
20883 doNextCompaction(this);
20884 }
20885 }).bind(this);
20886
20887 /* Begin api wrappers. Specific functionality to storage belongs in the _[method] */
20888 this.get = adapterFun('get', function (id, opts, cb) {
20889 if (typeof opts === 'function') {
20890 cb = opts;
20891 opts = {};
20892 }
20893 if (typeof id !== 'string') {
20894 return cb(createError(INVALID_ID));
20895 }
20896 if (isLocalId(id) && typeof this._getLocal === 'function') {
20897 return this._getLocal(id, cb);
20898 }
20899 var leaves = [];
20900
20901 const finishOpenRevs = () => {
20902 var result = [];
20903 var count = leaves.length;
20904 /* istanbul ignore if */
20905 if (!count) {
20906 return cb(null, result);
20907 }
20908
20909 // order with open_revs is unspecified
20910 leaves.forEach((leaf) => {
20911 this.get(id, {
20912 rev: leaf,
20913 revs: opts.revs,
20914 latest: opts.latest,
20915 attachments: opts.attachments,
20916 binary: opts.binary
20917 }, function (err, doc) {
20918 if (!err) {
20919 // using latest=true can produce duplicates
20920 var existing;
20921 for (var i = 0, l = result.length; i < l; i++) {
20922 if (result[i].ok && result[i].ok._rev === doc._rev) {
20923 existing = true;
20924 break;
20925 }
20926 }
20927 if (!existing) {
20928 result.push({ok: doc});
20929 }
20930 } else {
20931 result.push({missing: leaf});
20932 }
20933 count--;
20934 if (!count) {
20935 cb(null, result);
20936 }
20937 });
20938 });
20939 };
20940
20941 if (opts.open_revs) {
20942 if (opts.open_revs === "all") {
20943 this._getRevisionTree(id, function (err, rev_tree) {
20944 /* istanbul ignore if */
20945 if (err) {
20946 return cb(err);
20947 }
20948 leaves = collectLeaves(rev_tree).map(function (leaf) {
20949 return leaf.rev;
20950 });
20951 finishOpenRevs();
20952 });
20953 } else {
20954 if (Array.isArray(opts.open_revs)) {
20955 leaves = opts.open_revs;
20956 for (var i = 0; i < leaves.length; i++) {
20957 var l = leaves[i];
20958 // looks like it's the only thing couchdb checks
20959 if (!(typeof (l) === "string" && /^\d+-/.test(l))) {
20960 return cb(createError(INVALID_REV));
20961 }
20962 }
20963 finishOpenRevs();
20964 } else {
20965 return cb(createError(UNKNOWN_ERROR, 'function_clause'));
20966 }
20967 }
20968 return; // open_revs does not like other options
20969 }
20970
20971 return this._get(id, opts, (err, result) => {
20972 if (err) {
20973 err.docId = id;
20974 return cb(err);
20975 }
20976
20977 var doc = result.doc;
20978 var metadata = result.metadata;
20979 var ctx = result.ctx;
20980
20981 if (opts.conflicts) {
20982 var conflicts = collectConflicts(metadata);
20983 if (conflicts.length) {
20984 doc._conflicts = conflicts;
20985 }
20986 }
20987
20988 if (isDeleted(metadata, doc._rev)) {
20989 doc._deleted = true;
20990 }
20991
20992 if (opts.revs || opts.revs_info) {
20993 var splittedRev = doc._rev.split('-');
20994 var revNo = parseInt(splittedRev[0], 10);
20995 var revHash = splittedRev[1];
20996
20997 var paths = rootToLeaf(metadata.rev_tree);
20998 var path = null;
20999
21000 for (var i = 0; i < paths.length; i++) {
21001 var currentPath = paths[i];
21002 var hashIndex = currentPath.ids.map(function (x) { return x.id; })
21003 .indexOf(revHash);
21004 var hashFoundAtRevPos = hashIndex === (revNo - 1);
21005
21006 if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {
21007 path = currentPath;
21008 }
21009 }
21010
21011 /* istanbul ignore if */
21012 if (!path) {
21013 err = new Error('invalid rev tree');
21014 err.docId = id;
21015 return cb(err);
21016 }
21017
21018 var indexOfRev = path.ids.map(function (x) { return x.id; })
21019 .indexOf(doc._rev.split('-')[1]) + 1;
21020 var howMany = path.ids.length - indexOfRev;
21021 path.ids.splice(indexOfRev, howMany);
21022 path.ids.reverse();
21023
21024 if (opts.revs) {
21025 doc._revisions = {
21026 start: (path.pos + path.ids.length) - 1,
21027 ids: path.ids.map(function (rev) {
21028 return rev.id;
21029 })
21030 };
21031 }
21032 if (opts.revs_info) {
21033 var pos = path.pos + path.ids.length;
21034 doc._revs_info = path.ids.map(function (rev) {
21035 pos--;
21036 return {
21037 rev: pos + '-' + rev.id,
21038 status: rev.opts.status
21039 };
21040 });
21041 }
21042 }
21043
21044 if (opts.attachments && doc._attachments) {
21045 var attachments = doc._attachments;
21046 var count = Object.keys(attachments).length;
21047 if (count === 0) {
21048 return cb(null, doc);
21049 }
21050 Object.keys(attachments).forEach((key) => {
21051 this._getAttachment(doc._id, key, attachments[key], {
21052 // Previously the revision handling was done in adapter.js
21053 // getAttachment, however since idb-next doesnt we need to
21054 // pass the rev through
21055 rev: doc._rev,
21056 binary: opts.binary,
21057 ctx: ctx
21058 }, function (err, data) {
21059 var att = doc._attachments[key];
21060 att.data = data;
21061 delete att.stub;
21062 delete att.length;
21063 if (!--count) {
21064 cb(null, doc);
21065 }
21066 });
21067 });
21068 } else {
21069 if (doc._attachments) {
21070 for (var key in doc._attachments) {
21071 /* istanbul ignore else */
21072 if (Object.prototype.hasOwnProperty.call(doc._attachments, key)) {
21073 doc._attachments[key].stub = true;
21074 }
21075 }
21076 }
21077 cb(null, doc);
21078 }
21079 });
21080 }).bind(this);
21081
21082 // TODO: I dont like this, it forces an extra read for every
21083 // attachment read and enforces a confusing api between
21084 // adapter.js and the adapter implementation
21085 this.getAttachment = adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {
21086 if (opts instanceof Function) {
21087 callback = opts;
21088 opts = {};
21089 }
21090 this._get(docId, opts, (err, res) => {
21091 if (err) {
21092 return callback(err);
21093 }
21094 if (res.doc._attachments && res.doc._attachments[attachmentId]) {
21095 opts.ctx = res.ctx;
21096 opts.binary = true;
21097 this._getAttachment(docId, attachmentId,
21098 res.doc._attachments[attachmentId], opts, callback);
21099 } else {
21100 return callback(createError(MISSING_DOC));
21101 }
21102 });
21103 }).bind(this);
21104
21105 this.allDocs = adapterFun('allDocs', function (opts, callback) {
21106 if (typeof opts === 'function') {
21107 callback = opts;
21108 opts = {};
21109 }
21110 opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;
21111 if (opts.start_key) {
21112 opts.startkey = opts.start_key;
21113 }
21114 if (opts.end_key) {
21115 opts.endkey = opts.end_key;
21116 }
21117 if ('keys' in opts) {
21118 if (!Array.isArray(opts.keys)) {
21119 return callback(new TypeError('options.keys must be an array'));
21120 }
21121 var incompatibleOpt =
21122 ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {
21123 return incompatibleOpt in opts;
21124 })[0];
21125 if (incompatibleOpt) {
21126 callback(createError(QUERY_PARSE_ERROR,
21127 'Query parameter `' + incompatibleOpt +
21128 '` is not compatible with multi-get'
21129 ));
21130 return;
21131 }
21132 if (!isRemote(this)) {
21133 allDocsKeysParse(opts);
21134 if (opts.keys.length === 0) {
21135 return this._allDocs({limit: 0}, callback);
21136 }
21137 }
21138 }
21139
21140 return this._allDocs(opts, callback);
21141 }).bind(this);
21142
21143 this.close = adapterFun('close', function (callback) {
21144 this._closed = true;
21145 this.emit('closed');
21146 return this._close(callback);
21147 }).bind(this);
21148
21149 this.info = adapterFun('info', function (callback) {
21150 this._info((err, info) => {
21151 if (err) {
21152 return callback(err);
21153 }
21154 // assume we know better than the adapter, unless it informs us
21155 info.db_name = info.db_name || this.name;
21156 info.auto_compaction = !!(this.auto_compaction && !isRemote(this));
21157 info.adapter = this.adapter;
21158 callback(null, info);
21159 });
21160 }).bind(this);
21161
21162 this.id = adapterFun('id', function (callback) {
21163 return this._id(callback);
21164 }).bind(this);
21165
21166 this.bulkDocs = adapterFun('bulkDocs', function (req, opts, callback) {
21167 if (typeof opts === 'function') {
21168 callback = opts;
21169 opts = {};
21170 }
21171
21172 opts = opts || {};
21173
21174 if (Array.isArray(req)) {
21175 req = {
21176 docs: req
21177 };
21178 }
21179
21180 if (!req || !req.docs || !Array.isArray(req.docs)) {
21181 return callback(createError(MISSING_BULK_DOCS));
21182 }
21183
21184 for (var i = 0; i < req.docs.length; ++i) {
21185 if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) {
21186 return callback(createError(NOT_AN_OBJECT));
21187 }
21188 }
21189
21190 var attachmentError;
21191 req.docs.forEach(function (doc) {
21192 if (doc._attachments) {
21193 Object.keys(doc._attachments).forEach(function (name) {
21194 attachmentError = attachmentError || attachmentNameError(name);
21195 if (!doc._attachments[name].content_type) {
21196 guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');
21197 }
21198 });
21199 }
21200 });
21201
21202 if (attachmentError) {
21203 return callback(createError(BAD_REQUEST, attachmentError));
21204 }
21205
21206 if (!('new_edits' in opts)) {
21207 if ('new_edits' in req) {
21208 opts.new_edits = req.new_edits;
21209 } else {
21210 opts.new_edits = true;
21211 }
21212 }
21213
21214 var adapter = this;
21215 if (!opts.new_edits && !isRemote(adapter)) {
21216 // ensure revisions of the same doc are sorted, so that
21217 // the local adapter processes them correctly (#2935)
21218 req.docs.sort(compareByIdThenRev);
21219 }
21220
21221 cleanDocs(req.docs);
21222
21223 // in the case of conflicts, we want to return the _ids to the user
21224 // however, the underlying adapter may destroy the docs array, so
21225 // create a copy here
21226 var ids = req.docs.map(function (doc) {
21227 return doc._id;
21228 });
21229
21230 this._bulkDocs(req, opts, function (err, res) {
21231 if (err) {
21232 return callback(err);
21233 }
21234 if (!opts.new_edits) {
21235 // this is what couch does when new_edits is false
21236 res = res.filter(function (x) {
21237 return x.error;
21238 });
21239 }
21240 // add ids for error/conflict responses (not required for CouchDB)
21241 if (!isRemote(adapter)) {
21242 for (var i = 0, l = res.length; i < l; i++) {
21243 res[i].id = res[i].id || ids[i];
21244 }
21245 }
21246
21247 callback(null, res);
21248 });
21249 }).bind(this);
21250
21251 this.registerDependentDatabase = adapterFun('registerDependentDatabase', function (dependentDb, callback) {
21252 var dbOptions = clone(this.__opts);
21253 if (this.__opts.view_adapter) {
21254 dbOptions.adapter = this.__opts.view_adapter;
21255 }
21256
21257 var depDB = new this.constructor(dependentDb, dbOptions);
21258
21259 function diffFun(doc) {
21260 doc.dependentDbs = doc.dependentDbs || {};
21261 if (doc.dependentDbs[dependentDb]) {
21262 return false; // no update required
21263 }
21264 doc.dependentDbs[dependentDb] = true;
21265 return doc;
21266 }
21267 upsert(this, '_local/_pouch_dependentDbs', diffFun).then(function () {
21268 callback(null, {db: depDB});
21269 })["catch"](callback);
21270 }).bind(this);
21271
21272 this.destroy = adapterFun('destroy', function (opts, callback) {
21273
21274 if (typeof opts === 'function') {
21275 callback = opts;
21276 opts = {};
21277 }
21278
21279 var usePrefix = 'use_prefix' in this ? this.use_prefix : true;
21280
21281 const destroyDb = () => {
21282 // call destroy method of the particular adaptor
21283 this._destroy(opts, (err, resp) => {
21284 if (err) {
21285 return callback(err);
21286 }
21287 this._destroyed = true;
21288 this.emit('destroyed');
21289 callback(null, resp || { 'ok': true });
21290 });
21291 };
21292
21293 if (isRemote(this)) {
21294 // no need to check for dependent DBs if it's a remote DB
21295 return destroyDb();
21296 }
21297
21298 this.get('_local/_pouch_dependentDbs', (err, localDoc) => {
21299 if (err) {
21300 /* istanbul ignore if */
21301 if (err.status !== 404) {
21302 return callback(err);
21303 } else { // no dependencies
21304 return destroyDb();
21305 }
21306 }
21307 var dependentDbs = localDoc.dependentDbs;
21308 var PouchDB = this.constructor;
21309 var deletedMap = Object.keys(dependentDbs).map((name) => {
21310 // use_prefix is only false in the browser
21311 /* istanbul ignore next */
21312 var trueName = usePrefix ?
21313 name.replace(new RegExp('^' + PouchDB.prefix), '') : name;
21314 return new PouchDB(trueName, this.__opts).destroy();
21315 });
21316 Promise.all(deletedMap).then(destroyDb, callback);
21317 });
21318 }).bind(this);
21319 }
21320
21321 _compact(opts, callback) {
21322 var changesOpts = {
21323 return_docs: false,
21324 last_seq: opts.last_seq || 0
21325 };
21326 var promises = [];
21327
21328 var taskId;
21329 var compactedDocs = 0;
21330
21331 const onChange = (row) => {
21332 this.activeTasks.update(taskId, {
21333 completed_items: ++compactedDocs
21334 });
21335 promises.push(this.compactDocument(row.id, 0));
21336 };
21337 const onError = (err) => {
21338 this.activeTasks.remove(taskId, err);
21339 callback(err);
21340 };
21341 const onComplete = (resp) => {
21342 var lastSeq = resp.last_seq;
21343 Promise.all(promises).then(() => {
21344 return upsert(this, '_local/compaction', (doc) => {
21345 if (!doc.last_seq || doc.last_seq < lastSeq) {
21346 doc.last_seq = lastSeq;
21347 return doc;
21348 }
21349 return false; // somebody else got here first, don't update
21350 });
21351 }).then(() => {
21352 this.activeTasks.remove(taskId);
21353 callback(null, {ok: true});
21354 })["catch"](onError);
21355 };
21356
21357 this.info().then((info) => {
21358 taskId = this.activeTasks.add({
21359 name: 'database_compaction',
21360 total_items: info.update_seq - changesOpts.last_seq
21361 });
21362
21363 this.changes(changesOpts)
21364 .on('change', onChange)
21365 .on('complete', onComplete)
21366 .on('error', onError);
21367 });
21368 }
21369
21370 changes(opts, callback) {
21371 if (typeof opts === 'function') {
21372 callback = opts;
21373 opts = {};
21374 }
21375
21376 opts = opts || {};
21377
21378 // By default set return_docs to false if the caller has opts.live = true,
21379 // this will prevent us from collecting the set of changes indefinitely
21380 // resulting in growing memory
21381 opts.return_docs = ('return_docs' in opts) ? opts.return_docs : !opts.live;
21382
21383 return new Changes$1(this, opts, callback);
21384 }
21385
21386 type() {
21387 return (typeof this._type === 'function') ? this._type() : this.adapter;
21388 }
21389}
21390
21391// The abstract purge implementation expects a doc id and the rev of a leaf node in that doc.
21392// It will return errors if the rev doesn’t exist or isn’t a leaf.
21393AbstractPouchDB.prototype.purge = adapterFun('_purge', function (docId, rev, callback) {
21394 if (typeof this._purge === 'undefined') {
21395 return callback(createError(UNKNOWN_ERROR, 'Purge is not implemented in the ' + this.adapter + ' adapter.'));
21396 }
21397 var self = this;
21398
21399 self._getRevisionTree(docId, (error, revs) => {
21400 if (error) {
21401 return callback(error);
21402 }
21403 if (!revs) {
21404 return callback(createError(MISSING_DOC));
21405 }
21406 let path;
21407 try {
21408 path = findPathToLeaf(revs, rev);
21409 } catch (error) {
21410 return callback(error.message || error);
21411 }
21412 self._purge(docId, path, (error, result) => {
21413 if (error) {
21414 return callback(error);
21415 } else {
21416 appendPurgeSeq(self, docId, rev).then(function () {
21417 return callback(null, result);
21418 });
21419 }
21420 });
21421 });
21422});
21423
21424class TaskQueue {
21425 constructor() {
21426 this.isReady = false;
21427 this.failed = false;
21428 this.queue = [];
21429 }
21430
21431 execute() {
21432 var fun;
21433 if (this.failed) {
21434 while ((fun = this.queue.shift())) {
21435 fun(this.failed);
21436 }
21437 } else {
21438 while ((fun = this.queue.shift())) {
21439 fun();
21440 }
21441 }
21442 }
21443
21444 fail(err) {
21445 this.failed = err;
21446 this.execute();
21447 }
21448
21449 ready(db) {
21450 this.isReady = true;
21451 this.db = db;
21452 this.execute();
21453 }
21454
21455 addTask(fun) {
21456 this.queue.push(fun);
21457 if (this.failed) {
21458 this.execute();
21459 }
21460 }
21461}
21462
21463function parseAdapter(name, opts) {
21464 var match = name.match(/([a-z-]*):\/\/(.*)/);
21465 if (match) {
21466 // the http adapter expects the fully qualified name
21467 return {
21468 name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],
21469 adapter: match[1]
21470 };
21471 }
21472
21473 var adapters = PouchDB$1.adapters;
21474 var preferredAdapters = PouchDB$1.preferredAdapters;
21475 var prefix = PouchDB$1.prefix;
21476 var adapterName = opts.adapter;
21477
21478 if (!adapterName) { // automatically determine adapter
21479 for (var i = 0; i < preferredAdapters.length; ++i) {
21480 adapterName = preferredAdapters[i];
21481 // check for browsers that have been upgraded from websql-only to websql+idb
21482 /* istanbul ignore if */
21483 if (adapterName === 'idb' && 'websql' in adapters &&
21484 hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {
21485 // log it, because this can be confusing during development
21486 guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' +
21487 ' avoid data loss, because it was already opened with WebSQL.');
21488 continue; // keep using websql to avoid user data loss
21489 }
21490 break;
21491 }
21492 }
21493
21494 var adapter = adapters[adapterName];
21495
21496 // if adapter is invalid, then an error will be thrown later
21497 var usePrefix = (adapter && 'use_prefix' in adapter) ?
21498 adapter.use_prefix : true;
21499
21500 return {
21501 name: usePrefix ? (prefix + name) : name,
21502 adapter: adapterName
21503 };
21504}
21505
21506function inherits(A, B) {
21507 A.prototype = Object.create(B.prototype, {
21508 constructor: { value: A }
21509 });
21510}
21511
21512function createClass$1(parent, init) {
21513 let klass = function (...args) {
21514 if (!(this instanceof klass)) {
21515 return new klass(...args);
21516 }
21517 init.apply(this, args);
21518 };
21519 inherits(klass, parent);
21520 return klass;
21521}
21522
21523// OK, so here's the deal. Consider this code:
21524// var db1 = new PouchDB('foo');
21525// var db2 = new PouchDB('foo');
21526// db1.destroy();
21527// ^ these two both need to emit 'destroyed' events,
21528// as well as the PouchDB constructor itself.
21529// So we have one db object (whichever one got destroy() called on it)
21530// responsible for emitting the initial event, which then gets emitted
21531// by the constructor, which then broadcasts it to any other dbs
21532// that may have been created with the same name.
21533function prepareForDestruction(self) {
21534
21535 function onDestroyed(from_constructor) {
21536 self.removeListener('closed', onClosed);
21537 if (!from_constructor) {
21538 self.constructor.emit('destroyed', self.name);
21539 }
21540 }
21541
21542 function onClosed() {
21543 self.removeListener('destroyed', onDestroyed);
21544 self.constructor.emit('unref', self);
21545 }
21546
21547 self.once('destroyed', onDestroyed);
21548 self.once('closed', onClosed);
21549 self.constructor.emit('ref', self);
21550}
21551
21552class PouchInternal extends AbstractPouchDB {
21553 constructor(name, opts) {
21554 super();
21555 this._setup(name, opts);
21556 }
21557
21558 _setup(name, opts) {
21559 super._setup();
21560 opts = opts || {};
21561
21562 if (name && typeof name === 'object') {
21563 opts = name;
21564 name = opts.name;
21565 delete opts.name;
21566 }
21567
21568 if (opts.deterministic_revs === undefined) {
21569 opts.deterministic_revs = true;
21570 }
21571
21572 this.__opts = opts = clone(opts);
21573
21574 this.auto_compaction = opts.auto_compaction;
21575 this.purged_infos_limit = opts.purged_infos_limit || 1000;
21576 this.prefix = PouchDB$1.prefix;
21577
21578 if (typeof name !== 'string') {
21579 throw new Error('Missing/invalid DB name');
21580 }
21581
21582 var prefixedName = (opts.prefix || '') + name;
21583 var backend = parseAdapter(prefixedName, opts);
21584
21585 opts.name = backend.name;
21586 opts.adapter = opts.adapter || backend.adapter;
21587
21588 this.name = name;
21589 this._adapter = opts.adapter;
21590 PouchDB$1.emit('debug', ['adapter', 'Picked adapter: ', opts.adapter]);
21591
21592 if (!PouchDB$1.adapters[opts.adapter] ||
21593 !PouchDB$1.adapters[opts.adapter].valid()) {
21594 throw new Error('Invalid Adapter: ' + opts.adapter);
21595 }
21596
21597 if (opts.view_adapter) {
21598 if (!PouchDB$1.adapters[opts.view_adapter] ||
21599 !PouchDB$1.adapters[opts.view_adapter].valid()) {
21600 throw new Error('Invalid View Adapter: ' + opts.view_adapter);
21601 }
21602 }
21603
21604 this.taskqueue = new TaskQueue();
21605
21606 this.adapter = opts.adapter;
21607
21608 PouchDB$1.adapters[opts.adapter].call(this, opts, (err) => {
21609 if (err) {
21610 return this.taskqueue.fail(err);
21611 }
21612 prepareForDestruction(this);
21613
21614 this.emit('created', this);
21615 PouchDB$1.emit('created', this.name);
21616 this.taskqueue.ready(this);
21617 });
21618 }
21619}
21620
21621const PouchDB$1 = createClass$1(PouchInternal, function (name, opts) {
21622 PouchInternal.prototype._setup.call(this, name, opts);
21623});
21624
21625var f$1 = fetch;
21626
21627class ActiveTasks {
21628 constructor() {
21629 this.tasks = {};
21630 }
21631
21632 list() {
21633 return Object.values(this.tasks);
21634 }
21635
21636 add(task) {
21637 const id = uuid.v4();
21638 this.tasks[id] = {
21639 id,
21640 name: task.name,
21641 total_items: task.total_items,
21642 created_at: new Date().toJSON()
21643 };
21644 return id;
21645 }
21646
21647 get(id) {
21648 return this.tasks[id];
21649 }
21650
21651 /* eslint-disable no-unused-vars */
21652 remove(id, reason) {
21653 delete this.tasks[id];
21654 return this.tasks;
21655 }
21656
21657 update(id, updatedTask) {
21658 const task = this.tasks[id];
21659 if (typeof task !== 'undefined') {
21660 const mergedTask = {
21661 id: task.id,
21662 name: task.name,
21663 created_at: task.created_at,
21664 total_items: updatedTask.total_items || task.total_items,
21665 completed_items: updatedTask.completed_items || task.completed_items,
21666 updated_at: new Date().toJSON()
21667 };
21668 this.tasks[id] = mergedTask;
21669 }
21670 return this.tasks;
21671 }
21672}
21673
21674PouchDB$1.adapters = {};
21675PouchDB$1.preferredAdapters = [];
21676
21677PouchDB$1.prefix = '_pouch_';
21678
21679var eventEmitter = new EE();
21680
21681function setUpEventEmitter(Pouch) {
21682 Object.keys(EE.prototype).forEach(function (key) {
21683 if (typeof EE.prototype[key] === 'function') {
21684 Pouch[key] = eventEmitter[key].bind(eventEmitter);
21685 }
21686 });
21687
21688 // these are created in constructor.js, and allow us to notify each DB with
21689 // the same name that it was destroyed, via the constructor object
21690 var destructListeners = Pouch._destructionListeners = new ExportedMap();
21691
21692 Pouch.on('ref', function onConstructorRef(db) {
21693 if (!destructListeners.has(db.name)) {
21694 destructListeners.set(db.name, []);
21695 }
21696 destructListeners.get(db.name).push(db);
21697 });
21698
21699 Pouch.on('unref', function onConstructorUnref(db) {
21700 if (!destructListeners.has(db.name)) {
21701 return;
21702 }
21703 var dbList = destructListeners.get(db.name);
21704 var pos = dbList.indexOf(db);
21705 if (pos < 0) {
21706 /* istanbul ignore next */
21707 return;
21708 }
21709 dbList.splice(pos, 1);
21710 if (dbList.length > 1) {
21711 /* istanbul ignore next */
21712 destructListeners.set(db.name, dbList);
21713 } else {
21714 destructListeners["delete"](db.name);
21715 }
21716 });
21717
21718 Pouch.on('destroyed', function onConstructorDestroyed(name) {
21719 if (!destructListeners.has(name)) {
21720 return;
21721 }
21722 var dbList = destructListeners.get(name);
21723 destructListeners["delete"](name);
21724 dbList.forEach(function (db) {
21725 db.emit('destroyed',true);
21726 });
21727 });
21728}
21729
21730setUpEventEmitter(PouchDB$1);
21731
21732PouchDB$1.adapter = function (id, obj, addToPreferredAdapters) {
21733 /* istanbul ignore else */
21734 if (obj.valid()) {
21735 PouchDB$1.adapters[id] = obj;
21736 if (addToPreferredAdapters) {
21737 PouchDB$1.preferredAdapters.push(id);
21738 }
21739 }
21740};
21741
21742PouchDB$1.plugin = function (obj) {
21743 if (typeof obj === 'function') { // function style for plugins
21744 obj(PouchDB$1);
21745 } else if (typeof obj !== 'object' || Object.keys(obj).length === 0) {
21746 throw new Error('Invalid plugin: got "' + obj + '", expected an object or a function');
21747 } else {
21748 Object.keys(obj).forEach(function (id) { // object style for plugins
21749 PouchDB$1.prototype[id] = obj[id];
21750 });
21751 }
21752 if (this.__defaults) {
21753 PouchDB$1.__defaults = $inject_Object_assign({}, this.__defaults);
21754 }
21755 return PouchDB$1;
21756};
21757
21758PouchDB$1.defaults = function (defaultOpts) {
21759 let PouchWithDefaults = createClass$1(PouchDB$1, function (name, opts) {
21760 opts = opts || {};
21761
21762 if (name && typeof name === 'object') {
21763 opts = name;
21764 name = opts.name;
21765 delete opts.name;
21766 }
21767
21768 opts = $inject_Object_assign({}, PouchWithDefaults.__defaults, opts);
21769 PouchDB$1.call(this, name, opts);
21770 });
21771
21772 PouchWithDefaults.preferredAdapters = PouchDB$1.preferredAdapters.slice();
21773 Object.keys(PouchDB$1).forEach(function (key) {
21774 if (!(key in PouchWithDefaults)) {
21775 PouchWithDefaults[key] = PouchDB$1[key];
21776 }
21777 });
21778
21779 // make default options transitive
21780 // https://github.com/pouchdb/pouchdb/issues/5922
21781 PouchWithDefaults.__defaults = $inject_Object_assign({}, this.__defaults, defaultOpts);
21782
21783 return PouchWithDefaults;
21784};
21785
21786PouchDB$1.fetch = function (url, opts) {
21787 return f$1(url, opts);
21788};
21789
21790PouchDB$1.prototype.activeTasks = PouchDB$1.activeTasks = new ActiveTasks();
21791
21792// managed automatically by set-version.js
21793var version$1 = "8.0.0";
21794
21795// this would just be "return doc[field]", but fields
21796// can be "deep" due to dot notation
21797function getFieldFromDoc(doc, parsedField) {
21798 var value = doc;
21799 for (var i = 0, len = parsedField.length; i < len; i++) {
21800 var key = parsedField[i];
21801 value = value[key];
21802 if (!value) {
21803 break;
21804 }
21805 }
21806 return value;
21807}
21808
21809function compare$1(left, right) {
21810 return left < right ? -1 : left > right ? 1 : 0;
21811}
21812
21813// Converts a string in dot notation to an array of its components, with backslash escaping
21814function parseField(fieldName) {
21815 // fields may be deep (e.g. "foo.bar.baz"), so parse
21816 var fields = [];
21817 var current = '';
21818 for (var i = 0, len = fieldName.length; i < len; i++) {
21819 var ch = fieldName[i];
21820 if (i > 0 && fieldName[i - 1] === '\\' && (ch === '$' || ch === '.')) {
21821 // escaped delimiter
21822 current = current.substring(0, current.length - 1) + ch;
21823 } else if (ch === '.') {
21824 // When `.` is not escaped (above), it is a field delimiter
21825 fields.push(current);
21826 current = '';
21827 } else { // normal character
21828 current += ch;
21829 }
21830 }
21831 fields.push(current);
21832 return fields;
21833}
21834
21835var combinationFields = ['$or', '$nor', '$not'];
21836function isCombinationalField(field) {
21837 return combinationFields.indexOf(field) > -1;
21838}
21839
21840function getKey(obj) {
21841 return Object.keys(obj)[0];
21842}
21843
21844function getValue(obj) {
21845 return obj[getKey(obj)];
21846}
21847
21848
21849// flatten an array of selectors joined by an $and operator
21850function mergeAndedSelectors(selectors) {
21851
21852 // sort to ensure that e.g. if the user specified
21853 // $and: [{$gt: 'a'}, {$gt: 'b'}], then it's collapsed into
21854 // just {$gt: 'b'}
21855 var res = {};
21856 var first = {$or: true, $nor: true};
21857
21858 selectors.forEach(function (selector) {
21859 Object.keys(selector).forEach(function (field) {
21860 var matcher = selector[field];
21861 if (typeof matcher !== 'object') {
21862 matcher = {$eq: matcher};
21863 }
21864
21865 if (isCombinationalField(field)) {
21866 // or, nor
21867 if (matcher instanceof Array) {
21868 if (first[field]) {
21869 first[field] = false;
21870 res[field] = matcher;
21871 return;
21872 }
21873
21874 var entries = [];
21875 res[field].forEach(function (existing) {
21876 Object.keys(matcher).forEach(function (key) {
21877 var m = matcher[key];
21878 var longest = Math.max(Object.keys(existing).length, Object.keys(m).length);
21879 var merged = mergeAndedSelectors([existing, m]);
21880 if (Object.keys(merged).length <= longest) {
21881 // we have a situation like: (a :{$eq :1} || ...) && (a {$eq: 2} || ...)
21882 // merging would produce a $eq 2 when actually we shouldn't ever match against these merged conditions
21883 // merged should always contain more values to be valid
21884 return;
21885 }
21886 entries.push(merged);
21887 });
21888 });
21889 res[field] = entries;
21890 } else {
21891 // not
21892 res[field] = mergeAndedSelectors([matcher]);
21893 }
21894 } else {
21895 var fieldMatchers = res[field] = res[field] || {};
21896 Object.keys(matcher).forEach(function (operator) {
21897 var value = matcher[operator];
21898
21899 if (operator === '$gt' || operator === '$gte') {
21900 return mergeGtGte(operator, value, fieldMatchers);
21901 } else if (operator === '$lt' || operator === '$lte') {
21902 return mergeLtLte(operator, value, fieldMatchers);
21903 } else if (operator === '$ne') {
21904 return mergeNe(value, fieldMatchers);
21905 } else if (operator === '$eq') {
21906 return mergeEq(value, fieldMatchers);
21907 } else if (operator === "$regex") {
21908 return mergeRegex(value, fieldMatchers);
21909 }
21910 fieldMatchers[operator] = value;
21911 });
21912 }
21913 });
21914 });
21915
21916 return res;
21917}
21918
21919
21920
21921// collapse logically equivalent gt/gte values
21922function mergeGtGte(operator, value, fieldMatchers) {
21923 if (typeof fieldMatchers.$eq !== 'undefined') {
21924 return; // do nothing
21925 }
21926 if (typeof fieldMatchers.$gte !== 'undefined') {
21927 if (operator === '$gte') {
21928 if (value > fieldMatchers.$gte) { // more specificity
21929 fieldMatchers.$gte = value;
21930 }
21931 } else { // operator === '$gt'
21932 if (value >= fieldMatchers.$gte) { // more specificity
21933 delete fieldMatchers.$gte;
21934 fieldMatchers.$gt = value;
21935 }
21936 }
21937 } else if (typeof fieldMatchers.$gt !== 'undefined') {
21938 if (operator === '$gte') {
21939 if (value > fieldMatchers.$gt) { // more specificity
21940 delete fieldMatchers.$gt;
21941 fieldMatchers.$gte = value;
21942 }
21943 } else { // operator === '$gt'
21944 if (value > fieldMatchers.$gt) { // more specificity
21945 fieldMatchers.$gt = value;
21946 }
21947 }
21948 } else {
21949 fieldMatchers[operator] = value;
21950 }
21951}
21952
21953// collapse logically equivalent lt/lte values
21954function mergeLtLte(operator, value, fieldMatchers) {
21955 if (typeof fieldMatchers.$eq !== 'undefined') {
21956 return; // do nothing
21957 }
21958 if (typeof fieldMatchers.$lte !== 'undefined') {
21959 if (operator === '$lte') {
21960 if (value < fieldMatchers.$lte) { // more specificity
21961 fieldMatchers.$lte = value;
21962 }
21963 } else { // operator === '$gt'
21964 if (value <= fieldMatchers.$lte) { // more specificity
21965 delete fieldMatchers.$lte;
21966 fieldMatchers.$lt = value;
21967 }
21968 }
21969 } else if (typeof fieldMatchers.$lt !== 'undefined') {
21970 if (operator === '$lte') {
21971 if (value < fieldMatchers.$lt) { // more specificity
21972 delete fieldMatchers.$lt;
21973 fieldMatchers.$lte = value;
21974 }
21975 } else { // operator === '$gt'
21976 if (value < fieldMatchers.$lt) { // more specificity
21977 fieldMatchers.$lt = value;
21978 }
21979 }
21980 } else {
21981 fieldMatchers[operator] = value;
21982 }
21983}
21984
21985// combine $ne values into one array
21986function mergeNe(value, fieldMatchers) {
21987 if ('$ne' in fieldMatchers) {
21988 // there are many things this could "not" be
21989 fieldMatchers.$ne.push(value);
21990 } else { // doesn't exist yet
21991 fieldMatchers.$ne = [value];
21992 }
21993}
21994
21995// add $eq into the mix
21996function mergeEq(value, fieldMatchers) {
21997 // these all have less specificity than the $eq
21998 // TODO: check for user errors here
21999 delete fieldMatchers.$gt;
22000 delete fieldMatchers.$gte;
22001 delete fieldMatchers.$lt;
22002 delete fieldMatchers.$lte;
22003 delete fieldMatchers.$ne;
22004 fieldMatchers.$eq = value;
22005}
22006
22007// combine $regex values into one array
22008function mergeRegex(value, fieldMatchers) {
22009 if ('$regex' in fieldMatchers) {
22010 // a value could match multiple regexes
22011 fieldMatchers.$regex.push(value);
22012 } else { // doesn't exist yet
22013 fieldMatchers.$regex = [value];
22014 }
22015}
22016
22017//#7458: execute function mergeAndedSelectors on nested $and
22018function mergeAndedSelectorsNested(obj) {
22019 for (var prop in obj) {
22020 if (Array.isArray(obj)) {
22021 for (var i in obj) {
22022 if (obj[i]['$and']) {
22023 obj[i] = mergeAndedSelectors(obj[i]['$and']);
22024 }
22025 }
22026 }
22027 var value = obj[prop];
22028 if (typeof value === 'object') {
22029 mergeAndedSelectorsNested(value); // <- recursive call
22030 }
22031 }
22032 return obj;
22033}
22034
22035//#7458: determine id $and is present in selector (at any level)
22036function isAndInSelector(obj, isAnd) {
22037 for (var prop in obj) {
22038 if (prop === '$and') {
22039 isAnd = true;
22040 }
22041 var value = obj[prop];
22042 if (typeof value === 'object') {
22043 isAnd = isAndInSelector(value, isAnd); // <- recursive call
22044 }
22045 }
22046 return isAnd;
22047}
22048
22049//
22050// normalize the selector
22051//
22052function massageSelector(input) {
22053 var result = clone(input);
22054
22055 //#7458: if $and is present in selector (at any level) merge nested $and
22056 if (isAndInSelector(result, false)) {
22057 result = mergeAndedSelectorsNested(result);
22058 if ('$and' in result) {
22059 result = mergeAndedSelectors(result['$and']);
22060 }
22061 }
22062
22063 ['$or', '$nor'].forEach(function (orOrNor) {
22064 if (orOrNor in result) {
22065 // message each individual selector
22066 // e.g. {foo: 'bar'} becomes {foo: {$eq: 'bar'}}
22067 result[orOrNor].forEach(function (subSelector) {
22068 var fields = Object.keys(subSelector);
22069 for (var i = 0; i < fields.length; i++) {
22070 var field = fields[i];
22071 var matcher = subSelector[field];
22072 if (typeof matcher !== 'object' || matcher === null) {
22073 subSelector[field] = {$eq: matcher};
22074 }
22075 }
22076 });
22077 }
22078 });
22079
22080 if ('$not' in result) {
22081 //This feels a little like forcing, but it will work for now,
22082 //I would like to come back to this and make the merging of selectors a little more generic
22083 result['$not'] = mergeAndedSelectors([result['$not']]);
22084 }
22085
22086 var fields = Object.keys(result);
22087
22088 for (var i = 0; i < fields.length; i++) {
22089 var field = fields[i];
22090 var matcher = result[field];
22091
22092 if (typeof matcher !== 'object' || matcher === null) {
22093 matcher = {$eq: matcher};
22094 }
22095 result[field] = matcher;
22096 }
22097
22098 normalizeArrayOperators(result);
22099
22100 return result;
22101}
22102
22103//
22104// The $ne and $regex values must be placed in an array because these operators can be used multiple times on the same field.
22105// When $and is used, mergeAndedSelectors takes care of putting some of them into arrays, otherwise it's done here.
22106//
22107function normalizeArrayOperators(selector) {
22108 Object.keys(selector).forEach(function (field) {
22109 var matcher = selector[field];
22110
22111 if (Array.isArray(matcher)) {
22112 matcher.forEach(function (matcherItem) {
22113 if (matcherItem && typeof matcherItem === 'object') {
22114 normalizeArrayOperators(matcherItem);
22115 }
22116 });
22117 } else if (field === '$ne') {
22118 selector.$ne = [matcher];
22119 } else if (field === '$regex') {
22120 selector.$regex = [matcher];
22121 } else if (matcher && typeof matcher === 'object') {
22122 normalizeArrayOperators(matcher);
22123 }
22124 });
22125}
22126
22127function collate(a, b) {
22128
22129 if (a === b) {
22130 return 0;
22131 }
22132
22133 a = normalizeKey(a);
22134 b = normalizeKey(b);
22135
22136 var ai = collationIndex(a);
22137 var bi = collationIndex(b);
22138 if ((ai - bi) !== 0) {
22139 return ai - bi;
22140 }
22141 switch (typeof a) {
22142 case 'number':
22143 return a - b;
22144 case 'boolean':
22145 return a < b ? -1 : 1;
22146 case 'string':
22147 return stringCollate(a, b);
22148 }
22149 return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);
22150}
22151
22152// couch considers null/NaN/Infinity/-Infinity === undefined,
22153// for the purposes of mapreduce indexes. also, dates get stringified.
22154function normalizeKey(key) {
22155 switch (typeof key) {
22156 case 'undefined':
22157 return null;
22158 case 'number':
22159 if (key === Infinity || key === -Infinity || isNaN(key)) {
22160 return null;
22161 }
22162 return key;
22163 case 'object':
22164 var origKey = key;
22165 if (Array.isArray(key)) {
22166 var len = key.length;
22167 key = new Array(len);
22168 for (var i = 0; i < len; i++) {
22169 key[i] = normalizeKey(origKey[i]);
22170 }
22171 /* istanbul ignore next */
22172 } else if (key instanceof Date) {
22173 return key.toJSON();
22174 } else if (key !== null) { // generic object
22175 key = {};
22176 for (var k in origKey) {
22177 if (Object.prototype.hasOwnProperty.call(origKey, k)) {
22178 var val = origKey[k];
22179 if (typeof val !== 'undefined') {
22180 key[k] = normalizeKey(val);
22181 }
22182 }
22183 }
22184 }
22185 }
22186 return key;
22187}
22188
22189function arrayCollate(a, b) {
22190 var len = Math.min(a.length, b.length);
22191 for (var i = 0; i < len; i++) {
22192 var sort = collate(a[i], b[i]);
22193 if (sort !== 0) {
22194 return sort;
22195 }
22196 }
22197 return (a.length === b.length) ? 0 :
22198 (a.length > b.length) ? 1 : -1;
22199}
22200function stringCollate(a, b) {
22201 // See: https://github.com/daleharvey/pouchdb/issues/40
22202 // This is incompatible with the CouchDB implementation, but its the
22203 // best we can do for now
22204 return (a === b) ? 0 : ((a > b) ? 1 : -1);
22205}
22206function objectCollate(a, b) {
22207 var ak = Object.keys(a), bk = Object.keys(b);
22208 var len = Math.min(ak.length, bk.length);
22209 for (var i = 0; i < len; i++) {
22210 // First sort the keys
22211 var sort = collate(ak[i], bk[i]);
22212 if (sort !== 0) {
22213 return sort;
22214 }
22215 // if the keys are equal sort the values
22216 sort = collate(a[ak[i]], b[bk[i]]);
22217 if (sort !== 0) {
22218 return sort;
22219 }
22220
22221 }
22222 return (ak.length === bk.length) ? 0 :
22223 (ak.length > bk.length) ? 1 : -1;
22224}
22225// The collation is defined by erlangs ordered terms
22226// the atoms null, true, false come first, then numbers, strings,
22227// arrays, then objects
22228// null/undefined/NaN/Infinity/-Infinity are all considered null
22229function collationIndex(x) {
22230 var id = ['boolean', 'number', 'string', 'object'];
22231 var idx = id.indexOf(typeof x);
22232 //false if -1 otherwise true, but fast!!!!1
22233 if (~idx) {
22234 if (x === null) {
22235 return 1;
22236 }
22237 if (Array.isArray(x)) {
22238 return 5;
22239 }
22240 return idx < 3 ? (idx + 2) : (idx + 3);
22241 }
22242 /* istanbul ignore next */
22243 if (Array.isArray(x)) {
22244 return 5;
22245 }
22246}
22247
22248// create a comparator based on the sort object
22249function createFieldSorter(sort) {
22250
22251 function getFieldValuesAsArray(doc) {
22252 return sort.map(function (sorting) {
22253 var fieldName = getKey(sorting);
22254 var parsedField = parseField(fieldName);
22255 var docFieldValue = getFieldFromDoc(doc, parsedField);
22256 return docFieldValue;
22257 });
22258 }
22259
22260 return function (aRow, bRow) {
22261 var aFieldValues = getFieldValuesAsArray(aRow.doc);
22262 var bFieldValues = getFieldValuesAsArray(bRow.doc);
22263 var collation = collate(aFieldValues, bFieldValues);
22264 if (collation !== 0) {
22265 return collation;
22266 }
22267 // this is what mango seems to do
22268 return compare$1(aRow.doc._id, bRow.doc._id);
22269 };
22270}
22271
22272function filterInMemoryFields(rows, requestDef, inMemoryFields) {
22273 rows = rows.filter(function (row) {
22274 return rowFilter(row.doc, requestDef.selector, inMemoryFields);
22275 });
22276
22277 if (requestDef.sort) {
22278 // in-memory sort
22279 var fieldSorter = createFieldSorter(requestDef.sort);
22280 rows = rows.sort(fieldSorter);
22281 if (typeof requestDef.sort[0] !== 'string' &&
22282 getValue(requestDef.sort[0]) === 'desc') {
22283 rows = rows.reverse();
22284 }
22285 }
22286
22287 if ('limit' in requestDef || 'skip' in requestDef) {
22288 // have to do the limit in-memory
22289 var skip = requestDef.skip || 0;
22290 var limit = ('limit' in requestDef ? requestDef.limit : rows.length) + skip;
22291 rows = rows.slice(skip, limit);
22292 }
22293 return rows;
22294}
22295
22296function rowFilter(doc, selector, inMemoryFields) {
22297 return inMemoryFields.every(function (field) {
22298 var matcher = selector[field];
22299 var parsedField = parseField(field);
22300 var docFieldValue = getFieldFromDoc(doc, parsedField);
22301 if (isCombinationalField(field)) {
22302 return matchCominationalSelector(field, matcher, doc);
22303 }
22304
22305 return matchSelector(matcher, doc, parsedField, docFieldValue);
22306 });
22307}
22308
22309function matchSelector(matcher, doc, parsedField, docFieldValue) {
22310 if (!matcher) {
22311 // no filtering necessary; this field is just needed for sorting
22312 return true;
22313 }
22314
22315 // is matcher an object, if so continue recursion
22316 if (typeof matcher === 'object') {
22317 return Object.keys(matcher).every(function (maybeUserOperator) {
22318 var userValue = matcher[ maybeUserOperator ];
22319 // explicit operator
22320 if (maybeUserOperator.indexOf("$") === 0) {
22321 return match(maybeUserOperator, doc, userValue, parsedField, docFieldValue);
22322 } else {
22323 var subParsedField = parseField(maybeUserOperator);
22324
22325 if (
22326 docFieldValue === undefined &&
22327 typeof userValue !== "object" &&
22328 subParsedField.length > 0
22329 ) {
22330 // the field does not exist, return or getFieldFromDoc will throw
22331 return false;
22332 }
22333
22334 var subDocFieldValue = getFieldFromDoc(docFieldValue, subParsedField);
22335
22336 if (typeof userValue === "object") {
22337 // field value is an object that might contain more operators
22338 return matchSelector(userValue, doc, parsedField, subDocFieldValue);
22339 }
22340
22341 // implicit operator
22342 return match("$eq", doc, userValue, subParsedField, subDocFieldValue);
22343 }
22344 });
22345 }
22346
22347 // no more depth, No need to recurse further
22348 return matcher === docFieldValue;
22349}
22350
22351function matchCominationalSelector(field, matcher, doc) {
22352
22353 if (field === '$or') {
22354 return matcher.some(function (orMatchers) {
22355 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
22356 });
22357 }
22358
22359 if (field === '$not') {
22360 return !rowFilter(doc, matcher, Object.keys(matcher));
22361 }
22362
22363 //`$nor`
22364 return !matcher.find(function (orMatchers) {
22365 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
22366 });
22367
22368}
22369
22370function match(userOperator, doc, userValue, parsedField, docFieldValue) {
22371 if (!matchers[userOperator]) {
22372 /* istanbul ignore next */
22373 throw new Error('unknown operator "' + userOperator +
22374 '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, ' +
22375 '$nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
22376 }
22377 return matchers[userOperator](doc, userValue, parsedField, docFieldValue);
22378}
22379
22380function fieldExists(docFieldValue) {
22381 return typeof docFieldValue !== 'undefined' && docFieldValue !== null;
22382}
22383
22384function fieldIsNotUndefined(docFieldValue) {
22385 return typeof docFieldValue !== 'undefined';
22386}
22387
22388function modField(docFieldValue, userValue) {
22389 if (typeof docFieldValue !== "number" ||
22390 parseInt(docFieldValue, 10) !== docFieldValue) {
22391 return false;
22392 }
22393
22394 var divisor = userValue[0];
22395 var mod = userValue[1];
22396
22397 return docFieldValue % divisor === mod;
22398}
22399
22400function arrayContainsValue(docFieldValue, userValue) {
22401 return userValue.some(function (val) {
22402 if (docFieldValue instanceof Array) {
22403 return docFieldValue.some(function (docFieldValueItem) {
22404 return collate(val, docFieldValueItem) === 0;
22405 });
22406 }
22407
22408 return collate(val, docFieldValue) === 0;
22409 });
22410}
22411
22412function arrayContainsAllValues(docFieldValue, userValue) {
22413 return userValue.every(function (val) {
22414 return docFieldValue.some(function (docFieldValueItem) {
22415 return collate(val, docFieldValueItem) === 0;
22416 });
22417 });
22418}
22419
22420function arraySize(docFieldValue, userValue) {
22421 return docFieldValue.length === userValue;
22422}
22423
22424function regexMatch(docFieldValue, userValue) {
22425 var re = new RegExp(userValue);
22426
22427 return re.test(docFieldValue);
22428}
22429
22430function typeMatch(docFieldValue, userValue) {
22431
22432 switch (userValue) {
22433 case 'null':
22434 return docFieldValue === null;
22435 case 'boolean':
22436 return typeof (docFieldValue) === 'boolean';
22437 case 'number':
22438 return typeof (docFieldValue) === 'number';
22439 case 'string':
22440 return typeof (docFieldValue) === 'string';
22441 case 'array':
22442 return docFieldValue instanceof Array;
22443 case 'object':
22444 return ({}).toString.call(docFieldValue) === '[object Object]';
22445 }
22446}
22447
22448var matchers = {
22449
22450 '$elemMatch': function (doc, userValue, parsedField, docFieldValue) {
22451 if (!Array.isArray(docFieldValue)) {
22452 return false;
22453 }
22454
22455 if (docFieldValue.length === 0) {
22456 return false;
22457 }
22458
22459 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
22460 return docFieldValue.some(function (val) {
22461 return rowFilter(val, userValue, Object.keys(userValue));
22462 });
22463 }
22464
22465 return docFieldValue.some(function (val) {
22466 return matchSelector(userValue, doc, parsedField, val);
22467 });
22468 },
22469
22470 '$allMatch': function (doc, userValue, parsedField, docFieldValue) {
22471 if (!Array.isArray(docFieldValue)) {
22472 return false;
22473 }
22474
22475 /* istanbul ignore next */
22476 if (docFieldValue.length === 0) {
22477 return false;
22478 }
22479
22480 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
22481 return docFieldValue.every(function (val) {
22482 return rowFilter(val, userValue, Object.keys(userValue));
22483 });
22484 }
22485
22486 return docFieldValue.every(function (val) {
22487 return matchSelector(userValue, doc, parsedField, val);
22488 });
22489 },
22490
22491 '$eq': function (doc, userValue, parsedField, docFieldValue) {
22492 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0;
22493 },
22494
22495 '$gte': function (doc, userValue, parsedField, docFieldValue) {
22496 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0;
22497 },
22498
22499 '$gt': function (doc, userValue, parsedField, docFieldValue) {
22500 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0;
22501 },
22502
22503 '$lte': function (doc, userValue, parsedField, docFieldValue) {
22504 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0;
22505 },
22506
22507 '$lt': function (doc, userValue, parsedField, docFieldValue) {
22508 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0;
22509 },
22510
22511 '$exists': function (doc, userValue, parsedField, docFieldValue) {
22512 //a field that is null is still considered to exist
22513 if (userValue) {
22514 return fieldIsNotUndefined(docFieldValue);
22515 }
22516
22517 return !fieldIsNotUndefined(docFieldValue);
22518 },
22519
22520 '$mod': function (doc, userValue, parsedField, docFieldValue) {
22521 return fieldExists(docFieldValue) && modField(docFieldValue, userValue);
22522 },
22523
22524 '$ne': function (doc, userValue, parsedField, docFieldValue) {
22525 return userValue.every(function (neValue) {
22526 return collate(docFieldValue, neValue) !== 0;
22527 });
22528 },
22529 '$in': function (doc, userValue, parsedField, docFieldValue) {
22530 return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue);
22531 },
22532
22533 '$nin': function (doc, userValue, parsedField, docFieldValue) {
22534 return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue);
22535 },
22536
22537 '$size': function (doc, userValue, parsedField, docFieldValue) {
22538 return fieldExists(docFieldValue) &&
22539 Array.isArray(docFieldValue) &&
22540 arraySize(docFieldValue, userValue);
22541 },
22542
22543 '$all': function (doc, userValue, parsedField, docFieldValue) {
22544 return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue);
22545 },
22546
22547 '$regex': function (doc, userValue, parsedField, docFieldValue) {
22548 return fieldExists(docFieldValue) &&
22549 typeof docFieldValue == "string" &&
22550 userValue.every(function (regexValue) {
22551 return regexMatch(docFieldValue, regexValue);
22552 });
22553 },
22554
22555 '$type': function (doc, userValue, parsedField, docFieldValue) {
22556 return typeMatch(docFieldValue, userValue);
22557 }
22558};
22559
22560// return true if the given doc matches the supplied selector
22561function matchesSelector(doc, selector) {
22562 /* istanbul ignore if */
22563 if (typeof selector !== 'object') {
22564 // match the CouchDB error message
22565 throw new Error('Selector error: expected a JSON object');
22566 }
22567
22568 selector = massageSelector(selector);
22569 var row = {
22570 'doc': doc
22571 };
22572
22573 var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));
22574 return rowsMatched && rowsMatched.length === 1;
22575}
22576
22577function evalFilter(input) {
22578 return scopeEval('"use strict";\nreturn ' + input + ';', {});
22579}
22580
22581function evalView(input) {
22582 var code = [
22583 'return function(doc) {',
22584 ' "use strict";',
22585 ' var emitted = false;',
22586 ' var emit = function (a, b) {',
22587 ' emitted = true;',
22588 ' };',
22589 ' var view = ' + input + ';',
22590 ' view(doc);',
22591 ' if (emitted) {',
22592 ' return true;',
22593 ' }',
22594 '};'
22595 ].join('\n');
22596
22597 return scopeEval(code, {});
22598}
22599
22600function validate(opts, callback) {
22601 if (opts.selector) {
22602 if (opts.filter && opts.filter !== '_selector') {
22603 var filterName = typeof opts.filter === 'string' ?
22604 opts.filter : 'function';
22605 return callback(new Error('selector invalid for filter "' + filterName + '"'));
22606 }
22607 }
22608 callback();
22609}
22610
22611function normalize(opts) {
22612 if (opts.view && !opts.filter) {
22613 opts.filter = '_view';
22614 }
22615
22616 if (opts.selector && !opts.filter) {
22617 opts.filter = '_selector';
22618 }
22619
22620 if (opts.filter && typeof opts.filter === 'string') {
22621 if (opts.filter === '_view') {
22622 opts.view = normalizeDesignDocFunctionName(opts.view);
22623 } else {
22624 opts.filter = normalizeDesignDocFunctionName(opts.filter);
22625 }
22626 }
22627}
22628
22629function shouldFilter(changesHandler, opts) {
22630 return opts.filter && typeof opts.filter === 'string' &&
22631 !opts.doc_ids && !isRemote(changesHandler.db);
22632}
22633
22634function filter(changesHandler, opts) {
22635 var callback = opts.complete;
22636 if (opts.filter === '_view') {
22637 if (!opts.view || typeof opts.view !== 'string') {
22638 var err = createError(BAD_REQUEST,
22639 '`view` filter parameter not found or invalid.');
22640 return callback(err);
22641 }
22642 // fetch a view from a design doc, make it behave like a filter
22643 var viewName = parseDesignDocFunctionName(opts.view);
22644 changesHandler.db.get('_design/' + viewName[0], function (err, ddoc) {
22645 /* istanbul ignore if */
22646 if (changesHandler.isCancelled) {
22647 return callback(null, {status: 'cancelled'});
22648 }
22649 /* istanbul ignore next */
22650 if (err) {
22651 return callback(generateErrorFromResponse(err));
22652 }
22653 var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&
22654 ddoc.views[viewName[1]].map;
22655 if (!mapFun) {
22656 return callback(createError(MISSING_DOC,
22657 (ddoc.views ? 'missing json key: ' + viewName[1] :
22658 'missing json key: views')));
22659 }
22660 opts.filter = evalView(mapFun);
22661 changesHandler.doChanges(opts);
22662 });
22663 } else if (opts.selector) {
22664 opts.filter = function (doc) {
22665 return matchesSelector(doc, opts.selector);
22666 };
22667 changesHandler.doChanges(opts);
22668 } else {
22669 // fetch a filter from a design doc
22670 var filterName = parseDesignDocFunctionName(opts.filter);
22671 changesHandler.db.get('_design/' + filterName[0], function (err, ddoc) {
22672 /* istanbul ignore if */
22673 if (changesHandler.isCancelled) {
22674 return callback(null, {status: 'cancelled'});
22675 }
22676 /* istanbul ignore next */
22677 if (err) {
22678 return callback(generateErrorFromResponse(err));
22679 }
22680 var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];
22681 if (!filterFun) {
22682 return callback(createError(MISSING_DOC,
22683 ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]
22684 : 'missing json key: filters')));
22685 }
22686 opts.filter = evalFilter(filterFun);
22687 changesHandler.doChanges(opts);
22688 });
22689 }
22690}
22691
22692function applyChangesFilterPlugin(PouchDB) {
22693 PouchDB._changesFilterPlugin = {
22694 validate: validate,
22695 normalize: normalize,
22696 shouldFilter: shouldFilter,
22697 filter: filter
22698 };
22699}
22700
22701// TODO: remove from pouchdb-core (breaking)
22702PouchDB$1.plugin(applyChangesFilterPlugin);
22703
22704PouchDB$1.version = version$1;
22705
22706function allDocsKeysQuery(api, opts) {
22707 var keys = opts.keys;
22708 var finalResults = {
22709 offset: opts.skip
22710 };
22711 return Promise.all(keys.map(function (key) {
22712 var subOpts = $inject_Object_assign({key: key, deleted: 'ok'}, opts);
22713 ['limit', 'skip', 'keys'].forEach(function (optKey) {
22714 delete subOpts[optKey];
22715 });
22716 return new Promise(function (resolve, reject) {
22717 api._allDocs(subOpts, function (err, res) {
22718 /* istanbul ignore if */
22719 if (err) {
22720 return reject(err);
22721 }
22722 /* istanbul ignore if */
22723 if (opts.update_seq && res.update_seq !== undefined) {
22724 finalResults.update_seq = res.update_seq;
22725 }
22726 finalResults.total_rows = res.total_rows;
22727 resolve(res.rows[0] || {key: key, error: 'not_found'});
22728 });
22729 });
22730 })).then(function (results) {
22731 finalResults.rows = results;
22732 return finalResults;
22733 });
22734}
22735
22736function toObject(array) {
22737 return array.reduce(function (obj, item) {
22738 obj[item] = true;
22739 return obj;
22740 }, {});
22741}
22742// List of top level reserved words for doc
22743var reservedWords = toObject([
22744 '_id',
22745 '_rev',
22746 '_access',
22747 '_attachments',
22748 '_deleted',
22749 '_revisions',
22750 '_revs_info',
22751 '_conflicts',
22752 '_deleted_conflicts',
22753 '_local_seq',
22754 '_rev_tree',
22755 // replication documents
22756 '_replication_id',
22757 '_replication_state',
22758 '_replication_state_time',
22759 '_replication_state_reason',
22760 '_replication_stats',
22761 // Specific to Couchbase Sync Gateway
22762 '_removed'
22763]);
22764
22765// List of reserved words that should end up in the document
22766var dataWords = toObject([
22767 '_access',
22768 '_attachments',
22769 // replication documents
22770 '_replication_id',
22771 '_replication_state',
22772 '_replication_state_time',
22773 '_replication_state_reason',
22774 '_replication_stats'
22775]);
22776
22777function parseRevisionInfo(rev) {
22778 if (!/^\d+-/.test(rev)) {
22779 return createError(INVALID_REV);
22780 }
22781 var idx = rev.indexOf('-');
22782 var left = rev.substring(0, idx);
22783 var right = rev.substring(idx + 1);
22784 return {
22785 prefix: parseInt(left, 10),
22786 id: right
22787 };
22788}
22789
22790function makeRevTreeFromRevisions(revisions, opts) {
22791 var pos = revisions.start - revisions.ids.length + 1;
22792
22793 var revisionIds = revisions.ids;
22794 var ids = [revisionIds[0], opts, []];
22795
22796 for (var i = 1, len = revisionIds.length; i < len; i++) {
22797 ids = [revisionIds[i], {status: 'missing'}, [ids]];
22798 }
22799
22800 return [{
22801 pos: pos,
22802 ids: ids
22803 }];
22804}
22805
22806// Preprocess documents, parse their revisions, assign an id and a
22807// revision for new writes that are missing them, etc
22808function parseDoc(doc, newEdits, dbOpts) {
22809 if (!dbOpts) {
22810 dbOpts = {
22811 deterministic_revs: true
22812 };
22813 }
22814
22815 var nRevNum;
22816 var newRevId;
22817 var revInfo;
22818 var opts = {status: 'available'};
22819 if (doc._deleted) {
22820 opts.deleted = true;
22821 }
22822
22823 if (newEdits) {
22824 if (!doc._id) {
22825 doc._id = uuid$1();
22826 }
22827 newRevId = rev$$1(doc, dbOpts.deterministic_revs);
22828 if (doc._rev) {
22829 revInfo = parseRevisionInfo(doc._rev);
22830 if (revInfo.error) {
22831 return revInfo;
22832 }
22833 doc._rev_tree = [{
22834 pos: revInfo.prefix,
22835 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
22836 }];
22837 nRevNum = revInfo.prefix + 1;
22838 } else {
22839 doc._rev_tree = [{
22840 pos: 1,
22841 ids : [newRevId, opts, []]
22842 }];
22843 nRevNum = 1;
22844 }
22845 } else {
22846 if (doc._revisions) {
22847 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
22848 nRevNum = doc._revisions.start;
22849 newRevId = doc._revisions.ids[0];
22850 }
22851 if (!doc._rev_tree) {
22852 revInfo = parseRevisionInfo(doc._rev);
22853 if (revInfo.error) {
22854 return revInfo;
22855 }
22856 nRevNum = revInfo.prefix;
22857 newRevId = revInfo.id;
22858 doc._rev_tree = [{
22859 pos: nRevNum,
22860 ids: [newRevId, opts, []]
22861 }];
22862 }
22863 }
22864
22865 invalidIdError(doc._id);
22866
22867 doc._rev = nRevNum + '-' + newRevId;
22868
22869 var result = {metadata : {}, data : {}};
22870 for (var key in doc) {
22871 /* istanbul ignore else */
22872 if (Object.prototype.hasOwnProperty.call(doc, key)) {
22873 var specialKey = key[0] === '_';
22874 if (specialKey && !reservedWords[key]) {
22875 var error = createError(DOC_VALIDATION, key);
22876 error.message = DOC_VALIDATION.message + ': ' + key;
22877 throw error;
22878 } else if (specialKey && !dataWords[key]) {
22879 result.metadata[key.slice(1)] = doc[key];
22880 } else {
22881 result.data[key] = doc[key];
22882 }
22883 }
22884 }
22885 return result;
22886}
22887
22888function updateDoc(revLimit, prev, docInfo, results,
22889 i, cb, writeDoc, newEdits) {
22890
22891 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
22892 results[i] = docInfo;
22893 return cb();
22894 }
22895
22896 // sometimes this is pre-calculated. historically not always
22897 var previousWinningRev = prev.winningRev || winningRev(prev);
22898 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
22899 isDeleted(prev, previousWinningRev);
22900 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
22901 isDeleted(docInfo.metadata);
22902 var isRoot = /^1-/.test(docInfo.metadata.rev);
22903
22904 if (previouslyDeleted && !deleted && newEdits && isRoot) {
22905 var newDoc = docInfo.data;
22906 newDoc._rev = previousWinningRev;
22907 newDoc._id = docInfo.metadata.id;
22908 docInfo = parseDoc(newDoc, newEdits);
22909 }
22910
22911 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
22912
22913 var inConflict = newEdits && ((
22914 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
22915 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
22916 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
22917
22918 if (inConflict) {
22919 var err = createError(REV_CONFLICT);
22920 results[i] = err;
22921 return cb();
22922 }
22923
22924 var newRev = docInfo.metadata.rev;
22925 docInfo.metadata.rev_tree = merged.tree;
22926 docInfo.stemmedRevs = merged.stemmedRevs || [];
22927 /* istanbul ignore else */
22928 if (prev.rev_map) {
22929 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
22930 }
22931
22932 // recalculate
22933 var winningRev$$1 = winningRev(docInfo.metadata);
22934 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
22935
22936 // calculate the total number of documents that were added/removed,
22937 // from the perspective of total_rows/doc_count
22938 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
22939 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
22940
22941 var newRevIsDeleted;
22942 if (newRev === winningRev$$1) {
22943 // if the new rev is the same as the winning rev, we can reuse that value
22944 newRevIsDeleted = winningRevIsDeleted;
22945 } else {
22946 // if they're not the same, then we need to recalculate
22947 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
22948 }
22949
22950 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
22951 true, delta, i, cb);
22952}
22953
22954function rootIsMissing(docInfo) {
22955 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
22956}
22957
22958function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
22959 writeDoc, opts, overallCallback) {
22960
22961 // Default to 1000 locally
22962 revLimit = revLimit || 1000;
22963
22964 function insertDoc(docInfo, resultsIdx, callback) {
22965 // Cant insert new deleted documents
22966 var winningRev$$1 = winningRev(docInfo.metadata);
22967 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
22968 if ('was_delete' in opts && deleted) {
22969 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
22970 return callback();
22971 }
22972
22973 // 4712 - detect whether a new document was inserted with a _rev
22974 var inConflict = newEdits && rootIsMissing(docInfo);
22975
22976 if (inConflict) {
22977 var err = createError(REV_CONFLICT);
22978 results[resultsIdx] = err;
22979 return callback();
22980 }
22981
22982 var delta = deleted ? 0 : 1;
22983
22984 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
22985 delta, resultsIdx, callback);
22986 }
22987
22988 var newEdits = opts.new_edits;
22989 var idsToDocs = new ExportedMap();
22990
22991 var docsDone = 0;
22992 var docsToDo = docInfos.length;
22993
22994 function checkAllDocsDone() {
22995 if (++docsDone === docsToDo && overallCallback) {
22996 overallCallback();
22997 }
22998 }
22999
23000 docInfos.forEach(function (currentDoc, resultsIdx) {
23001
23002 if (currentDoc._id && isLocalId(currentDoc._id)) {
23003 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
23004 api[fun](currentDoc, {ctx: tx}, function (err, res) {
23005 results[resultsIdx] = err || res;
23006 checkAllDocsDone();
23007 });
23008 return;
23009 }
23010
23011 var id = currentDoc.metadata.id;
23012 if (idsToDocs.has(id)) {
23013 docsToDo--; // duplicate
23014 idsToDocs.get(id).push([currentDoc, resultsIdx]);
23015 } else {
23016 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
23017 }
23018 });
23019
23020 // in the case of new_edits, the user can provide multiple docs
23021 // with the same id. these need to be processed sequentially
23022 idsToDocs.forEach(function (docs, id) {
23023 var numDone = 0;
23024
23025 function docWritten() {
23026 if (++numDone < docs.length) {
23027 nextDoc();
23028 } else {
23029 checkAllDocsDone();
23030 }
23031 }
23032 function nextDoc() {
23033 var value = docs[numDone];
23034 var currentDoc = value[0];
23035 var resultsIdx = value[1];
23036
23037 if (fetchedDocs.has(id)) {
23038 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
23039 resultsIdx, docWritten, writeDoc, newEdits);
23040 } else {
23041 // Ensure stemming applies to new writes as well
23042 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
23043 currentDoc.metadata.rev_tree = merged.tree;
23044 currentDoc.stemmedRevs = merged.stemmedRevs || [];
23045 insertDoc(currentDoc, resultsIdx, docWritten);
23046 }
23047 }
23048 nextDoc();
23049 });
23050}
23051
23052function safeJsonParse(str) {
23053 // This try/catch guards against stack overflow errors.
23054 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
23055 // cannot overflow.
23056 try {
23057 return JSON.parse(str);
23058 } catch (e) {
23059 /* istanbul ignore next */
23060 return vuvuzela.parse(str);
23061 }
23062}
23063
23064function safeJsonStringify(json) {
23065 try {
23066 return JSON.stringify(json);
23067 } catch (e) {
23068 /* istanbul ignore next */
23069 return vuvuzela.stringify(json);
23070 }
23071}
23072
23073function readAsBlobOrBuffer(storedObject, type) {
23074 // In the browser, we've stored a binary string. This now comes back as a
23075 // browserified Node-style Buffer (implemented as a typed array),
23076 // but we want a Blob instead.
23077 var byteArray = new Uint8Array(storedObject);
23078 return createBlob([byteArray], {type: type});
23079}
23080
23081// In the browser, we store a binary string
23082function prepareAttachmentForStorage(attData, cb) {
23083 readAsBinaryString(attData, cb);
23084}
23085
23086function createEmptyBlobOrBuffer(type) {
23087 return createBlob([''], {type: type});
23088}
23089
23090function getCacheFor(transaction, store) {
23091 var prefix = store.prefix()[0];
23092 var cache = transaction._cache;
23093 var subCache = cache.get(prefix);
23094 if (!subCache) {
23095 subCache = new ExportedMap();
23096 cache.set(prefix, subCache);
23097 }
23098 return subCache;
23099}
23100
23101class LevelTransaction {
23102 constructor() {
23103 this._batch = [];
23104 this._cache = new ExportedMap();
23105 }
23106
23107 get(store, key, callback) {
23108 var cache = getCacheFor(this, store);
23109 var exists = cache.get(key);
23110 if (exists) {
23111 return immediate(function () {
23112 callback(null, exists);
23113 });
23114 } else if (exists === null) { // deleted marker
23115 /* istanbul ignore next */
23116 return immediate(function () {
23117 callback({name: 'NotFoundError'});
23118 });
23119 }
23120 store.get(key, function (err, res) {
23121 if (err) {
23122 /* istanbul ignore else */
23123 if (err.name === 'NotFoundError') {
23124 cache.set(key, null);
23125 }
23126 return callback(err);
23127 }
23128 cache.set(key, res);
23129 callback(null, res);
23130 });
23131 }
23132
23133 batch(batch) {
23134 for (var i = 0, len = batch.length; i < len; i++) {
23135 var operation = batch[i];
23136
23137 var cache = getCacheFor(this, operation.prefix);
23138
23139 if (operation.type === 'put') {
23140 cache.set(operation.key, operation.value);
23141 } else {
23142 cache.set(operation.key, null);
23143 }
23144 }
23145 this._batch = this._batch.concat(batch);
23146 }
23147
23148 execute(db, callback) {
23149 var keys = new ExportedSet();
23150 var uniqBatches = [];
23151
23152 // remove duplicates; last one wins
23153 for (var i = this._batch.length - 1; i >= 0; i--) {
23154 var operation = this._batch[i];
23155 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
23156 if (keys.has(lookupKey)) {
23157 continue;
23158 }
23159 keys.add(lookupKey);
23160 uniqBatches.push(operation);
23161 }
23162
23163 db.batch(uniqBatches, callback);
23164 }
23165}
23166
23167var DOC_STORE = 'document-store';
23168var BY_SEQ_STORE = 'by-sequence';
23169var ATTACHMENT_STORE = 'attach-store';
23170var BINARY_STORE = 'attach-binary-store';
23171var LOCAL_STORE = 'local-store';
23172var META_STORE = 'meta-store';
23173
23174// leveldb barks if we try to open a db multiple times
23175// so we cache opened connections here for initstore()
23176var dbStores = new ExportedMap();
23177
23178// store the value of update_seq in the by-sequence store the key name will
23179// never conflict, since the keys in the by-sequence store are integers
23180var UPDATE_SEQ_KEY = '_local_last_update_seq';
23181var DOC_COUNT_KEY = '_local_doc_count';
23182var UUID_KEY = '_local_uuid';
23183
23184var MD5_PREFIX = 'md5-';
23185
23186var safeJsonEncoding = {
23187 encode: safeJsonStringify,
23188 decode: safeJsonParse,
23189 buffer: false,
23190 type: 'cheap-json'
23191};
23192
23193var levelChanges = new Changes();
23194
23195// winningRev and deleted are performance-killers, but
23196// in newer versions of PouchDB, they are cached on the metadata
23197function getWinningRev(metadata) {
23198 return 'winningRev' in metadata ?
23199 metadata.winningRev : winningRev(metadata);
23200}
23201
23202function getIsDeleted(metadata, winningRev$$1) {
23203 return 'deleted' in metadata ?
23204 metadata.deleted : isDeleted(metadata, winningRev$$1);
23205}
23206
23207function fetchAttachment(att, stores, opts) {
23208 var type = att.content_type;
23209 return new Promise(function (resolve, reject) {
23210 stores.binaryStore.get(att.digest, function (err, buffer) {
23211 var data;
23212 if (err) {
23213 /* istanbul ignore if */
23214 if (err.name !== 'NotFoundError') {
23215 return reject(err);
23216 } else {
23217 // empty
23218 if (!opts.binary) {
23219 data = '';
23220 } else {
23221 data = binStringToBluffer('', type);
23222 }
23223 }
23224 } else { // non-empty
23225 if (opts.binary) {
23226 data = readAsBlobOrBuffer(buffer, type);
23227 } else {
23228 data = buffer.toString('base64');
23229 }
23230 }
23231 delete att.stub;
23232 delete att.length;
23233 att.data = data;
23234 resolve();
23235 });
23236 });
23237}
23238
23239function fetchAttachments(results, stores, opts) {
23240 var atts = [];
23241 results.forEach(function (row) {
23242 if (!(row.doc && row.doc._attachments)) {
23243 return;
23244 }
23245 var attNames = Object.keys(row.doc._attachments);
23246 attNames.forEach(function (attName) {
23247 var att = row.doc._attachments[attName];
23248 if (!('data' in att)) {
23249 atts.push(att);
23250 }
23251 });
23252 });
23253
23254 return Promise.all(atts.map(function (att) {
23255 return fetchAttachment(att, stores, opts);
23256 }));
23257}
23258
23259function LevelPouch(opts, callback) {
23260 opts = clone(opts);
23261 var api = this;
23262 var instanceId;
23263 var stores = {};
23264 var revLimit = opts.revs_limit;
23265 var db;
23266 var name = opts.name;
23267 // TODO: this is undocumented and unused probably
23268 /* istanbul ignore else */
23269 if (typeof opts.createIfMissing === 'undefined') {
23270 opts.createIfMissing = true;
23271 }
23272
23273 var leveldown = opts.db;
23274
23275 var dbStore;
23276 var leveldownName = functionName(leveldown);
23277 if (dbStores.has(leveldownName)) {
23278 dbStore = dbStores.get(leveldownName);
23279 } else {
23280 dbStore = new ExportedMap();
23281 dbStores.set(leveldownName, dbStore);
23282 }
23283 if (dbStore.has(name)) {
23284 db = dbStore.get(name);
23285 afterDBCreated();
23286 } else {
23287 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
23288 /* istanbul ignore if */
23289 if (err) {
23290 dbStore["delete"](name);
23291 return callback(err);
23292 }
23293 db = dbStore.get(name);
23294 db._docCount = -1;
23295 db._queue = new Deque();
23296 /* istanbul ignore else */
23297 if (typeof opts.migrate === 'object') { // migration for leveldown
23298 opts.migrate.doMigrationOne(name, db, afterDBCreated);
23299 } else {
23300 afterDBCreated();
23301 }
23302 })));
23303 }
23304
23305 function afterDBCreated() {
23306 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
23307 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
23308 stores.attachmentStore =
23309 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
23310 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
23311 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
23312 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
23313 /* istanbul ignore else */
23314 if (typeof opts.migrate === 'object') { // migration for leveldown
23315 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
23316 } else {
23317 afterLastMigration();
23318 }
23319 }
23320
23321 function afterLastMigration() {
23322 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
23323 if (typeof db._updateSeq === 'undefined') {
23324 db._updateSeq = value || 0;
23325 }
23326 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
23327 db._docCount = !err ? value : 0;
23328 stores.metaStore.get(UUID_KEY, function (err, value) {
23329 instanceId = !err ? value : uuid$1();
23330 stores.metaStore.put(UUID_KEY, instanceId, function () {
23331 immediate(function () {
23332 callback(null, api);
23333 });
23334 });
23335 });
23336 });
23337 });
23338 }
23339
23340 function countDocs(callback) {
23341 /* istanbul ignore if */
23342 if (db.isClosed()) {
23343 return callback(new Error('database is closed'));
23344 }
23345 return callback(null, db._docCount); // use cached value
23346 }
23347
23348 api._remote = false;
23349 /* istanbul ignore next */
23350 api.type = function () {
23351 return 'leveldb';
23352 };
23353
23354 api._id = function (callback) {
23355 callback(null, instanceId);
23356 };
23357
23358 api._info = function (callback) {
23359 var res = {
23360 doc_count: db._docCount,
23361 update_seq: db._updateSeq,
23362 backend_adapter: functionName(leveldown)
23363 };
23364 return immediate(function () {
23365 callback(null, res);
23366 });
23367 };
23368
23369 function tryCode(fun, args) {
23370 try {
23371 fun.apply(null, args);
23372 } catch (err) {
23373 args[args.length - 1](err);
23374 }
23375 }
23376
23377 function executeNext() {
23378 var firstTask = db._queue.peekFront();
23379
23380 if (firstTask.type === 'read') {
23381 runReadOperation(firstTask);
23382 } else { // write, only do one at a time
23383 runWriteOperation(firstTask);
23384 }
23385 }
23386
23387 function runReadOperation(firstTask) {
23388 // do multiple reads at once simultaneously, because it's safe
23389
23390 var readTasks = [firstTask];
23391 var i = 1;
23392 var nextTask = db._queue.get(i);
23393 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
23394 readTasks.push(nextTask);
23395 i++;
23396 nextTask = db._queue.get(i);
23397 }
23398
23399 var numDone = 0;
23400
23401 readTasks.forEach(function (readTask) {
23402 var args = readTask.args;
23403 var callback = args[args.length - 1];
23404 args[args.length - 1] = function (...cbArgs) {
23405 callback.apply(null, cbArgs);
23406 if (++numDone === readTasks.length) {
23407 immediate(function () {
23408 // all read tasks have finished
23409 readTasks.forEach(function () {
23410 db._queue.shift();
23411 });
23412 if (db._queue.length) {
23413 executeNext();
23414 }
23415 });
23416 }
23417 };
23418 tryCode(readTask.fun, args);
23419 });
23420 }
23421
23422 function runWriteOperation(firstTask) {
23423 var args = firstTask.args;
23424 var callback = args[args.length - 1];
23425 args[args.length - 1] = function (...cbArgs) {
23426 callback.apply(null, cbArgs);
23427 immediate(function () {
23428 db._queue.shift();
23429 if (db._queue.length) {
23430 executeNext();
23431 }
23432 });
23433 };
23434 tryCode(firstTask.fun, args);
23435 }
23436
23437 // all read/write operations to the database are done in a queue,
23438 // similar to how websql/idb works. this avoids problems such
23439 // as e.g. compaction needing to have a lock on the database while
23440 // it updates stuff. in the future we can revisit this.
23441 function writeLock(fun) {
23442 return function (...args) {
23443 db._queue.push({
23444 fun: fun,
23445 args: args,
23446 type: 'write'
23447 });
23448
23449 if (db._queue.length === 1) {
23450 immediate(executeNext);
23451 }
23452 };
23453 }
23454
23455 // same as the writelock, but multiple can run at once
23456 function readLock(fun) {
23457 return function (...args) {
23458 db._queue.push({
23459 fun: fun,
23460 args: args,
23461 type: 'read'
23462 });
23463
23464 if (db._queue.length === 1) {
23465 immediate(executeNext);
23466 }
23467 };
23468 }
23469
23470 function formatSeq(n) {
23471 return ('0000000000000000' + n).slice(-16);
23472 }
23473
23474 function parseSeq(s) {
23475 return parseInt(s, 10);
23476 }
23477
23478 api._get = readLock(function (id, opts, callback) {
23479 opts = clone(opts);
23480
23481 stores.docStore.get(id, function (err, metadata) {
23482
23483 if (err || !metadata) {
23484 return callback(createError(MISSING_DOC, 'missing'));
23485 }
23486
23487 var rev;
23488 if (!opts.rev) {
23489 rev = getWinningRev(metadata);
23490 var deleted = getIsDeleted(metadata, rev);
23491 if (deleted) {
23492 return callback(createError(MISSING_DOC, "deleted"));
23493 }
23494 } else {
23495 rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;
23496 }
23497
23498 var seq = metadata.rev_map[rev];
23499
23500 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
23501 if (!doc) {
23502 return callback(createError(MISSING_DOC));
23503 }
23504 /* istanbul ignore if */
23505 if ('_id' in doc && doc._id !== metadata.id) {
23506 // this failing implies something very wrong
23507 return callback(new Error('wrong doc returned'));
23508 }
23509 doc._id = metadata.id;
23510 if ('_rev' in doc) {
23511 /* istanbul ignore if */
23512 if (doc._rev !== rev) {
23513 // this failing implies something very wrong
23514 return callback(new Error('wrong doc returned'));
23515 }
23516 } else {
23517 // we didn't always store this
23518 doc._rev = rev;
23519 }
23520 return callback(null, {doc: doc, metadata: metadata});
23521 });
23522 });
23523 });
23524
23525 // not technically part of the spec, but if putAttachment has its own
23526 // method...
23527 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
23528 var digest = attachment.digest;
23529 var type = attachment.content_type;
23530
23531 stores.binaryStore.get(digest, function (err, attach) {
23532 if (err) {
23533 /* istanbul ignore if */
23534 if (err.name !== 'NotFoundError') {
23535 return callback(err);
23536 }
23537 // Empty attachment
23538 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
23539 }
23540
23541 if (opts.binary) {
23542 callback(null, readAsBlobOrBuffer(attach, type));
23543 } else {
23544 callback(null, attach.toString('base64'));
23545 }
23546 });
23547 };
23548
23549 api._bulkDocs = writeLock(function (req, opts, callback) {
23550 var newEdits = opts.new_edits;
23551 var results = new Array(req.docs.length);
23552 var fetchedDocs = new ExportedMap();
23553 var stemmedRevs = new ExportedMap();
23554
23555 var txn = new LevelTransaction();
23556 var docCountDelta = 0;
23557 var newUpdateSeq = db._updateSeq;
23558
23559 // parse the docs and give each a sequence number
23560 var userDocs = req.docs;
23561 var docInfos = userDocs.map(function (doc) {
23562 if (doc._id && isLocalId(doc._id)) {
23563 return doc;
23564 }
23565 var newDoc = parseDoc(doc, newEdits, api.__opts);
23566
23567 if (newDoc.metadata && !newDoc.metadata.rev_map) {
23568 newDoc.metadata.rev_map = {};
23569 }
23570
23571 return newDoc;
23572 });
23573 var infoErrors = docInfos.filter(function (doc) {
23574 return doc.error;
23575 });
23576
23577 if (infoErrors.length) {
23578 return callback(infoErrors[0]);
23579 }
23580
23581 // verify any stub attachments as a precondition test
23582
23583 function verifyAttachment(digest, callback) {
23584 txn.get(stores.attachmentStore, digest, function (levelErr) {
23585 if (levelErr) {
23586 var err = createError(MISSING_STUB,
23587 'unknown stub attachment with digest ' +
23588 digest);
23589 callback(err);
23590 } else {
23591 callback();
23592 }
23593 });
23594 }
23595
23596 function verifyAttachments(finish) {
23597 var digests = [];
23598 userDocs.forEach(function (doc) {
23599 if (doc && doc._attachments) {
23600 Object.keys(doc._attachments).forEach(function (filename) {
23601 var att = doc._attachments[filename];
23602 if (att.stub) {
23603 digests.push(att.digest);
23604 }
23605 });
23606 }
23607 });
23608 if (!digests.length) {
23609 return finish();
23610 }
23611 var numDone = 0;
23612 var err;
23613
23614 digests.forEach(function (digest) {
23615 verifyAttachment(digest, function (attErr) {
23616 if (attErr && !err) {
23617 err = attErr;
23618 }
23619
23620 if (++numDone === digests.length) {
23621 finish(err);
23622 }
23623 });
23624 });
23625 }
23626
23627 function fetchExistingDocs(finish) {
23628 var numDone = 0;
23629 var overallErr;
23630 function checkDone() {
23631 if (++numDone === userDocs.length) {
23632 return finish(overallErr);
23633 }
23634 }
23635
23636 userDocs.forEach(function (doc) {
23637 if (doc._id && isLocalId(doc._id)) {
23638 // skip local docs
23639 return checkDone();
23640 }
23641 txn.get(stores.docStore, doc._id, function (err, info) {
23642 if (err) {
23643 /* istanbul ignore if */
23644 if (err.name !== 'NotFoundError') {
23645 overallErr = err;
23646 }
23647 } else {
23648 fetchedDocs.set(doc._id, info);
23649 }
23650 checkDone();
23651 });
23652 });
23653 }
23654
23655 function compact(revsMap, callback) {
23656 var promise = Promise.resolve();
23657 revsMap.forEach(function (revs, docId) {
23658 // TODO: parallelize, for now need to be sequential to
23659 // pass orphaned attachment tests
23660 promise = promise.then(function () {
23661 return new Promise(function (resolve, reject) {
23662 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
23663 /* istanbul ignore if */
23664 if (err) {
23665 return reject(err);
23666 }
23667 resolve();
23668 });
23669 });
23670 });
23671 });
23672
23673 promise.then(function () {
23674 callback();
23675 }, callback);
23676 }
23677
23678 function autoCompact(callback) {
23679 var revsMap = new ExportedMap();
23680 fetchedDocs.forEach(function (metadata, docId) {
23681 revsMap.set(docId, compactTree(metadata));
23682 });
23683 compact(revsMap, callback);
23684 }
23685
23686 function finish() {
23687 compact(stemmedRevs, function (error) {
23688 /* istanbul ignore if */
23689 if (error) {
23690 complete(error);
23691 }
23692 if (api.auto_compaction) {
23693 return autoCompact(complete);
23694 }
23695 complete();
23696 });
23697 }
23698
23699 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
23700 isUpdate, delta, resultsIdx, callback2) {
23701 docCountDelta += delta;
23702
23703 var err = null;
23704 var recv = 0;
23705
23706 docInfo.metadata.winningRev = winningRev$$1;
23707 docInfo.metadata.deleted = winningRevIsDeleted;
23708
23709 docInfo.data._id = docInfo.metadata.id;
23710 docInfo.data._rev = docInfo.metadata.rev;
23711
23712 if (newRevIsDeleted) {
23713 docInfo.data._deleted = true;
23714 }
23715
23716 if (docInfo.stemmedRevs.length) {
23717 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
23718 }
23719
23720 var attachments = docInfo.data._attachments ?
23721 Object.keys(docInfo.data._attachments) :
23722 [];
23723
23724 function attachmentSaved(attachmentErr) {
23725 recv++;
23726 if (!err) {
23727 /* istanbul ignore if */
23728 if (attachmentErr) {
23729 err = attachmentErr;
23730 callback2(err);
23731 } else if (recv === attachments.length) {
23732 finish();
23733 }
23734 }
23735 }
23736
23737 function onMD5Load(doc, key, data, attachmentSaved) {
23738 return function (result) {
23739 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
23740 };
23741 }
23742
23743 function doMD5(doc, key, attachmentSaved) {
23744 return function (data) {
23745 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
23746 };
23747 }
23748
23749 for (var i = 0; i < attachments.length; i++) {
23750 var key = attachments[i];
23751 var att = docInfo.data._attachments[key];
23752
23753 if (att.stub) {
23754 // still need to update the refs mapping
23755 var id = docInfo.data._id;
23756 var rev = docInfo.data._rev;
23757 saveAttachmentRefs(id, rev, att.digest, attachmentSaved);
23758 continue;
23759 }
23760 var data;
23761 if (typeof att.data === 'string') {
23762 // input is assumed to be a base64 string
23763 try {
23764 data = thisAtob(att.data);
23765 } catch (e) {
23766 callback(createError(BAD_ARG,
23767 'Attachment is not a valid base64 string'));
23768 return;
23769 }
23770 doMD5(docInfo, key, attachmentSaved)(data);
23771 } else {
23772 prepareAttachmentForStorage(att.data,
23773 doMD5(docInfo, key, attachmentSaved));
23774 }
23775 }
23776
23777 function finish() {
23778 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
23779 /* istanbul ignore if */
23780 if (seq) {
23781 // check that there aren't any existing revisions with the same
23782 // revision id, else we shouldn't do anything
23783 return callback2();
23784 }
23785 seq = ++newUpdateSeq;
23786 docInfo.metadata.rev_map[docInfo.metadata.rev] =
23787 docInfo.metadata.seq = seq;
23788 var seqKey = formatSeq(seq);
23789 var batch = [{
23790 key: seqKey,
23791 value: docInfo.data,
23792 prefix: stores.bySeqStore,
23793 type: 'put'
23794 }, {
23795 key: docInfo.metadata.id,
23796 value: docInfo.metadata,
23797 prefix: stores.docStore,
23798 type: 'put'
23799 }];
23800 txn.batch(batch);
23801 results[resultsIdx] = {
23802 ok: true,
23803 id: docInfo.metadata.id,
23804 rev: docInfo.metadata.rev
23805 };
23806 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
23807 callback2();
23808 }
23809
23810 if (!attachments.length) {
23811 finish();
23812 }
23813 }
23814
23815 // attachments are queued per-digest, otherwise the refs could be
23816 // overwritten by concurrent writes in the same bulkDocs session
23817 var attachmentQueues = {};
23818
23819 function saveAttachmentRefs(id, rev, digest, callback) {
23820
23821 function fetchAtt() {
23822 return new Promise(function (resolve, reject) {
23823 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
23824 /* istanbul ignore if */
23825 if (err && err.name !== 'NotFoundError') {
23826 return reject(err);
23827 }
23828 resolve(oldAtt);
23829 });
23830 });
23831 }
23832
23833 function saveAtt(oldAtt) {
23834 var ref = [id, rev].join('@');
23835 var newAtt = {};
23836
23837 if (oldAtt) {
23838 if (oldAtt.refs) {
23839 // only update references if this attachment already has them
23840 // since we cannot migrate old style attachments here without
23841 // doing a full db scan for references
23842 newAtt.refs = oldAtt.refs;
23843 newAtt.refs[ref] = true;
23844 }
23845 } else {
23846 newAtt.refs = {};
23847 newAtt.refs[ref] = true;
23848 }
23849
23850 return new Promise(function (resolve) {
23851 txn.batch([{
23852 type: 'put',
23853 prefix: stores.attachmentStore,
23854 key: digest,
23855 value: newAtt
23856 }]);
23857 resolve(!oldAtt);
23858 });
23859 }
23860
23861 // put attachments in a per-digest queue, to avoid two docs with the same
23862 // attachment overwriting each other
23863 var queue = attachmentQueues[digest] || Promise.resolve();
23864 attachmentQueues[digest] = queue.then(function () {
23865 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
23866 callback(null, isNewAttachment);
23867 }, callback);
23868 });
23869 }
23870
23871 function saveAttachment(docInfo, digest, key, data, callback) {
23872 var att = docInfo.data._attachments[key];
23873 delete att.data;
23874 att.digest = digest;
23875 att.length = data.length;
23876 var id = docInfo.metadata.id;
23877 var rev = docInfo.metadata.rev;
23878 att.revpos = parseInt(rev, 10);
23879
23880 saveAttachmentRefs(id, rev, digest, function (err, isNewAttachment) {
23881 /* istanbul ignore if */
23882 if (err) {
23883 return callback(err);
23884 }
23885 // do not try to store empty attachments
23886 if (data.length === 0) {
23887 return callback(err);
23888 }
23889 if (!isNewAttachment) {
23890 // small optimization - don't bother writing it again
23891 return callback(err);
23892 }
23893 txn.batch([{
23894 type: 'put',
23895 prefix: stores.binaryStore,
23896 key: digest,
23897 value: bufferFrom(data, 'binary')
23898 }]);
23899 callback();
23900 });
23901 }
23902
23903 function complete(err) {
23904 /* istanbul ignore if */
23905 if (err) {
23906 return immediate(function () {
23907 callback(err);
23908 });
23909 }
23910 txn.batch([
23911 {
23912 prefix: stores.metaStore,
23913 type: 'put',
23914 key: UPDATE_SEQ_KEY,
23915 value: newUpdateSeq
23916 },
23917 {
23918 prefix: stores.metaStore,
23919 type: 'put',
23920 key: DOC_COUNT_KEY,
23921 value: db._docCount + docCountDelta
23922 }
23923 ]);
23924 txn.execute(db, function (err) {
23925 /* istanbul ignore if */
23926 if (err) {
23927 return callback(err);
23928 }
23929 db._docCount += docCountDelta;
23930 db._updateSeq = newUpdateSeq;
23931 levelChanges.notify(name);
23932 immediate(function () {
23933 callback(null, results);
23934 });
23935 });
23936 }
23937
23938 if (!docInfos.length) {
23939 return callback(null, []);
23940 }
23941
23942 verifyAttachments(function (err) {
23943 if (err) {
23944 return callback(err);
23945 }
23946 fetchExistingDocs(function (err) {
23947 /* istanbul ignore if */
23948 if (err) {
23949 return callback(err);
23950 }
23951 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
23952 writeDoc, opts, finish);
23953 });
23954 });
23955 });
23956 api._allDocs = function (opts, callback) {
23957 if ('keys' in opts) {
23958 return allDocsKeysQuery(this, opts);
23959 }
23960 return readLock(function (opts, callback) {
23961 opts = clone(opts);
23962 countDocs(function (err, docCount) {
23963 /* istanbul ignore if */
23964 if (err) {
23965 return callback(err);
23966 }
23967 var readstreamOpts = {};
23968 var skip = opts.skip || 0;
23969 if (opts.startkey) {
23970 readstreamOpts.gte = opts.startkey;
23971 }
23972 if (opts.endkey) {
23973 readstreamOpts.lte = opts.endkey;
23974 }
23975 if (opts.key) {
23976 readstreamOpts.gte = readstreamOpts.lte = opts.key;
23977 }
23978 if (opts.descending) {
23979 readstreamOpts.reverse = true;
23980 // switch start and ends
23981 var tmp = readstreamOpts.lte;
23982 readstreamOpts.lte = readstreamOpts.gte;
23983 readstreamOpts.gte = tmp;
23984 }
23985 var limit;
23986 if (typeof opts.limit === 'number') {
23987 limit = opts.limit;
23988 }
23989 if (limit === 0 ||
23990 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
23991 readstreamOpts.gte > readstreamOpts.lte)) {
23992 // should return 0 results when start is greater than end.
23993 // normally level would "fix" this for us by reversing the order,
23994 // so short-circuit instead
23995 var returnVal = {
23996 total_rows: docCount,
23997 offset: opts.skip,
23998 rows: []
23999 };
24000 /* istanbul ignore if */
24001 if (opts.update_seq) {
24002 returnVal.update_seq = db._updateSeq;
24003 }
24004 return callback(null, returnVal);
24005 }
24006 var results = [];
24007 var docstream = stores.docStore.readStream(readstreamOpts);
24008
24009 var throughStream = through2.obj(function (entry, _, next) {
24010 var metadata = entry.value;
24011 // winningRev and deleted are performance-killers, but
24012 // in newer versions of PouchDB, they are cached on the metadata
24013 var winningRev$$1 = getWinningRev(metadata);
24014 var deleted = getIsDeleted(metadata, winningRev$$1);
24015 if (!deleted) {
24016 if (skip-- > 0) {
24017 next();
24018 return;
24019 } else if (typeof limit === 'number' && limit-- <= 0) {
24020 docstream.unpipe();
24021 docstream.destroy();
24022 next();
24023 return;
24024 }
24025 } else if (opts.deleted !== 'ok') {
24026 next();
24027 return;
24028 }
24029 function allDocsInner(data) {
24030 var doc = {
24031 id: metadata.id,
24032 key: metadata.id,
24033 value: {
24034 rev: winningRev$$1
24035 }
24036 };
24037 if (opts.include_docs) {
24038 doc.doc = data;
24039 doc.doc._rev = doc.value.rev;
24040 if (opts.conflicts) {
24041 var conflicts = collectConflicts(metadata);
24042 if (conflicts.length) {
24043 doc.doc._conflicts = conflicts;
24044 }
24045 }
24046 for (var att in doc.doc._attachments) {
24047 if (Object.prototype.hasOwnProperty.call(doc.doc._attachments, att)) {
24048 doc.doc._attachments[att].stub = true;
24049 }
24050 }
24051 }
24052 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
24053 return next();
24054 } else if (deleted) {
24055 if (opts.deleted === 'ok') {
24056 doc.value.deleted = true;
24057 doc.doc = null;
24058 } else {
24059 /* istanbul ignore next */
24060 return next();
24061 }
24062 }
24063 results.push(doc);
24064 next();
24065 }
24066 if (opts.include_docs) {
24067 var seq = metadata.rev_map[winningRev$$1];
24068 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
24069 allDocsInner(data);
24070 });
24071 }
24072 else {
24073 allDocsInner();
24074 }
24075 }, function (next) {
24076 Promise.resolve().then(function () {
24077 if (opts.include_docs && opts.attachments) {
24078 return fetchAttachments(results, stores, opts);
24079 }
24080 }).then(function () {
24081 var returnVal = {
24082 total_rows: docCount,
24083 offset: opts.skip,
24084 rows: results
24085 };
24086
24087 /* istanbul ignore if */
24088 if (opts.update_seq) {
24089 returnVal.update_seq = db._updateSeq;
24090 }
24091 callback(null, returnVal);
24092 }, callback);
24093 next();
24094 }).on('unpipe', function () {
24095 throughStream.end();
24096 });
24097
24098 docstream.on('error', callback);
24099
24100 docstream.pipe(throughStream);
24101 });
24102 })(opts, callback);
24103 };
24104
24105 api._changes = function (opts) {
24106 opts = clone(opts);
24107
24108 if (opts.continuous) {
24109 var id = name + ':' + uuid$1();
24110 levelChanges.addListener(name, id, api, opts);
24111 levelChanges.notify(name);
24112 return {
24113 cancel: function () {
24114 levelChanges.removeListener(name, id);
24115 }
24116 };
24117 }
24118
24119 var descending = opts.descending;
24120 var results = [];
24121 var lastSeq = opts.since || 0;
24122 var called = 0;
24123 var streamOpts = {
24124 reverse: descending
24125 };
24126 var limit;
24127 if ('limit' in opts && opts.limit > 0) {
24128 limit = opts.limit;
24129 }
24130 if (!streamOpts.reverse) {
24131 streamOpts.start = formatSeq(opts.since || 0);
24132 }
24133
24134 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
24135 var filter = filterChange(opts);
24136 var docIdsToMetadata = new ExportedMap();
24137
24138 function complete() {
24139 opts.done = true;
24140 if (opts.return_docs && opts.limit) {
24141 /* istanbul ignore if */
24142 if (opts.limit < results.length) {
24143 results.length = opts.limit;
24144 }
24145 }
24146 changeStream.unpipe(throughStream);
24147 changeStream.destroy();
24148 if (!opts.continuous && !opts.cancelled) {
24149 if (opts.include_docs && opts.attachments && opts.return_docs) {
24150 fetchAttachments(results, stores, opts).then(function () {
24151 opts.complete(null, {results: results, last_seq: lastSeq});
24152 });
24153 } else {
24154 opts.complete(null, {results: results, last_seq: lastSeq});
24155 }
24156 }
24157 }
24158 var changeStream = stores.bySeqStore.readStream(streamOpts);
24159 var throughStream = through2.obj(function (data, _, next) {
24160 if (limit && called >= limit) {
24161 complete();
24162 return next();
24163 }
24164 if (opts.cancelled || opts.done) {
24165 return next();
24166 }
24167
24168 var seq = parseSeq(data.key);
24169 var doc = data.value;
24170
24171 if (seq === opts.since && !descending) {
24172 // couchdb ignores `since` if descending=true
24173 return next();
24174 }
24175
24176 if (docIds && !docIds.has(doc._id)) {
24177 return next();
24178 }
24179
24180 var metadata;
24181
24182 function onGetMetadata(metadata) {
24183 var winningRev$$1 = getWinningRev(metadata);
24184
24185 function onGetWinningDoc(winningDoc) {
24186
24187 var change = opts.processChange(winningDoc, metadata, opts);
24188 change.seq = metadata.seq;
24189
24190 var filtered = filter(change);
24191 if (typeof filtered === 'object') {
24192 return opts.complete(filtered);
24193 }
24194
24195 if (filtered) {
24196 called++;
24197
24198 if (opts.attachments && opts.include_docs) {
24199 // fetch attachment immediately for the benefit
24200 // of live listeners
24201 fetchAttachments([change], stores, opts).then(function () {
24202 opts.onChange(change);
24203 });
24204 } else {
24205 opts.onChange(change);
24206 }
24207
24208 if (opts.return_docs) {
24209 results.push(change);
24210 }
24211 }
24212 next();
24213 }
24214
24215 if (metadata.seq !== seq) {
24216 // some other seq is later
24217 return next();
24218 }
24219
24220 lastSeq = seq;
24221
24222 if (winningRev$$1 === doc._rev) {
24223 return onGetWinningDoc(doc);
24224 }
24225
24226 // fetch the winner
24227
24228 var winningSeq = metadata.rev_map[winningRev$$1];
24229
24230 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
24231 onGetWinningDoc(doc);
24232 });
24233 }
24234
24235 metadata = docIdsToMetadata.get(doc._id);
24236 if (metadata) { // cached
24237 return onGetMetadata(metadata);
24238 }
24239 // metadata not cached, have to go fetch it
24240 stores.docStore.get(doc._id, function (err, metadata) {
24241 /* istanbul ignore if */
24242 if (opts.cancelled || opts.done || db.isClosed() ||
24243 isLocalId(metadata.id)) {
24244 return next();
24245 }
24246 docIdsToMetadata.set(doc._id, metadata);
24247 onGetMetadata(metadata);
24248 });
24249 }, function (next) {
24250 if (opts.cancelled) {
24251 return next();
24252 }
24253 if (opts.return_docs && opts.limit) {
24254 /* istanbul ignore if */
24255 if (opts.limit < results.length) {
24256 results.length = opts.limit;
24257 }
24258 }
24259
24260 next();
24261 }).on('unpipe', function () {
24262 throughStream.end();
24263 complete();
24264 });
24265 changeStream.pipe(throughStream);
24266 return {
24267 cancel: function () {
24268 opts.cancelled = true;
24269 complete();
24270 }
24271 };
24272 };
24273
24274 api._close = function (callback) {
24275 /* istanbul ignore if */
24276 if (db.isClosed()) {
24277 return callback(createError(NOT_OPEN));
24278 }
24279 db.close(function (err) {
24280 /* istanbul ignore if */
24281 if (err) {
24282 callback(err);
24283 } else {
24284 dbStore["delete"](name);
24285
24286 var adapterName = functionName(leveldown);
24287 var adapterStore = dbStores.get(adapterName);
24288 var viewNamePrefix = PouchDB$1.prefix + name + "-mrview-";
24289 var keys = [...adapterStore.keys()].filter(k => k.includes(viewNamePrefix));
24290 keys.forEach(key => {
24291 var eventEmitter = adapterStore.get(key);
24292 eventEmitter.removeAllListeners();
24293 eventEmitter.close();
24294 adapterStore["delete"](key);
24295 });
24296
24297 callback();
24298 }
24299 });
24300 };
24301
24302 api._getRevisionTree = function (docId, callback) {
24303 stores.docStore.get(docId, function (err, metadata) {
24304 if (err) {
24305 callback(createError(MISSING_DOC));
24306 } else {
24307 callback(null, metadata.rev_tree);
24308 }
24309 });
24310 };
24311
24312 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
24313 api._doCompactionNoLock(docId, revs, opts, callback);
24314 });
24315
24316 // the NoLock version is for use by bulkDocs
24317 api._doCompactionNoLock = function (docId, revs, opts, callback) {
24318 if (typeof opts === 'function') {
24319 callback = opts;
24320 opts = {};
24321 }
24322
24323 if (!revs.length) {
24324 return callback();
24325 }
24326 var txn = opts.ctx || new LevelTransaction();
24327
24328 txn.get(stores.docStore, docId, function (err, metadata) {
24329 /* istanbul ignore if */
24330 if (err) {
24331 return callback(err);
24332 }
24333 var seqs = revs.map(function (rev) {
24334 var seq = metadata.rev_map[rev];
24335 delete metadata.rev_map[rev];
24336 return seq;
24337 });
24338 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
24339 revHash, ctx, opts) {
24340 var rev = pos + '-' + revHash;
24341 if (revs.indexOf(rev) !== -1) {
24342 opts.status = 'missing';
24343 }
24344 });
24345
24346 var batch = [];
24347 batch.push({
24348 key: metadata.id,
24349 value: metadata,
24350 type: 'put',
24351 prefix: stores.docStore
24352 });
24353
24354 var digestMap = {};
24355 var numDone = 0;
24356 var overallErr;
24357 function checkDone(err) {
24358 /* istanbul ignore if */
24359 if (err) {
24360 overallErr = err;
24361 }
24362 if (++numDone === revs.length) { // done
24363 /* istanbul ignore if */
24364 if (overallErr) {
24365 return callback(overallErr);
24366 }
24367 deleteOrphanedAttachments();
24368 }
24369 }
24370
24371 function finish(err) {
24372 /* istanbul ignore if */
24373 if (err) {
24374 return callback(err);
24375 }
24376 txn.batch(batch);
24377 if (opts.ctx) {
24378 // don't execute immediately
24379 return callback();
24380 }
24381 txn.execute(db, callback);
24382 }
24383
24384 function deleteOrphanedAttachments() {
24385 var possiblyOrphanedAttachments = Object.keys(digestMap);
24386 if (!possiblyOrphanedAttachments.length) {
24387 return finish();
24388 }
24389 var numDone = 0;
24390 var overallErr;
24391 function checkDone(err) {
24392 /* istanbul ignore if */
24393 if (err) {
24394 overallErr = err;
24395 }
24396 if (++numDone === possiblyOrphanedAttachments.length) {
24397 finish(overallErr);
24398 }
24399 }
24400 var refsToDelete = new ExportedMap();
24401 revs.forEach(function (rev) {
24402 refsToDelete.set(docId + '@' + rev, true);
24403 });
24404 possiblyOrphanedAttachments.forEach(function (digest) {
24405 txn.get(stores.attachmentStore, digest, function (err, attData) {
24406 /* istanbul ignore if */
24407 if (err) {
24408 if (err.name === 'NotFoundError') {
24409 return checkDone();
24410 } else {
24411 return checkDone(err);
24412 }
24413 }
24414 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
24415 return !refsToDelete.has(ref);
24416 });
24417 var newRefs = {};
24418 refs.forEach(function (ref) {
24419 newRefs[ref] = true;
24420 });
24421 if (refs.length) { // not orphaned
24422 batch.push({
24423 key: digest,
24424 type: 'put',
24425 value: {refs: newRefs},
24426 prefix: stores.attachmentStore
24427 });
24428 } else { // orphaned, can safely delete
24429 batch = batch.concat([{
24430 key: digest,
24431 type: 'del',
24432 prefix: stores.attachmentStore
24433 }, {
24434 key: digest,
24435 type: 'del',
24436 prefix: stores.binaryStore
24437 }]);
24438 }
24439 checkDone();
24440 });
24441 });
24442 }
24443
24444 seqs.forEach(function (seq) {
24445 batch.push({
24446 key: formatSeq(seq),
24447 type: 'del',
24448 prefix: stores.bySeqStore
24449 });
24450 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
24451 /* istanbul ignore if */
24452 if (err) {
24453 if (err.name === 'NotFoundError') {
24454 return checkDone();
24455 } else {
24456 return checkDone(err);
24457 }
24458 }
24459 var atts = Object.keys(doc._attachments || {});
24460 atts.forEach(function (attName) {
24461 var digest = doc._attachments[attName].digest;
24462 digestMap[digest] = true;
24463 });
24464 checkDone();
24465 });
24466 });
24467 });
24468 };
24469
24470 api._getLocal = function (id, callback) {
24471 stores.localStore.get(id, function (err, doc) {
24472 if (err) {
24473 callback(createError(MISSING_DOC));
24474 } else {
24475 callback(null, doc);
24476 }
24477 });
24478 };
24479
24480 api._putLocal = function (doc, opts, callback) {
24481 if (typeof opts === 'function') {
24482 callback = opts;
24483 opts = {};
24484 }
24485 if (opts.ctx) {
24486 api._putLocalNoLock(doc, opts, callback);
24487 } else {
24488 api._putLocalWithLock(doc, opts, callback);
24489 }
24490 };
24491
24492 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
24493 api._putLocalNoLock(doc, opts, callback);
24494 });
24495
24496 // the NoLock version is for use by bulkDocs
24497 api._putLocalNoLock = function (doc, opts, callback) {
24498 delete doc._revisions; // ignore this, trust the rev
24499 var oldRev = doc._rev;
24500 var id = doc._id;
24501
24502 var txn = opts.ctx || new LevelTransaction();
24503
24504 txn.get(stores.localStore, id, function (err, resp) {
24505 if (err && oldRev) {
24506 return callback(createError(REV_CONFLICT));
24507 }
24508 if (resp && resp._rev !== oldRev) {
24509 return callback(createError(REV_CONFLICT));
24510 }
24511 doc._rev =
24512 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
24513 var batch = [
24514 {
24515 type: 'put',
24516 prefix: stores.localStore,
24517 key: id,
24518 value: doc
24519 }
24520 ];
24521
24522 txn.batch(batch);
24523 var ret = {ok: true, id: doc._id, rev: doc._rev};
24524
24525 if (opts.ctx) {
24526 // don't execute immediately
24527 return callback(null, ret);
24528 }
24529 txn.execute(db, function (err) {
24530 /* istanbul ignore if */
24531 if (err) {
24532 return callback(err);
24533 }
24534 callback(null, ret);
24535 });
24536 });
24537 };
24538
24539 api._removeLocal = function (doc, opts, callback) {
24540 if (typeof opts === 'function') {
24541 callback = opts;
24542 opts = {};
24543 }
24544 if (opts.ctx) {
24545 api._removeLocalNoLock(doc, opts, callback);
24546 } else {
24547 api._removeLocalWithLock(doc, opts, callback);
24548 }
24549 };
24550
24551 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
24552 api._removeLocalNoLock(doc, opts, callback);
24553 });
24554
24555 // the NoLock version is for use by bulkDocs
24556 api._removeLocalNoLock = function (doc, opts, callback) {
24557 var txn = opts.ctx || new LevelTransaction();
24558 txn.get(stores.localStore, doc._id, function (err, resp) {
24559 if (err) {
24560 /* istanbul ignore if */
24561 if (err.name !== 'NotFoundError') {
24562 return callback(err);
24563 } else {
24564 return callback(createError(MISSING_DOC));
24565 }
24566 }
24567 if (resp._rev !== doc._rev) {
24568 return callback(createError(REV_CONFLICT));
24569 }
24570 txn.batch([{
24571 prefix: stores.localStore,
24572 type: 'del',
24573 key: doc._id
24574 }]);
24575 var ret = {ok: true, id: doc._id, rev: '0-0'};
24576 if (opts.ctx) {
24577 // don't execute immediately
24578 return callback(null, ret);
24579 }
24580 txn.execute(db, function (err) {
24581 /* istanbul ignore if */
24582 if (err) {
24583 return callback(err);
24584 }
24585 callback(null, ret);
24586 });
24587 });
24588 };
24589
24590 // close and delete open leveldb stores
24591 api._destroy = function (opts, callback) {
24592 var dbStore;
24593 var leveldownName = functionName(leveldown);
24594 /* istanbul ignore else */
24595 if (dbStores.has(leveldownName)) {
24596 dbStore = dbStores.get(leveldownName);
24597 } else {
24598 return callDestroy(name, callback);
24599 }
24600
24601 /* istanbul ignore else */
24602 if (dbStore.has(name)) {
24603 levelChanges.removeAllListeners(name);
24604
24605 dbStore.get(name).close(function () {
24606 dbStore["delete"](name);
24607 callDestroy(name, callback);
24608 });
24609 } else {
24610 callDestroy(name, callback);
24611 }
24612 };
24613 function callDestroy(name, cb) {
24614 // May not exist if leveldown is backed by memory adapter
24615 /* istanbul ignore else */
24616 if ('destroy' in leveldown) {
24617 leveldown.destroy(name, cb);
24618 } else {
24619 cb(null);
24620 }
24621 }
24622}
24623
24624function LocalStoragePouch(opts, callback) {
24625 var _opts = $inject_Object_assign({
24626 db: localstoragedown
24627 }, opts);
24628
24629 LevelPouch.call(this, _opts, callback);
24630}
24631
24632// overrides for normal LevelDB behavior on Node
24633LocalStoragePouch.valid = function () {
24634 return typeof localStorage !== 'undefined';
24635};
24636LocalStoragePouch.use_prefix = true;
24637
24638function LocalStoragePouchPlugin (PouchDB) {
24639 PouchDB.adapter('localstorage', LocalStoragePouch, true);
24640}
24641
24642// this code only runs in the browser, as its own dist/ script
24643
24644if (typeof PouchDB === 'undefined') {
24645 guardedConsole('error', 'localstorage adapter plugin error: ' +
24646 'Cannot find global "PouchDB" object! ' +
24647 'Did you remember to include pouchdb.js?');
24648} else {
24649 PouchDB.plugin(LocalStoragePouchPlugin);
24650}
24651
24652},{"118":118,"12":12,"125":125,"140":140,"23":23,"26":26,"31":31,"39":39,"61":61,"63":63,"70":70,"82":82,"84":84}]},{},[143]);
24653
\No newline at end of file