UNPKG

624 kBJavaScriptView Raw
1// PouchDB in-memory plugin 7.3.1
2// Based on MemDOWN: https://github.com/rvagg/memdown
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'use strict';
10
11module.exports = argsArray;
12
13function argsArray(fun) {
14 return function () {
15 var len = arguments.length;
16 if (len) {
17 var args = [];
18 var i = -1;
19 while (++i < len) {
20 args[i] = arguments[i];
21 }
22 return fun.call(this, args);
23 } else {
24 return fun.call(this, []);
25 }
26 };
27}
28},{}],2:[function(_dereq_,module,exports){
29(function (global){(function (){
30'use strict';
31
32var objectAssign = _dereq_(65);
33
34// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
35// original notice:
36
37/*!
38 * The buffer module from node.js, for the browser.
39 *
40 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
41 * @license MIT
42 */
43function compare(a, b) {
44 if (a === b) {
45 return 0;
46 }
47
48 var x = a.length;
49 var y = b.length;
50
51 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
52 if (a[i] !== b[i]) {
53 x = a[i];
54 y = b[i];
55 break;
56 }
57 }
58
59 if (x < y) {
60 return -1;
61 }
62 if (y < x) {
63 return 1;
64 }
65 return 0;
66}
67function isBuffer(b) {
68 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
69 return global.Buffer.isBuffer(b);
70 }
71 return !!(b != null && b._isBuffer);
72}
73
74// based on node assert, original notice:
75// NB: The URL to the CommonJS spec is kept just for tradition.
76// node-assert has evolved a lot since then, both in API and behavior.
77
78// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
79//
80// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
81//
82// Originally from narwhal.js (http://narwhaljs.org)
83// Copyright (c) 2009 Thomas Robinson <280north.com>
84//
85// Permission is hereby granted, free of charge, to any person obtaining a copy
86// of this software and associated documentation files (the 'Software'), to
87// deal in the Software without restriction, including without limitation the
88// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
89// sell copies of the Software, and to permit persons to whom the Software is
90// furnished to do so, subject to the following conditions:
91//
92// The above copyright notice and this permission notice shall be included in
93// all copies or substantial portions of the Software.
94//
95// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
96// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
97// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
98// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
99// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
100// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
101
102var util = _dereq_(5);
103var hasOwn = Object.prototype.hasOwnProperty;
104var pSlice = Array.prototype.slice;
105var functionsHaveNames = (function () {
106 return function foo() {}.name === 'foo';
107}());
108function pToString (obj) {
109 return Object.prototype.toString.call(obj);
110}
111function isView(arrbuf) {
112 if (isBuffer(arrbuf)) {
113 return false;
114 }
115 if (typeof global.ArrayBuffer !== 'function') {
116 return false;
117 }
118 if (typeof ArrayBuffer.isView === 'function') {
119 return ArrayBuffer.isView(arrbuf);
120 }
121 if (!arrbuf) {
122 return false;
123 }
124 if (arrbuf instanceof DataView) {
125 return true;
126 }
127 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
128 return true;
129 }
130 return false;
131}
132// 1. The assert module provides functions that throw
133// AssertionError's when particular conditions are not met. The
134// assert module must conform to the following interface.
135
136var assert = module.exports = ok;
137
138// 2. The AssertionError is defined in assert.
139// new assert.AssertionError({ message: message,
140// actual: actual,
141// expected: expected })
142
143var regex = /\s*function\s+([^\(\s]*)\s*/;
144// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
145function getName(func) {
146 if (!util.isFunction(func)) {
147 return;
148 }
149 if (functionsHaveNames) {
150 return func.name;
151 }
152 var str = func.toString();
153 var match = str.match(regex);
154 return match && match[1];
155}
156assert.AssertionError = function AssertionError(options) {
157 this.name = 'AssertionError';
158 this.actual = options.actual;
159 this.expected = options.expected;
160 this.operator = options.operator;
161 if (options.message) {
162 this.message = options.message;
163 this.generatedMessage = false;
164 } else {
165 this.message = getMessage(this);
166 this.generatedMessage = true;
167 }
168 var stackStartFunction = options.stackStartFunction || fail;
169 if (Error.captureStackTrace) {
170 Error.captureStackTrace(this, stackStartFunction);
171 } else {
172 // non v8 browsers so we can have a stacktrace
173 var err = new Error();
174 if (err.stack) {
175 var out = err.stack;
176
177 // try to strip useless frames
178 var fn_name = getName(stackStartFunction);
179 var idx = out.indexOf('\n' + fn_name);
180 if (idx >= 0) {
181 // once we have located the function frame
182 // we need to strip out everything before it (and its line)
183 var next_line = out.indexOf('\n', idx + 1);
184 out = out.substring(next_line + 1);
185 }
186
187 this.stack = out;
188 }
189 }
190};
191
192// assert.AssertionError instanceof Error
193util.inherits(assert.AssertionError, Error);
194
195function truncate(s, n) {
196 if (typeof s === 'string') {
197 return s.length < n ? s : s.slice(0, n);
198 } else {
199 return s;
200 }
201}
202function inspect(something) {
203 if (functionsHaveNames || !util.isFunction(something)) {
204 return util.inspect(something);
205 }
206 var rawname = getName(something);
207 var name = rawname ? ': ' + rawname : '';
208 return '[Function' + name + ']';
209}
210function getMessage(self) {
211 return truncate(inspect(self.actual), 128) + ' ' +
212 self.operator + ' ' +
213 truncate(inspect(self.expected), 128);
214}
215
216// At present only the three keys mentioned above are used and
217// understood by the spec. Implementations or sub modules can pass
218// other keys to the AssertionError's constructor - they will be
219// ignored.
220
221// 3. All of the following functions must throw an AssertionError
222// when a corresponding condition is not met, with a message that
223// may be undefined if not provided. All assertion methods provide
224// both the actual and expected values to the assertion error for
225// display purposes.
226
227function fail(actual, expected, message, operator, stackStartFunction) {
228 throw new assert.AssertionError({
229 message: message,
230 actual: actual,
231 expected: expected,
232 operator: operator,
233 stackStartFunction: stackStartFunction
234 });
235}
236
237// EXTENSION! allows for well behaved errors defined elsewhere.
238assert.fail = fail;
239
240// 4. Pure assertion tests whether a value is truthy, as determined
241// by !!guard.
242// assert.ok(guard, message_opt);
243// This statement is equivalent to assert.equal(true, !!guard,
244// message_opt);. To test strictly for the value true, use
245// assert.strictEqual(true, guard, message_opt);.
246
247function ok(value, message) {
248 if (!value) fail(value, true, message, '==', assert.ok);
249}
250assert.ok = ok;
251
252// 5. The equality assertion tests shallow, coercive equality with
253// ==.
254// assert.equal(actual, expected, message_opt);
255
256assert.equal = function equal(actual, expected, message) {
257 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
258};
259
260// 6. The non-equality assertion tests for whether two objects are not equal
261// with != assert.notEqual(actual, expected, message_opt);
262
263assert.notEqual = function notEqual(actual, expected, message) {
264 if (actual == expected) {
265 fail(actual, expected, message, '!=', assert.notEqual);
266 }
267};
268
269// 7. The equivalence assertion tests a deep equality relation.
270// assert.deepEqual(actual, expected, message_opt);
271
272assert.deepEqual = function deepEqual(actual, expected, message) {
273 if (!_deepEqual(actual, expected, false)) {
274 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
275 }
276};
277
278assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
279 if (!_deepEqual(actual, expected, true)) {
280 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
281 }
282};
283
284function _deepEqual(actual, expected, strict, memos) {
285 // 7.1. All identical values are equivalent, as determined by ===.
286 if (actual === expected) {
287 return true;
288 } else if (isBuffer(actual) && isBuffer(expected)) {
289 return compare(actual, expected) === 0;
290
291 // 7.2. If the expected value is a Date object, the actual value is
292 // equivalent if it is also a Date object that refers to the same time.
293 } else if (util.isDate(actual) && util.isDate(expected)) {
294 return actual.getTime() === expected.getTime();
295
296 // 7.3 If the expected value is a RegExp object, the actual value is
297 // equivalent if it is also a RegExp object with the same source and
298 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
299 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
300 return actual.source === expected.source &&
301 actual.global === expected.global &&
302 actual.multiline === expected.multiline &&
303 actual.lastIndex === expected.lastIndex &&
304 actual.ignoreCase === expected.ignoreCase;
305
306 // 7.4. Other pairs that do not both pass typeof value == 'object',
307 // equivalence is determined by ==.
308 } else if ((actual === null || typeof actual !== 'object') &&
309 (expected === null || typeof expected !== 'object')) {
310 return strict ? actual === expected : actual == expected;
311
312 // If both values are instances of typed arrays, wrap their underlying
313 // ArrayBuffers in a Buffer each to increase performance
314 // This optimization requires the arrays to have the same type as checked by
315 // Object.prototype.toString (aka pToString). Never perform binary
316 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
317 // bit patterns are not identical.
318 } else if (isView(actual) && isView(expected) &&
319 pToString(actual) === pToString(expected) &&
320 !(actual instanceof Float32Array ||
321 actual instanceof Float64Array)) {
322 return compare(new Uint8Array(actual.buffer),
323 new Uint8Array(expected.buffer)) === 0;
324
325 // 7.5 For all other Object pairs, including Array objects, equivalence is
326 // determined by having the same number of owned properties (as verified
327 // with Object.prototype.hasOwnProperty.call), the same set of keys
328 // (although not necessarily the same order), equivalent values for every
329 // corresponding key, and an identical 'prototype' property. Note: this
330 // accounts for both named and indexed properties on Arrays.
331 } else if (isBuffer(actual) !== isBuffer(expected)) {
332 return false;
333 } else {
334 memos = memos || {actual: [], expected: []};
335
336 var actualIndex = memos.actual.indexOf(actual);
337 if (actualIndex !== -1) {
338 if (actualIndex === memos.expected.indexOf(expected)) {
339 return true;
340 }
341 }
342
343 memos.actual.push(actual);
344 memos.expected.push(expected);
345
346 return objEquiv(actual, expected, strict, memos);
347 }
348}
349
350function isArguments(object) {
351 return Object.prototype.toString.call(object) == '[object Arguments]';
352}
353
354function objEquiv(a, b, strict, actualVisitedObjects) {
355 if (a === null || a === undefined || b === null || b === undefined)
356 return false;
357 // if one is a primitive, the other must be same
358 if (util.isPrimitive(a) || util.isPrimitive(b))
359 return a === b;
360 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
361 return false;
362 var aIsArgs = isArguments(a);
363 var bIsArgs = isArguments(b);
364 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
365 return false;
366 if (aIsArgs) {
367 a = pSlice.call(a);
368 b = pSlice.call(b);
369 return _deepEqual(a, b, strict);
370 }
371 var ka = objectKeys(a);
372 var kb = objectKeys(b);
373 var key, i;
374 // having the same number of owned properties (keys incorporates
375 // hasOwnProperty)
376 if (ka.length !== kb.length)
377 return false;
378 //the same set of keys (although not necessarily the same order),
379 ka.sort();
380 kb.sort();
381 //~~~cheap key test
382 for (i = ka.length - 1; i >= 0; i--) {
383 if (ka[i] !== kb[i])
384 return false;
385 }
386 //equivalent values for every corresponding key, and
387 //~~~possibly expensive deep test
388 for (i = ka.length - 1; i >= 0; i--) {
389 key = ka[i];
390 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
391 return false;
392 }
393 return true;
394}
395
396// 8. The non-equivalence assertion tests for any deep inequality.
397// assert.notDeepEqual(actual, expected, message_opt);
398
399assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
400 if (_deepEqual(actual, expected, false)) {
401 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
402 }
403};
404
405assert.notDeepStrictEqual = notDeepStrictEqual;
406function notDeepStrictEqual(actual, expected, message) {
407 if (_deepEqual(actual, expected, true)) {
408 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
409 }
410}
411
412
413// 9. The strict equality assertion tests strict equality, as determined by ===.
414// assert.strictEqual(actual, expected, message_opt);
415
416assert.strictEqual = function strictEqual(actual, expected, message) {
417 if (actual !== expected) {
418 fail(actual, expected, message, '===', assert.strictEqual);
419 }
420};
421
422// 10. The strict non-equality assertion tests for strict inequality, as
423// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
424
425assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
426 if (actual === expected) {
427 fail(actual, expected, message, '!==', assert.notStrictEqual);
428 }
429};
430
431function expectedException(actual, expected) {
432 if (!actual || !expected) {
433 return false;
434 }
435
436 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
437 return expected.test(actual);
438 }
439
440 try {
441 if (actual instanceof expected) {
442 return true;
443 }
444 } catch (e) {
445 // Ignore. The instanceof check doesn't work for arrow functions.
446 }
447
448 if (Error.isPrototypeOf(expected)) {
449 return false;
450 }
451
452 return expected.call({}, actual) === true;
453}
454
455function _tryBlock(block) {
456 var error;
457 try {
458 block();
459 } catch (e) {
460 error = e;
461 }
462 return error;
463}
464
465function _throws(shouldThrow, block, expected, message) {
466 var actual;
467
468 if (typeof block !== 'function') {
469 throw new TypeError('"block" argument must be a function');
470 }
471
472 if (typeof expected === 'string') {
473 message = expected;
474 expected = null;
475 }
476
477 actual = _tryBlock(block);
478
479 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
480 (message ? ' ' + message : '.');
481
482 if (shouldThrow && !actual) {
483 fail(actual, expected, 'Missing expected exception' + message);
484 }
485
486 var userProvidedMessage = typeof message === 'string';
487 var isUnwantedException = !shouldThrow && util.isError(actual);
488 var isUnexpectedException = !shouldThrow && actual && !expected;
489
490 if ((isUnwantedException &&
491 userProvidedMessage &&
492 expectedException(actual, expected)) ||
493 isUnexpectedException) {
494 fail(actual, expected, 'Got unwanted exception' + message);
495 }
496
497 if ((shouldThrow && actual && expected &&
498 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
499 throw actual;
500 }
501}
502
503// 11. Expected to throw an error:
504// assert.throws(block, Error_opt, message_opt);
505
506assert.throws = function(block, /*optional*/error, /*optional*/message) {
507 _throws(true, block, error, message);
508};
509
510// EXTENSION! This is annoying to write outside this module.
511assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
512 _throws(false, block, error, message);
513};
514
515assert.ifError = function(err) { if (err) throw err; };
516
517// Expose a strict only variant of assert
518function strict(value, message) {
519 if (!value) fail(value, true, message, '==', strict);
520}
521assert.strict = objectAssign(strict, assert, {
522 equal: assert.strictEqual,
523 deepEqual: assert.deepStrictEqual,
524 notEqual: assert.notStrictEqual,
525 notDeepEqual: assert.notDeepStrictEqual
526});
527assert.strict.strict = assert.strict;
528
529var objectKeys = Object.keys || function (obj) {
530 var keys = [];
531 for (var key in obj) {
532 if (hasOwn.call(obj, key)) keys.push(key);
533 }
534 return keys;
535};
536
537}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
538},{"5":5,"65":65}],3:[function(_dereq_,module,exports){
539if (typeof Object.create === 'function') {
540 // implementation from standard node.js 'util' module
541 module.exports = function inherits(ctor, superCtor) {
542 ctor.super_ = superCtor
543 ctor.prototype = Object.create(superCtor.prototype, {
544 constructor: {
545 value: ctor,
546 enumerable: false,
547 writable: true,
548 configurable: true
549 }
550 });
551 };
552} else {
553 // old school shim for old browsers
554 module.exports = function inherits(ctor, superCtor) {
555 ctor.super_ = superCtor
556 var TempCtor = function () {}
557 TempCtor.prototype = superCtor.prototype
558 ctor.prototype = new TempCtor()
559 ctor.prototype.constructor = ctor
560 }
561}
562
563},{}],4:[function(_dereq_,module,exports){
564module.exports = function isBuffer(arg) {
565 return arg && typeof arg === 'object'
566 && typeof arg.copy === 'function'
567 && typeof arg.fill === 'function'
568 && typeof arg.readUInt8 === 'function';
569}
570},{}],5:[function(_dereq_,module,exports){
571(function (process,global){(function (){
572// Copyright Joyent, Inc. and other Node contributors.
573//
574// Permission is hereby granted, free of charge, to any person obtaining a
575// copy of this software and associated documentation files (the
576// "Software"), to deal in the Software without restriction, including
577// without limitation the rights to use, copy, modify, merge, publish,
578// distribute, sublicense, and/or sell copies of the Software, and to permit
579// persons to whom the Software is furnished to do so, subject to the
580// following conditions:
581//
582// The above copyright notice and this permission notice shall be included
583// in all copies or substantial portions of the Software.
584//
585// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
586// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
587// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
588// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
589// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
590// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
591// USE OR OTHER DEALINGS IN THE SOFTWARE.
592
593var formatRegExp = /%[sdj%]/g;
594exports.format = function(f) {
595 if (!isString(f)) {
596 var objects = [];
597 for (var i = 0; i < arguments.length; i++) {
598 objects.push(inspect(arguments[i]));
599 }
600 return objects.join(' ');
601 }
602
603 var i = 1;
604 var args = arguments;
605 var len = args.length;
606 var str = String(f).replace(formatRegExp, function(x) {
607 if (x === '%%') return '%';
608 if (i >= len) return x;
609 switch (x) {
610 case '%s': return String(args[i++]);
611 case '%d': return Number(args[i++]);
612 case '%j':
613 try {
614 return JSON.stringify(args[i++]);
615 } catch (_) {
616 return '[Circular]';
617 }
618 default:
619 return x;
620 }
621 });
622 for (var x = args[i]; i < len; x = args[++i]) {
623 if (isNull(x) || !isObject(x)) {
624 str += ' ' + x;
625 } else {
626 str += ' ' + inspect(x);
627 }
628 }
629 return str;
630};
631
632
633// Mark that a method should not be used.
634// Returns a modified function which warns once by default.
635// If --no-deprecation is set, then it is a no-op.
636exports.deprecate = function(fn, msg) {
637 // Allow for deprecating things in the process of starting up.
638 if (isUndefined(global.process)) {
639 return function() {
640 return exports.deprecate(fn, msg).apply(this, arguments);
641 };
642 }
643
644 if (process.noDeprecation === true) {
645 return fn;
646 }
647
648 var warned = false;
649 function deprecated() {
650 if (!warned) {
651 if (process.throwDeprecation) {
652 throw new Error(msg);
653 } else if (process.traceDeprecation) {
654 console.trace(msg);
655 } else {
656 console.error(msg);
657 }
658 warned = true;
659 }
660 return fn.apply(this, arguments);
661 }
662
663 return deprecated;
664};
665
666
667var debugs = {};
668var debugEnviron;
669exports.debuglog = function(set) {
670 if (isUndefined(debugEnviron))
671 debugEnviron = process.env.NODE_DEBUG || '';
672 set = set.toUpperCase();
673 if (!debugs[set]) {
674 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
675 var pid = process.pid;
676 debugs[set] = function() {
677 var msg = exports.format.apply(exports, arguments);
678 console.error('%s %d: %s', set, pid, msg);
679 };
680 } else {
681 debugs[set] = function() {};
682 }
683 }
684 return debugs[set];
685};
686
687
688/**
689 * Echos the value of a value. Trys to print the value out
690 * in the best way possible given the different types.
691 *
692 * @param {Object} obj The object to print out.
693 * @param {Object} opts Optional options object that alters the output.
694 */
695/* legacy: obj, showHidden, depth, colors*/
696function inspect(obj, opts) {
697 // default options
698 var ctx = {
699 seen: [],
700 stylize: stylizeNoColor
701 };
702 // legacy...
703 if (arguments.length >= 3) ctx.depth = arguments[2];
704 if (arguments.length >= 4) ctx.colors = arguments[3];
705 if (isBoolean(opts)) {
706 // legacy...
707 ctx.showHidden = opts;
708 } else if (opts) {
709 // got an "options" object
710 exports._extend(ctx, opts);
711 }
712 // set default options
713 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
714 if (isUndefined(ctx.depth)) ctx.depth = 2;
715 if (isUndefined(ctx.colors)) ctx.colors = false;
716 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
717 if (ctx.colors) ctx.stylize = stylizeWithColor;
718 return formatValue(ctx, obj, ctx.depth);
719}
720exports.inspect = inspect;
721
722
723// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
724inspect.colors = {
725 'bold' : [1, 22],
726 'italic' : [3, 23],
727 'underline' : [4, 24],
728 'inverse' : [7, 27],
729 'white' : [37, 39],
730 'grey' : [90, 39],
731 'black' : [30, 39],
732 'blue' : [34, 39],
733 'cyan' : [36, 39],
734 'green' : [32, 39],
735 'magenta' : [35, 39],
736 'red' : [31, 39],
737 'yellow' : [33, 39]
738};
739
740// Don't use 'blue' not visible on cmd.exe
741inspect.styles = {
742 'special': 'cyan',
743 'number': 'yellow',
744 'boolean': 'yellow',
745 'undefined': 'grey',
746 'null': 'bold',
747 'string': 'green',
748 'date': 'magenta',
749 // "name": intentionally not styling
750 'regexp': 'red'
751};
752
753
754function stylizeWithColor(str, styleType) {
755 var style = inspect.styles[styleType];
756
757 if (style) {
758 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
759 '\u001b[' + inspect.colors[style][1] + 'm';
760 } else {
761 return str;
762 }
763}
764
765
766function stylizeNoColor(str, styleType) {
767 return str;
768}
769
770
771function arrayToHash(array) {
772 var hash = {};
773
774 array.forEach(function(val, idx) {
775 hash[val] = true;
776 });
777
778 return hash;
779}
780
781
782function formatValue(ctx, value, recurseTimes) {
783 // Provide a hook for user-specified inspect functions.
784 // Check that value is an object with an inspect function on it
785 if (ctx.customInspect &&
786 value &&
787 isFunction(value.inspect) &&
788 // Filter out the util module, it's inspect function is special
789 value.inspect !== exports.inspect &&
790 // Also filter out any prototype objects using the circular check.
791 !(value.constructor && value.constructor.prototype === value)) {
792 var ret = value.inspect(recurseTimes, ctx);
793 if (!isString(ret)) {
794 ret = formatValue(ctx, ret, recurseTimes);
795 }
796 return ret;
797 }
798
799 // Primitive types cannot have properties
800 var primitive = formatPrimitive(ctx, value);
801 if (primitive) {
802 return primitive;
803 }
804
805 // Look up the keys of the object.
806 var keys = Object.keys(value);
807 var visibleKeys = arrayToHash(keys);
808
809 if (ctx.showHidden) {
810 keys = Object.getOwnPropertyNames(value);
811 }
812
813 // IE doesn't make error fields non-enumerable
814 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
815 if (isError(value)
816 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
817 return formatError(value);
818 }
819
820 // Some type of object without properties can be shortcutted.
821 if (keys.length === 0) {
822 if (isFunction(value)) {
823 var name = value.name ? ': ' + value.name : '';
824 return ctx.stylize('[Function' + name + ']', 'special');
825 }
826 if (isRegExp(value)) {
827 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
828 }
829 if (isDate(value)) {
830 return ctx.stylize(Date.prototype.toString.call(value), 'date');
831 }
832 if (isError(value)) {
833 return formatError(value);
834 }
835 }
836
837 var base = '', array = false, braces = ['{', '}'];
838
839 // Make Array say that they are Array
840 if (isArray(value)) {
841 array = true;
842 braces = ['[', ']'];
843 }
844
845 // Make functions say that they are functions
846 if (isFunction(value)) {
847 var n = value.name ? ': ' + value.name : '';
848 base = ' [Function' + n + ']';
849 }
850
851 // Make RegExps say that they are RegExps
852 if (isRegExp(value)) {
853 base = ' ' + RegExp.prototype.toString.call(value);
854 }
855
856 // Make dates with properties first say the date
857 if (isDate(value)) {
858 base = ' ' + Date.prototype.toUTCString.call(value);
859 }
860
861 // Make error with message first say the error
862 if (isError(value)) {
863 base = ' ' + formatError(value);
864 }
865
866 if (keys.length === 0 && (!array || value.length == 0)) {
867 return braces[0] + base + braces[1];
868 }
869
870 if (recurseTimes < 0) {
871 if (isRegExp(value)) {
872 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
873 } else {
874 return ctx.stylize('[Object]', 'special');
875 }
876 }
877
878 ctx.seen.push(value);
879
880 var output;
881 if (array) {
882 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
883 } else {
884 output = keys.map(function(key) {
885 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
886 });
887 }
888
889 ctx.seen.pop();
890
891 return reduceToSingleString(output, base, braces);
892}
893
894
895function formatPrimitive(ctx, value) {
896 if (isUndefined(value))
897 return ctx.stylize('undefined', 'undefined');
898 if (isString(value)) {
899 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
900 .replace(/'/g, "\\'")
901 .replace(/\\"/g, '"') + '\'';
902 return ctx.stylize(simple, 'string');
903 }
904 if (isNumber(value))
905 return ctx.stylize('' + value, 'number');
906 if (isBoolean(value))
907 return ctx.stylize('' + value, 'boolean');
908 // For some reason typeof null is "object", so special case here.
909 if (isNull(value))
910 return ctx.stylize('null', 'null');
911}
912
913
914function formatError(value) {
915 return '[' + Error.prototype.toString.call(value) + ']';
916}
917
918
919function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
920 var output = [];
921 for (var i = 0, l = value.length; i < l; ++i) {
922 if (hasOwnProperty(value, String(i))) {
923 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
924 String(i), true));
925 } else {
926 output.push('');
927 }
928 }
929 keys.forEach(function(key) {
930 if (!key.match(/^\d+$/)) {
931 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
932 key, true));
933 }
934 });
935 return output;
936}
937
938
939function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
940 var name, str, desc;
941 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
942 if (desc.get) {
943 if (desc.set) {
944 str = ctx.stylize('[Getter/Setter]', 'special');
945 } else {
946 str = ctx.stylize('[Getter]', 'special');
947 }
948 } else {
949 if (desc.set) {
950 str = ctx.stylize('[Setter]', 'special');
951 }
952 }
953 if (!hasOwnProperty(visibleKeys, key)) {
954 name = '[' + key + ']';
955 }
956 if (!str) {
957 if (ctx.seen.indexOf(desc.value) < 0) {
958 if (isNull(recurseTimes)) {
959 str = formatValue(ctx, desc.value, null);
960 } else {
961 str = formatValue(ctx, desc.value, recurseTimes - 1);
962 }
963 if (str.indexOf('\n') > -1) {
964 if (array) {
965 str = str.split('\n').map(function(line) {
966 return ' ' + line;
967 }).join('\n').substr(2);
968 } else {
969 str = '\n' + str.split('\n').map(function(line) {
970 return ' ' + line;
971 }).join('\n');
972 }
973 }
974 } else {
975 str = ctx.stylize('[Circular]', 'special');
976 }
977 }
978 if (isUndefined(name)) {
979 if (array && key.match(/^\d+$/)) {
980 return str;
981 }
982 name = JSON.stringify('' + key);
983 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
984 name = name.substr(1, name.length - 2);
985 name = ctx.stylize(name, 'name');
986 } else {
987 name = name.replace(/'/g, "\\'")
988 .replace(/\\"/g, '"')
989 .replace(/(^"|"$)/g, "'");
990 name = ctx.stylize(name, 'string');
991 }
992 }
993
994 return name + ': ' + str;
995}
996
997
998function reduceToSingleString(output, base, braces) {
999 var numLinesEst = 0;
1000 var length = output.reduce(function(prev, cur) {
1001 numLinesEst++;
1002 if (cur.indexOf('\n') >= 0) numLinesEst++;
1003 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
1004 }, 0);
1005
1006 if (length > 60) {
1007 return braces[0] +
1008 (base === '' ? '' : base + '\n ') +
1009 ' ' +
1010 output.join(',\n ') +
1011 ' ' +
1012 braces[1];
1013 }
1014
1015 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
1016}
1017
1018
1019// NOTE: These type checking functions intentionally don't use `instanceof`
1020// because it is fragile and can be easily faked with `Object.create()`.
1021function isArray(ar) {
1022 return Array.isArray(ar);
1023}
1024exports.isArray = isArray;
1025
1026function isBoolean(arg) {
1027 return typeof arg === 'boolean';
1028}
1029exports.isBoolean = isBoolean;
1030
1031function isNull(arg) {
1032 return arg === null;
1033}
1034exports.isNull = isNull;
1035
1036function isNullOrUndefined(arg) {
1037 return arg == null;
1038}
1039exports.isNullOrUndefined = isNullOrUndefined;
1040
1041function isNumber(arg) {
1042 return typeof arg === 'number';
1043}
1044exports.isNumber = isNumber;
1045
1046function isString(arg) {
1047 return typeof arg === 'string';
1048}
1049exports.isString = isString;
1050
1051function isSymbol(arg) {
1052 return typeof arg === 'symbol';
1053}
1054exports.isSymbol = isSymbol;
1055
1056function isUndefined(arg) {
1057 return arg === void 0;
1058}
1059exports.isUndefined = isUndefined;
1060
1061function isRegExp(re) {
1062 return isObject(re) && objectToString(re) === '[object RegExp]';
1063}
1064exports.isRegExp = isRegExp;
1065
1066function isObject(arg) {
1067 return typeof arg === 'object' && arg !== null;
1068}
1069exports.isObject = isObject;
1070
1071function isDate(d) {
1072 return isObject(d) && objectToString(d) === '[object Date]';
1073}
1074exports.isDate = isDate;
1075
1076function isError(e) {
1077 return isObject(e) &&
1078 (objectToString(e) === '[object Error]' || e instanceof Error);
1079}
1080exports.isError = isError;
1081
1082function isFunction(arg) {
1083 return typeof arg === 'function';
1084}
1085exports.isFunction = isFunction;
1086
1087function isPrimitive(arg) {
1088 return arg === null ||
1089 typeof arg === 'boolean' ||
1090 typeof arg === 'number' ||
1091 typeof arg === 'string' ||
1092 typeof arg === 'symbol' || // ES6 symbol
1093 typeof arg === 'undefined';
1094}
1095exports.isPrimitive = isPrimitive;
1096
1097exports.isBuffer = _dereq_(4);
1098
1099function objectToString(o) {
1100 return Object.prototype.toString.call(o);
1101}
1102
1103
1104function pad(n) {
1105 return n < 10 ? '0' + n.toString(10) : n.toString(10);
1106}
1107
1108
1109var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
1110 'Oct', 'Nov', 'Dec'];
1111
1112// 26 Feb 16:19:34
1113function timestamp() {
1114 var d = new Date();
1115 var time = [pad(d.getHours()),
1116 pad(d.getMinutes()),
1117 pad(d.getSeconds())].join(':');
1118 return [d.getDate(), months[d.getMonth()], time].join(' ');
1119}
1120
1121
1122// log is just a thin wrapper to console.log that prepends a timestamp
1123exports.log = function() {
1124 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
1125};
1126
1127
1128/**
1129 * Inherit the prototype methods from one constructor into another.
1130 *
1131 * The Function.prototype.inherits from lang.js rewritten as a standalone
1132 * function (not on Function.prototype). NOTE: If this file is to be loaded
1133 * during bootstrapping this function needs to be rewritten using some native
1134 * functions as prototype setup using normal JavaScript does not work as
1135 * expected during bootstrapping (see mirror.js in r114903).
1136 *
1137 * @param {function} ctor Constructor function which needs to inherit the
1138 * prototype.
1139 * @param {function} superCtor Constructor function to inherit prototype from.
1140 */
1141exports.inherits = _dereq_(3);
1142
1143exports._extend = function(origin, add) {
1144 // Don't do anything if add isn't an object
1145 if (!add || !isObject(add)) return origin;
1146
1147 var keys = Object.keys(add);
1148 var i = keys.length;
1149 while (i--) {
1150 origin[keys[i]] = add[keys[i]];
1151 }
1152 return origin;
1153};
1154
1155function hasOwnProperty(obj, prop) {
1156 return Object.prototype.hasOwnProperty.call(obj, prop);
1157}
1158
1159}).call(this)}).call(this,_dereq_(67),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1160},{"3":3,"4":4,"67":67}],6:[function(_dereq_,module,exports){
1161'use strict'
1162
1163exports.byteLength = byteLength
1164exports.toByteArray = toByteArray
1165exports.fromByteArray = fromByteArray
1166
1167var lookup = []
1168var revLookup = []
1169var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
1170
1171var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1172for (var i = 0, len = code.length; i < len; ++i) {
1173 lookup[i] = code[i]
1174 revLookup[code.charCodeAt(i)] = i
1175}
1176
1177// Support decoding URL-safe base64 strings, as Node.js does.
1178// See: https://en.wikipedia.org/wiki/Base64#URL_applications
1179revLookup['-'.charCodeAt(0)] = 62
1180revLookup['_'.charCodeAt(0)] = 63
1181
1182function getLens (b64) {
1183 var len = b64.length
1184
1185 if (len % 4 > 0) {
1186 throw new Error('Invalid string. Length must be a multiple of 4')
1187 }
1188
1189 // Trim off extra bytes after placeholder bytes are found
1190 // See: https://github.com/beatgammit/base64-js/issues/42
1191 var validLen = b64.indexOf('=')
1192 if (validLen === -1) validLen = len
1193
1194 var placeHoldersLen = validLen === len
1195 ? 0
1196 : 4 - (validLen % 4)
1197
1198 return [validLen, placeHoldersLen]
1199}
1200
1201// base64 is 4/3 + up to two characters of the original data
1202function byteLength (b64) {
1203 var lens = getLens(b64)
1204 var validLen = lens[0]
1205 var placeHoldersLen = lens[1]
1206 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1207}
1208
1209function _byteLength (b64, validLen, placeHoldersLen) {
1210 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1211}
1212
1213function toByteArray (b64) {
1214 var tmp
1215 var lens = getLens(b64)
1216 var validLen = lens[0]
1217 var placeHoldersLen = lens[1]
1218
1219 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1220
1221 var curByte = 0
1222
1223 // if there are placeholders, only get up to the last complete 4 chars
1224 var len = placeHoldersLen > 0
1225 ? validLen - 4
1226 : validLen
1227
1228 var i
1229 for (i = 0; i < len; i += 4) {
1230 tmp =
1231 (revLookup[b64.charCodeAt(i)] << 18) |
1232 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1233 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1234 revLookup[b64.charCodeAt(i + 3)]
1235 arr[curByte++] = (tmp >> 16) & 0xFF
1236 arr[curByte++] = (tmp >> 8) & 0xFF
1237 arr[curByte++] = tmp & 0xFF
1238 }
1239
1240 if (placeHoldersLen === 2) {
1241 tmp =
1242 (revLookup[b64.charCodeAt(i)] << 2) |
1243 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1244 arr[curByte++] = tmp & 0xFF
1245 }
1246
1247 if (placeHoldersLen === 1) {
1248 tmp =
1249 (revLookup[b64.charCodeAt(i)] << 10) |
1250 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1251 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1252 arr[curByte++] = (tmp >> 8) & 0xFF
1253 arr[curByte++] = tmp & 0xFF
1254 }
1255
1256 return arr
1257}
1258
1259function tripletToBase64 (num) {
1260 return lookup[num >> 18 & 0x3F] +
1261 lookup[num >> 12 & 0x3F] +
1262 lookup[num >> 6 & 0x3F] +
1263 lookup[num & 0x3F]
1264}
1265
1266function encodeChunk (uint8, start, end) {
1267 var tmp
1268 var output = []
1269 for (var i = start; i < end; i += 3) {
1270 tmp =
1271 ((uint8[i] << 16) & 0xFF0000) +
1272 ((uint8[i + 1] << 8) & 0xFF00) +
1273 (uint8[i + 2] & 0xFF)
1274 output.push(tripletToBase64(tmp))
1275 }
1276 return output.join('')
1277}
1278
1279function fromByteArray (uint8) {
1280 var tmp
1281 var len = uint8.length
1282 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1283 var parts = []
1284 var maxChunkLength = 16383 // must be multiple of 3
1285
1286 // go through the array every three bytes, we'll deal with trailing stuff later
1287 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1288 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
1289 }
1290
1291 // pad the end with zeros, but make sure to not forget the extra bytes
1292 if (extraBytes === 1) {
1293 tmp = uint8[len - 1]
1294 parts.push(
1295 lookup[tmp >> 2] +
1296 lookup[(tmp << 4) & 0x3F] +
1297 '=='
1298 )
1299 } else if (extraBytes === 2) {
1300 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1301 parts.push(
1302 lookup[tmp >> 10] +
1303 lookup[(tmp >> 4) & 0x3F] +
1304 lookup[(tmp << 2) & 0x3F] +
1305 '='
1306 )
1307 }
1308
1309 return parts.join('')
1310}
1311
1312},{}],7:[function(_dereq_,module,exports){
1313
1314},{}],8:[function(_dereq_,module,exports){
1315(function (Buffer){(function (){
1316/* eslint-disable node/no-deprecated-api */
1317
1318var toString = Object.prototype.toString
1319
1320var isModern = (
1321 typeof Buffer !== 'undefined' &&
1322 typeof Buffer.alloc === 'function' &&
1323 typeof Buffer.allocUnsafe === 'function' &&
1324 typeof Buffer.from === 'function'
1325)
1326
1327function isArrayBuffer (input) {
1328 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1329}
1330
1331function fromArrayBuffer (obj, byteOffset, length) {
1332 byteOffset >>>= 0
1333
1334 var maxLength = obj.byteLength - byteOffset
1335
1336 if (maxLength < 0) {
1337 throw new RangeError("'offset' is out of bounds")
1338 }
1339
1340 if (length === undefined) {
1341 length = maxLength
1342 } else {
1343 length >>>= 0
1344
1345 if (length > maxLength) {
1346 throw new RangeError("'length' is out of bounds")
1347 }
1348 }
1349
1350 return isModern
1351 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1352 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1353}
1354
1355function fromString (string, encoding) {
1356 if (typeof encoding !== 'string' || encoding === '') {
1357 encoding = 'utf8'
1358 }
1359
1360 if (!Buffer.isEncoding(encoding)) {
1361 throw new TypeError('"encoding" must be a valid string encoding')
1362 }
1363
1364 return isModern
1365 ? Buffer.from(string, encoding)
1366 : new Buffer(string, encoding)
1367}
1368
1369function bufferFrom (value, encodingOrOffset, length) {
1370 if (typeof value === 'number') {
1371 throw new TypeError('"value" argument must not be a number')
1372 }
1373
1374 if (isArrayBuffer(value)) {
1375 return fromArrayBuffer(value, encodingOrOffset, length)
1376 }
1377
1378 if (typeof value === 'string') {
1379 return fromString(value, encodingOrOffset)
1380 }
1381
1382 return isModern
1383 ? Buffer.from(value)
1384 : new Buffer(value)
1385}
1386
1387module.exports = bufferFrom
1388
1389}).call(this)}).call(this,_dereq_(9).Buffer)
1390},{"9":9}],9:[function(_dereq_,module,exports){
1391(function (Buffer){(function (){
1392/*!
1393 * The buffer module from node.js, for the browser.
1394 *
1395 * @author Feross Aboukhadijeh <https://feross.org>
1396 * @license MIT
1397 */
1398/* eslint-disable no-proto */
1399
1400'use strict'
1401
1402var base64 = _dereq_(6)
1403var ieee754 = _dereq_(23)
1404var customInspectSymbol =
1405 (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
1406 ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
1407 : null
1408
1409exports.Buffer = Buffer
1410exports.SlowBuffer = SlowBuffer
1411exports.INSPECT_MAX_BYTES = 50
1412
1413var K_MAX_LENGTH = 0x7fffffff
1414exports.kMaxLength = K_MAX_LENGTH
1415
1416/**
1417 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1418 * === true Use Uint8Array implementation (fastest)
1419 * === false Print warning and recommend using `buffer` v4.x which has an Object
1420 * implementation (most compatible, even IE6)
1421 *
1422 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1423 * Opera 11.6+, iOS 4.2+.
1424 *
1425 * We report that the browser does not support typed arrays if the are not subclassable
1426 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1427 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1428 * for __proto__ and has a buggy typed array implementation.
1429 */
1430Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1431
1432if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1433 typeof console.error === 'function') {
1434 console.error(
1435 'This browser lacks typed array (Uint8Array) support which is required by ' +
1436 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1437 )
1438}
1439
1440function typedArraySupport () {
1441 // Can typed array instances can be augmented?
1442 try {
1443 var arr = new Uint8Array(1)
1444 var proto = { foo: function () { return 42 } }
1445 Object.setPrototypeOf(proto, Uint8Array.prototype)
1446 Object.setPrototypeOf(arr, proto)
1447 return arr.foo() === 42
1448 } catch (e) {
1449 return false
1450 }
1451}
1452
1453Object.defineProperty(Buffer.prototype, 'parent', {
1454 enumerable: true,
1455 get: function () {
1456 if (!Buffer.isBuffer(this)) return undefined
1457 return this.buffer
1458 }
1459})
1460
1461Object.defineProperty(Buffer.prototype, 'offset', {
1462 enumerable: true,
1463 get: function () {
1464 if (!Buffer.isBuffer(this)) return undefined
1465 return this.byteOffset
1466 }
1467})
1468
1469function createBuffer (length) {
1470 if (length > K_MAX_LENGTH) {
1471 throw new RangeError('The value "' + length + '" is invalid for option "size"')
1472 }
1473 // Return an augmented `Uint8Array` instance
1474 var buf = new Uint8Array(length)
1475 Object.setPrototypeOf(buf, Buffer.prototype)
1476 return buf
1477}
1478
1479/**
1480 * The Buffer constructor returns instances of `Uint8Array` that have their
1481 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1482 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1483 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1484 * returns a single octet.
1485 *
1486 * The `Uint8Array` prototype remains unmodified.
1487 */
1488
1489function Buffer (arg, encodingOrOffset, length) {
1490 // Common case.
1491 if (typeof arg === 'number') {
1492 if (typeof encodingOrOffset === 'string') {
1493 throw new TypeError(
1494 'The "string" argument must be of type string. Received type number'
1495 )
1496 }
1497 return allocUnsafe(arg)
1498 }
1499 return from(arg, encodingOrOffset, length)
1500}
1501
1502Buffer.poolSize = 8192 // not used by this implementation
1503
1504function from (value, encodingOrOffset, length) {
1505 if (typeof value === 'string') {
1506 return fromString(value, encodingOrOffset)
1507 }
1508
1509 if (ArrayBuffer.isView(value)) {
1510 return fromArrayView(value)
1511 }
1512
1513 if (value == null) {
1514 throw new TypeError(
1515 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1516 'or Array-like Object. Received type ' + (typeof value)
1517 )
1518 }
1519
1520 if (isInstance(value, ArrayBuffer) ||
1521 (value && isInstance(value.buffer, ArrayBuffer))) {
1522 return fromArrayBuffer(value, encodingOrOffset, length)
1523 }
1524
1525 if (typeof SharedArrayBuffer !== 'undefined' &&
1526 (isInstance(value, SharedArrayBuffer) ||
1527 (value && isInstance(value.buffer, SharedArrayBuffer)))) {
1528 return fromArrayBuffer(value, encodingOrOffset, length)
1529 }
1530
1531 if (typeof value === 'number') {
1532 throw new TypeError(
1533 'The "value" argument must not be of type number. Received type number'
1534 )
1535 }
1536
1537 var valueOf = value.valueOf && value.valueOf()
1538 if (valueOf != null && valueOf !== value) {
1539 return Buffer.from(valueOf, encodingOrOffset, length)
1540 }
1541
1542 var b = fromObject(value)
1543 if (b) return b
1544
1545 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
1546 typeof value[Symbol.toPrimitive] === 'function') {
1547 return Buffer.from(
1548 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
1549 )
1550 }
1551
1552 throw new TypeError(
1553 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1554 'or Array-like Object. Received type ' + (typeof value)
1555 )
1556}
1557
1558/**
1559 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1560 * if value is a number.
1561 * Buffer.from(str[, encoding])
1562 * Buffer.from(array)
1563 * Buffer.from(buffer)
1564 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1565 **/
1566Buffer.from = function (value, encodingOrOffset, length) {
1567 return from(value, encodingOrOffset, length)
1568}
1569
1570// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1571// https://github.com/feross/buffer/pull/148
1572Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
1573Object.setPrototypeOf(Buffer, Uint8Array)
1574
1575function assertSize (size) {
1576 if (typeof size !== 'number') {
1577 throw new TypeError('"size" argument must be of type number')
1578 } else if (size < 0) {
1579 throw new RangeError('The value "' + size + '" is invalid for option "size"')
1580 }
1581}
1582
1583function alloc (size, fill, encoding) {
1584 assertSize(size)
1585 if (size <= 0) {
1586 return createBuffer(size)
1587 }
1588 if (fill !== undefined) {
1589 // Only pay attention to encoding if it's a string. This
1590 // prevents accidentally sending in a number that would
1591 // be interpreted as a start offset.
1592 return typeof encoding === 'string'
1593 ? createBuffer(size).fill(fill, encoding)
1594 : createBuffer(size).fill(fill)
1595 }
1596 return createBuffer(size)
1597}
1598
1599/**
1600 * Creates a new filled Buffer instance.
1601 * alloc(size[, fill[, encoding]])
1602 **/
1603Buffer.alloc = function (size, fill, encoding) {
1604 return alloc(size, fill, encoding)
1605}
1606
1607function allocUnsafe (size) {
1608 assertSize(size)
1609 return createBuffer(size < 0 ? 0 : checked(size) | 0)
1610}
1611
1612/**
1613 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
1614 * */
1615Buffer.allocUnsafe = function (size) {
1616 return allocUnsafe(size)
1617}
1618/**
1619 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
1620 */
1621Buffer.allocUnsafeSlow = function (size) {
1622 return allocUnsafe(size)
1623}
1624
1625function fromString (string, encoding) {
1626 if (typeof encoding !== 'string' || encoding === '') {
1627 encoding = 'utf8'
1628 }
1629
1630 if (!Buffer.isEncoding(encoding)) {
1631 throw new TypeError('Unknown encoding: ' + encoding)
1632 }
1633
1634 var length = byteLength(string, encoding) | 0
1635 var buf = createBuffer(length)
1636
1637 var actual = buf.write(string, encoding)
1638
1639 if (actual !== length) {
1640 // Writing a hex string, for example, that contains invalid characters will
1641 // cause everything after the first invalid character to be ignored. (e.g.
1642 // 'abxxcd' will be treated as 'ab')
1643 buf = buf.slice(0, actual)
1644 }
1645
1646 return buf
1647}
1648
1649function fromArrayLike (array) {
1650 var length = array.length < 0 ? 0 : checked(array.length) | 0
1651 var buf = createBuffer(length)
1652 for (var i = 0; i < length; i += 1) {
1653 buf[i] = array[i] & 255
1654 }
1655 return buf
1656}
1657
1658function fromArrayView (arrayView) {
1659 if (isInstance(arrayView, Uint8Array)) {
1660 var copy = new Uint8Array(arrayView)
1661 return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
1662 }
1663 return fromArrayLike(arrayView)
1664}
1665
1666function fromArrayBuffer (array, byteOffset, length) {
1667 if (byteOffset < 0 || array.byteLength < byteOffset) {
1668 throw new RangeError('"offset" is outside of buffer bounds')
1669 }
1670
1671 if (array.byteLength < byteOffset + (length || 0)) {
1672 throw new RangeError('"length" is outside of buffer bounds')
1673 }
1674
1675 var buf
1676 if (byteOffset === undefined && length === undefined) {
1677 buf = new Uint8Array(array)
1678 } else if (length === undefined) {
1679 buf = new Uint8Array(array, byteOffset)
1680 } else {
1681 buf = new Uint8Array(array, byteOffset, length)
1682 }
1683
1684 // Return an augmented `Uint8Array` instance
1685 Object.setPrototypeOf(buf, Buffer.prototype)
1686
1687 return buf
1688}
1689
1690function fromObject (obj) {
1691 if (Buffer.isBuffer(obj)) {
1692 var len = checked(obj.length) | 0
1693 var buf = createBuffer(len)
1694
1695 if (buf.length === 0) {
1696 return buf
1697 }
1698
1699 obj.copy(buf, 0, 0, len)
1700 return buf
1701 }
1702
1703 if (obj.length !== undefined) {
1704 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
1705 return createBuffer(0)
1706 }
1707 return fromArrayLike(obj)
1708 }
1709
1710 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
1711 return fromArrayLike(obj.data)
1712 }
1713}
1714
1715function checked (length) {
1716 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
1717 // length is NaN (which is otherwise coerced to zero.)
1718 if (length >= K_MAX_LENGTH) {
1719 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1720 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1721 }
1722 return length | 0
1723}
1724
1725function SlowBuffer (length) {
1726 if (+length != length) { // eslint-disable-line eqeqeq
1727 length = 0
1728 }
1729 return Buffer.alloc(+length)
1730}
1731
1732Buffer.isBuffer = function isBuffer (b) {
1733 return b != null && b._isBuffer === true &&
1734 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
1735}
1736
1737Buffer.compare = function compare (a, b) {
1738 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
1739 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
1740 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1741 throw new TypeError(
1742 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
1743 )
1744 }
1745
1746 if (a === b) return 0
1747
1748 var x = a.length
1749 var y = b.length
1750
1751 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1752 if (a[i] !== b[i]) {
1753 x = a[i]
1754 y = b[i]
1755 break
1756 }
1757 }
1758
1759 if (x < y) return -1
1760 if (y < x) return 1
1761 return 0
1762}
1763
1764Buffer.isEncoding = function isEncoding (encoding) {
1765 switch (String(encoding).toLowerCase()) {
1766 case 'hex':
1767 case 'utf8':
1768 case 'utf-8':
1769 case 'ascii':
1770 case 'latin1':
1771 case 'binary':
1772 case 'base64':
1773 case 'ucs2':
1774 case 'ucs-2':
1775 case 'utf16le':
1776 case 'utf-16le':
1777 return true
1778 default:
1779 return false
1780 }
1781}
1782
1783Buffer.concat = function concat (list, length) {
1784 if (!Array.isArray(list)) {
1785 throw new TypeError('"list" argument must be an Array of Buffers')
1786 }
1787
1788 if (list.length === 0) {
1789 return Buffer.alloc(0)
1790 }
1791
1792 var i
1793 if (length === undefined) {
1794 length = 0
1795 for (i = 0; i < list.length; ++i) {
1796 length += list[i].length
1797 }
1798 }
1799
1800 var buffer = Buffer.allocUnsafe(length)
1801 var pos = 0
1802 for (i = 0; i < list.length; ++i) {
1803 var buf = list[i]
1804 if (isInstance(buf, Uint8Array)) {
1805 if (pos + buf.length > buffer.length) {
1806 Buffer.from(buf).copy(buffer, pos)
1807 } else {
1808 Uint8Array.prototype.set.call(
1809 buffer,
1810 buf,
1811 pos
1812 )
1813 }
1814 } else if (!Buffer.isBuffer(buf)) {
1815 throw new TypeError('"list" argument must be an Array of Buffers')
1816 } else {
1817 buf.copy(buffer, pos)
1818 }
1819 pos += buf.length
1820 }
1821 return buffer
1822}
1823
1824function byteLength (string, encoding) {
1825 if (Buffer.isBuffer(string)) {
1826 return string.length
1827 }
1828 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
1829 return string.byteLength
1830 }
1831 if (typeof string !== 'string') {
1832 throw new TypeError(
1833 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
1834 'Received type ' + typeof string
1835 )
1836 }
1837
1838 var len = string.length
1839 var mustMatch = (arguments.length > 2 && arguments[2] === true)
1840 if (!mustMatch && len === 0) return 0
1841
1842 // Use a for loop to avoid recursion
1843 var loweredCase = false
1844 for (;;) {
1845 switch (encoding) {
1846 case 'ascii':
1847 case 'latin1':
1848 case 'binary':
1849 return len
1850 case 'utf8':
1851 case 'utf-8':
1852 return utf8ToBytes(string).length
1853 case 'ucs2':
1854 case 'ucs-2':
1855 case 'utf16le':
1856 case 'utf-16le':
1857 return len * 2
1858 case 'hex':
1859 return len >>> 1
1860 case 'base64':
1861 return base64ToBytes(string).length
1862 default:
1863 if (loweredCase) {
1864 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
1865 }
1866 encoding = ('' + encoding).toLowerCase()
1867 loweredCase = true
1868 }
1869 }
1870}
1871Buffer.byteLength = byteLength
1872
1873function slowToString (encoding, start, end) {
1874 var loweredCase = false
1875
1876 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1877 // property of a typed array.
1878
1879 // This behaves neither like String nor Uint8Array in that we set start/end
1880 // to their upper/lower bounds if the value passed is out of range.
1881 // undefined is handled specially as per ECMA-262 6th Edition,
1882 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1883 if (start === undefined || start < 0) {
1884 start = 0
1885 }
1886 // Return early if start > this.length. Done here to prevent potential uint32
1887 // coercion fail below.
1888 if (start > this.length) {
1889 return ''
1890 }
1891
1892 if (end === undefined || end > this.length) {
1893 end = this.length
1894 }
1895
1896 if (end <= 0) {
1897 return ''
1898 }
1899
1900 // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
1901 end >>>= 0
1902 start >>>= 0
1903
1904 if (end <= start) {
1905 return ''
1906 }
1907
1908 if (!encoding) encoding = 'utf8'
1909
1910 while (true) {
1911 switch (encoding) {
1912 case 'hex':
1913 return hexSlice(this, start, end)
1914
1915 case 'utf8':
1916 case 'utf-8':
1917 return utf8Slice(this, start, end)
1918
1919 case 'ascii':
1920 return asciiSlice(this, start, end)
1921
1922 case 'latin1':
1923 case 'binary':
1924 return latin1Slice(this, start, end)
1925
1926 case 'base64':
1927 return base64Slice(this, start, end)
1928
1929 case 'ucs2':
1930 case 'ucs-2':
1931 case 'utf16le':
1932 case 'utf-16le':
1933 return utf16leSlice(this, start, end)
1934
1935 default:
1936 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1937 encoding = (encoding + '').toLowerCase()
1938 loweredCase = true
1939 }
1940 }
1941}
1942
1943// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1944// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1945// reliably in a browserify context because there could be multiple different
1946// copies of the 'buffer' package in use. This method works even for Buffer
1947// instances that were created from another copy of the `buffer` package.
1948// See: https://github.com/feross/buffer/issues/154
1949Buffer.prototype._isBuffer = true
1950
1951function swap (b, n, m) {
1952 var i = b[n]
1953 b[n] = b[m]
1954 b[m] = i
1955}
1956
1957Buffer.prototype.swap16 = function swap16 () {
1958 var len = this.length
1959 if (len % 2 !== 0) {
1960 throw new RangeError('Buffer size must be a multiple of 16-bits')
1961 }
1962 for (var i = 0; i < len; i += 2) {
1963 swap(this, i, i + 1)
1964 }
1965 return this
1966}
1967
1968Buffer.prototype.swap32 = function swap32 () {
1969 var len = this.length
1970 if (len % 4 !== 0) {
1971 throw new RangeError('Buffer size must be a multiple of 32-bits')
1972 }
1973 for (var i = 0; i < len; i += 4) {
1974 swap(this, i, i + 3)
1975 swap(this, i + 1, i + 2)
1976 }
1977 return this
1978}
1979
1980Buffer.prototype.swap64 = function swap64 () {
1981 var len = this.length
1982 if (len % 8 !== 0) {
1983 throw new RangeError('Buffer size must be a multiple of 64-bits')
1984 }
1985 for (var i = 0; i < len; i += 8) {
1986 swap(this, i, i + 7)
1987 swap(this, i + 1, i + 6)
1988 swap(this, i + 2, i + 5)
1989 swap(this, i + 3, i + 4)
1990 }
1991 return this
1992}
1993
1994Buffer.prototype.toString = function toString () {
1995 var length = this.length
1996 if (length === 0) return ''
1997 if (arguments.length === 0) return utf8Slice(this, 0, length)
1998 return slowToString.apply(this, arguments)
1999}
2000
2001Buffer.prototype.toLocaleString = Buffer.prototype.toString
2002
2003Buffer.prototype.equals = function equals (b) {
2004 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2005 if (this === b) return true
2006 return Buffer.compare(this, b) === 0
2007}
2008
2009Buffer.prototype.inspect = function inspect () {
2010 var str = ''
2011 var max = exports.INSPECT_MAX_BYTES
2012 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
2013 if (this.length > max) str += ' ... '
2014 return '<Buffer ' + str + '>'
2015}
2016if (customInspectSymbol) {
2017 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
2018}
2019
2020Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2021 if (isInstance(target, Uint8Array)) {
2022 target = Buffer.from(target, target.offset, target.byteLength)
2023 }
2024 if (!Buffer.isBuffer(target)) {
2025 throw new TypeError(
2026 'The "target" argument must be one of type Buffer or Uint8Array. ' +
2027 'Received type ' + (typeof target)
2028 )
2029 }
2030
2031 if (start === undefined) {
2032 start = 0
2033 }
2034 if (end === undefined) {
2035 end = target ? target.length : 0
2036 }
2037 if (thisStart === undefined) {
2038 thisStart = 0
2039 }
2040 if (thisEnd === undefined) {
2041 thisEnd = this.length
2042 }
2043
2044 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2045 throw new RangeError('out of range index')
2046 }
2047
2048 if (thisStart >= thisEnd && start >= end) {
2049 return 0
2050 }
2051 if (thisStart >= thisEnd) {
2052 return -1
2053 }
2054 if (start >= end) {
2055 return 1
2056 }
2057
2058 start >>>= 0
2059 end >>>= 0
2060 thisStart >>>= 0
2061 thisEnd >>>= 0
2062
2063 if (this === target) return 0
2064
2065 var x = thisEnd - thisStart
2066 var y = end - start
2067 var len = Math.min(x, y)
2068
2069 var thisCopy = this.slice(thisStart, thisEnd)
2070 var targetCopy = target.slice(start, end)
2071
2072 for (var i = 0; i < len; ++i) {
2073 if (thisCopy[i] !== targetCopy[i]) {
2074 x = thisCopy[i]
2075 y = targetCopy[i]
2076 break
2077 }
2078 }
2079
2080 if (x < y) return -1
2081 if (y < x) return 1
2082 return 0
2083}
2084
2085// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2086// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2087//
2088// Arguments:
2089// - buffer - a Buffer to search
2090// - val - a string, Buffer, or number
2091// - byteOffset - an index into `buffer`; will be clamped to an int32
2092// - encoding - an optional encoding, relevant is val is a string
2093// - dir - true for indexOf, false for lastIndexOf
2094function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2095 // Empty buffer means no match
2096 if (buffer.length === 0) return -1
2097
2098 // Normalize byteOffset
2099 if (typeof byteOffset === 'string') {
2100 encoding = byteOffset
2101 byteOffset = 0
2102 } else if (byteOffset > 0x7fffffff) {
2103 byteOffset = 0x7fffffff
2104 } else if (byteOffset < -0x80000000) {
2105 byteOffset = -0x80000000
2106 }
2107 byteOffset = +byteOffset // Coerce to Number.
2108 if (numberIsNaN(byteOffset)) {
2109 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2110 byteOffset = dir ? 0 : (buffer.length - 1)
2111 }
2112
2113 // Normalize byteOffset: negative offsets start from the end of the buffer
2114 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2115 if (byteOffset >= buffer.length) {
2116 if (dir) return -1
2117 else byteOffset = buffer.length - 1
2118 } else if (byteOffset < 0) {
2119 if (dir) byteOffset = 0
2120 else return -1
2121 }
2122
2123 // Normalize val
2124 if (typeof val === 'string') {
2125 val = Buffer.from(val, encoding)
2126 }
2127
2128 // Finally, search either indexOf (if dir is true) or lastIndexOf
2129 if (Buffer.isBuffer(val)) {
2130 // Special case: looking for empty string/buffer always fails
2131 if (val.length === 0) {
2132 return -1
2133 }
2134 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2135 } else if (typeof val === 'number') {
2136 val = val & 0xFF // Search for a byte value [0-255]
2137 if (typeof Uint8Array.prototype.indexOf === 'function') {
2138 if (dir) {
2139 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2140 } else {
2141 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2142 }
2143 }
2144 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
2145 }
2146
2147 throw new TypeError('val must be string, number or Buffer')
2148}
2149
2150function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2151 var indexSize = 1
2152 var arrLength = arr.length
2153 var valLength = val.length
2154
2155 if (encoding !== undefined) {
2156 encoding = String(encoding).toLowerCase()
2157 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2158 encoding === 'utf16le' || encoding === 'utf-16le') {
2159 if (arr.length < 2 || val.length < 2) {
2160 return -1
2161 }
2162 indexSize = 2
2163 arrLength /= 2
2164 valLength /= 2
2165 byteOffset /= 2
2166 }
2167 }
2168
2169 function read (buf, i) {
2170 if (indexSize === 1) {
2171 return buf[i]
2172 } else {
2173 return buf.readUInt16BE(i * indexSize)
2174 }
2175 }
2176
2177 var i
2178 if (dir) {
2179 var foundIndex = -1
2180 for (i = byteOffset; i < arrLength; i++) {
2181 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2182 if (foundIndex === -1) foundIndex = i
2183 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2184 } else {
2185 if (foundIndex !== -1) i -= i - foundIndex
2186 foundIndex = -1
2187 }
2188 }
2189 } else {
2190 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2191 for (i = byteOffset; i >= 0; i--) {
2192 var found = true
2193 for (var j = 0; j < valLength; j++) {
2194 if (read(arr, i + j) !== read(val, j)) {
2195 found = false
2196 break
2197 }
2198 }
2199 if (found) return i
2200 }
2201 }
2202
2203 return -1
2204}
2205
2206Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2207 return this.indexOf(val, byteOffset, encoding) !== -1
2208}
2209
2210Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2211 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2212}
2213
2214Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2215 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2216}
2217
2218function hexWrite (buf, string, offset, length) {
2219 offset = Number(offset) || 0
2220 var remaining = buf.length - offset
2221 if (!length) {
2222 length = remaining
2223 } else {
2224 length = Number(length)
2225 if (length > remaining) {
2226 length = remaining
2227 }
2228 }
2229
2230 var strLen = string.length
2231
2232 if (length > strLen / 2) {
2233 length = strLen / 2
2234 }
2235 for (var i = 0; i < length; ++i) {
2236 var parsed = parseInt(string.substr(i * 2, 2), 16)
2237 if (numberIsNaN(parsed)) return i
2238 buf[offset + i] = parsed
2239 }
2240 return i
2241}
2242
2243function utf8Write (buf, string, offset, length) {
2244 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2245}
2246
2247function asciiWrite (buf, string, offset, length) {
2248 return blitBuffer(asciiToBytes(string), buf, offset, length)
2249}
2250
2251function base64Write (buf, string, offset, length) {
2252 return blitBuffer(base64ToBytes(string), buf, offset, length)
2253}
2254
2255function ucs2Write (buf, string, offset, length) {
2256 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2257}
2258
2259Buffer.prototype.write = function write (string, offset, length, encoding) {
2260 // Buffer#write(string)
2261 if (offset === undefined) {
2262 encoding = 'utf8'
2263 length = this.length
2264 offset = 0
2265 // Buffer#write(string, encoding)
2266 } else if (length === undefined && typeof offset === 'string') {
2267 encoding = offset
2268 length = this.length
2269 offset = 0
2270 // Buffer#write(string, offset[, length][, encoding])
2271 } else if (isFinite(offset)) {
2272 offset = offset >>> 0
2273 if (isFinite(length)) {
2274 length = length >>> 0
2275 if (encoding === undefined) encoding = 'utf8'
2276 } else {
2277 encoding = length
2278 length = undefined
2279 }
2280 } else {
2281 throw new Error(
2282 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2283 )
2284 }
2285
2286 var remaining = this.length - offset
2287 if (length === undefined || length > remaining) length = remaining
2288
2289 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2290 throw new RangeError('Attempt to write outside buffer bounds')
2291 }
2292
2293 if (!encoding) encoding = 'utf8'
2294
2295 var loweredCase = false
2296 for (;;) {
2297 switch (encoding) {
2298 case 'hex':
2299 return hexWrite(this, string, offset, length)
2300
2301 case 'utf8':
2302 case 'utf-8':
2303 return utf8Write(this, string, offset, length)
2304
2305 case 'ascii':
2306 case 'latin1':
2307 case 'binary':
2308 return asciiWrite(this, string, offset, length)
2309
2310 case 'base64':
2311 // Warning: maxLength not taken into account in base64Write
2312 return base64Write(this, string, offset, length)
2313
2314 case 'ucs2':
2315 case 'ucs-2':
2316 case 'utf16le':
2317 case 'utf-16le':
2318 return ucs2Write(this, string, offset, length)
2319
2320 default:
2321 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2322 encoding = ('' + encoding).toLowerCase()
2323 loweredCase = true
2324 }
2325 }
2326}
2327
2328Buffer.prototype.toJSON = function toJSON () {
2329 return {
2330 type: 'Buffer',
2331 data: Array.prototype.slice.call(this._arr || this, 0)
2332 }
2333}
2334
2335function base64Slice (buf, start, end) {
2336 if (start === 0 && end === buf.length) {
2337 return base64.fromByteArray(buf)
2338 } else {
2339 return base64.fromByteArray(buf.slice(start, end))
2340 }
2341}
2342
2343function utf8Slice (buf, start, end) {
2344 end = Math.min(buf.length, end)
2345 var res = []
2346
2347 var i = start
2348 while (i < end) {
2349 var firstByte = buf[i]
2350 var codePoint = null
2351 var bytesPerSequence = (firstByte > 0xEF)
2352 ? 4
2353 : (firstByte > 0xDF)
2354 ? 3
2355 : (firstByte > 0xBF)
2356 ? 2
2357 : 1
2358
2359 if (i + bytesPerSequence <= end) {
2360 var secondByte, thirdByte, fourthByte, tempCodePoint
2361
2362 switch (bytesPerSequence) {
2363 case 1:
2364 if (firstByte < 0x80) {
2365 codePoint = firstByte
2366 }
2367 break
2368 case 2:
2369 secondByte = buf[i + 1]
2370 if ((secondByte & 0xC0) === 0x80) {
2371 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2372 if (tempCodePoint > 0x7F) {
2373 codePoint = tempCodePoint
2374 }
2375 }
2376 break
2377 case 3:
2378 secondByte = buf[i + 1]
2379 thirdByte = buf[i + 2]
2380 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2381 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2382 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2383 codePoint = tempCodePoint
2384 }
2385 }
2386 break
2387 case 4:
2388 secondByte = buf[i + 1]
2389 thirdByte = buf[i + 2]
2390 fourthByte = buf[i + 3]
2391 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2392 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2393 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2394 codePoint = tempCodePoint
2395 }
2396 }
2397 }
2398 }
2399
2400 if (codePoint === null) {
2401 // we did not generate a valid codePoint so insert a
2402 // replacement char (U+FFFD) and advance only 1 byte
2403 codePoint = 0xFFFD
2404 bytesPerSequence = 1
2405 } else if (codePoint > 0xFFFF) {
2406 // encode to utf16 (surrogate pair dance)
2407 codePoint -= 0x10000
2408 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2409 codePoint = 0xDC00 | codePoint & 0x3FF
2410 }
2411
2412 res.push(codePoint)
2413 i += bytesPerSequence
2414 }
2415
2416 return decodeCodePointsArray(res)
2417}
2418
2419// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2420// the lowest limit is Chrome, with 0x10000 args.
2421// We go 1 magnitude less, for safety
2422var MAX_ARGUMENTS_LENGTH = 0x1000
2423
2424function decodeCodePointsArray (codePoints) {
2425 var len = codePoints.length
2426 if (len <= MAX_ARGUMENTS_LENGTH) {
2427 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2428 }
2429
2430 // Decode in chunks to avoid "call stack size exceeded".
2431 var res = ''
2432 var i = 0
2433 while (i < len) {
2434 res += String.fromCharCode.apply(
2435 String,
2436 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2437 )
2438 }
2439 return res
2440}
2441
2442function asciiSlice (buf, start, end) {
2443 var ret = ''
2444 end = Math.min(buf.length, end)
2445
2446 for (var i = start; i < end; ++i) {
2447 ret += String.fromCharCode(buf[i] & 0x7F)
2448 }
2449 return ret
2450}
2451
2452function latin1Slice (buf, start, end) {
2453 var ret = ''
2454 end = Math.min(buf.length, end)
2455
2456 for (var i = start; i < end; ++i) {
2457 ret += String.fromCharCode(buf[i])
2458 }
2459 return ret
2460}
2461
2462function hexSlice (buf, start, end) {
2463 var len = buf.length
2464
2465 if (!start || start < 0) start = 0
2466 if (!end || end < 0 || end > len) end = len
2467
2468 var out = ''
2469 for (var i = start; i < end; ++i) {
2470 out += hexSliceLookupTable[buf[i]]
2471 }
2472 return out
2473}
2474
2475function utf16leSlice (buf, start, end) {
2476 var bytes = buf.slice(start, end)
2477 var res = ''
2478 // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
2479 for (var i = 0; i < bytes.length - 1; i += 2) {
2480 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2481 }
2482 return res
2483}
2484
2485Buffer.prototype.slice = function slice (start, end) {
2486 var len = this.length
2487 start = ~~start
2488 end = end === undefined ? len : ~~end
2489
2490 if (start < 0) {
2491 start += len
2492 if (start < 0) start = 0
2493 } else if (start > len) {
2494 start = len
2495 }
2496
2497 if (end < 0) {
2498 end += len
2499 if (end < 0) end = 0
2500 } else if (end > len) {
2501 end = len
2502 }
2503
2504 if (end < start) end = start
2505
2506 var newBuf = this.subarray(start, end)
2507 // Return an augmented `Uint8Array` instance
2508 Object.setPrototypeOf(newBuf, Buffer.prototype)
2509
2510 return newBuf
2511}
2512
2513/*
2514 * Need to make sure that buffer isn't trying to write out of bounds.
2515 */
2516function checkOffset (offset, ext, length) {
2517 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2518 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2519}
2520
2521Buffer.prototype.readUintLE =
2522Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2523 offset = offset >>> 0
2524 byteLength = byteLength >>> 0
2525 if (!noAssert) checkOffset(offset, byteLength, this.length)
2526
2527 var val = this[offset]
2528 var mul = 1
2529 var i = 0
2530 while (++i < byteLength && (mul *= 0x100)) {
2531 val += this[offset + i] * mul
2532 }
2533
2534 return val
2535}
2536
2537Buffer.prototype.readUintBE =
2538Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2539 offset = offset >>> 0
2540 byteLength = byteLength >>> 0
2541 if (!noAssert) {
2542 checkOffset(offset, byteLength, this.length)
2543 }
2544
2545 var val = this[offset + --byteLength]
2546 var mul = 1
2547 while (byteLength > 0 && (mul *= 0x100)) {
2548 val += this[offset + --byteLength] * mul
2549 }
2550
2551 return val
2552}
2553
2554Buffer.prototype.readUint8 =
2555Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2556 offset = offset >>> 0
2557 if (!noAssert) checkOffset(offset, 1, this.length)
2558 return this[offset]
2559}
2560
2561Buffer.prototype.readUint16LE =
2562Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2563 offset = offset >>> 0
2564 if (!noAssert) checkOffset(offset, 2, this.length)
2565 return this[offset] | (this[offset + 1] << 8)
2566}
2567
2568Buffer.prototype.readUint16BE =
2569Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2570 offset = offset >>> 0
2571 if (!noAssert) checkOffset(offset, 2, this.length)
2572 return (this[offset] << 8) | this[offset + 1]
2573}
2574
2575Buffer.prototype.readUint32LE =
2576Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2577 offset = offset >>> 0
2578 if (!noAssert) checkOffset(offset, 4, this.length)
2579
2580 return ((this[offset]) |
2581 (this[offset + 1] << 8) |
2582 (this[offset + 2] << 16)) +
2583 (this[offset + 3] * 0x1000000)
2584}
2585
2586Buffer.prototype.readUint32BE =
2587Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2588 offset = offset >>> 0
2589 if (!noAssert) checkOffset(offset, 4, this.length)
2590
2591 return (this[offset] * 0x1000000) +
2592 ((this[offset + 1] << 16) |
2593 (this[offset + 2] << 8) |
2594 this[offset + 3])
2595}
2596
2597Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2598 offset = offset >>> 0
2599 byteLength = byteLength >>> 0
2600 if (!noAssert) checkOffset(offset, byteLength, this.length)
2601
2602 var val = this[offset]
2603 var mul = 1
2604 var i = 0
2605 while (++i < byteLength && (mul *= 0x100)) {
2606 val += this[offset + i] * mul
2607 }
2608 mul *= 0x80
2609
2610 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2611
2612 return val
2613}
2614
2615Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2616 offset = offset >>> 0
2617 byteLength = byteLength >>> 0
2618 if (!noAssert) checkOffset(offset, byteLength, this.length)
2619
2620 var i = byteLength
2621 var mul = 1
2622 var val = this[offset + --i]
2623 while (i > 0 && (mul *= 0x100)) {
2624 val += this[offset + --i] * mul
2625 }
2626 mul *= 0x80
2627
2628 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2629
2630 return val
2631}
2632
2633Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2634 offset = offset >>> 0
2635 if (!noAssert) checkOffset(offset, 1, this.length)
2636 if (!(this[offset] & 0x80)) return (this[offset])
2637 return ((0xff - this[offset] + 1) * -1)
2638}
2639
2640Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2641 offset = offset >>> 0
2642 if (!noAssert) checkOffset(offset, 2, this.length)
2643 var val = this[offset] | (this[offset + 1] << 8)
2644 return (val & 0x8000) ? val | 0xFFFF0000 : val
2645}
2646
2647Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2648 offset = offset >>> 0
2649 if (!noAssert) checkOffset(offset, 2, this.length)
2650 var val = this[offset + 1] | (this[offset] << 8)
2651 return (val & 0x8000) ? val | 0xFFFF0000 : val
2652}
2653
2654Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2655 offset = offset >>> 0
2656 if (!noAssert) checkOffset(offset, 4, this.length)
2657
2658 return (this[offset]) |
2659 (this[offset + 1] << 8) |
2660 (this[offset + 2] << 16) |
2661 (this[offset + 3] << 24)
2662}
2663
2664Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2665 offset = offset >>> 0
2666 if (!noAssert) checkOffset(offset, 4, this.length)
2667
2668 return (this[offset] << 24) |
2669 (this[offset + 1] << 16) |
2670 (this[offset + 2] << 8) |
2671 (this[offset + 3])
2672}
2673
2674Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2675 offset = offset >>> 0
2676 if (!noAssert) checkOffset(offset, 4, this.length)
2677 return ieee754.read(this, offset, true, 23, 4)
2678}
2679
2680Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
2681 offset = offset >>> 0
2682 if (!noAssert) checkOffset(offset, 4, this.length)
2683 return ieee754.read(this, offset, false, 23, 4)
2684}
2685
2686Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
2687 offset = offset >>> 0
2688 if (!noAssert) checkOffset(offset, 8, this.length)
2689 return ieee754.read(this, offset, true, 52, 8)
2690}
2691
2692Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
2693 offset = offset >>> 0
2694 if (!noAssert) checkOffset(offset, 8, this.length)
2695 return ieee754.read(this, offset, false, 52, 8)
2696}
2697
2698function checkInt (buf, value, offset, ext, max, min) {
2699 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
2700 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
2701 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2702}
2703
2704Buffer.prototype.writeUintLE =
2705Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
2706 value = +value
2707 offset = offset >>> 0
2708 byteLength = byteLength >>> 0
2709 if (!noAssert) {
2710 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2711 checkInt(this, value, offset, byteLength, maxBytes, 0)
2712 }
2713
2714 var mul = 1
2715 var i = 0
2716 this[offset] = value & 0xFF
2717 while (++i < byteLength && (mul *= 0x100)) {
2718 this[offset + i] = (value / mul) & 0xFF
2719 }
2720
2721 return offset + byteLength
2722}
2723
2724Buffer.prototype.writeUintBE =
2725Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2726 value = +value
2727 offset = offset >>> 0
2728 byteLength = byteLength >>> 0
2729 if (!noAssert) {
2730 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2731 checkInt(this, value, offset, byteLength, maxBytes, 0)
2732 }
2733
2734 var i = byteLength - 1
2735 var mul = 1
2736 this[offset + i] = value & 0xFF
2737 while (--i >= 0 && (mul *= 0x100)) {
2738 this[offset + i] = (value / mul) & 0xFF
2739 }
2740
2741 return offset + byteLength
2742}
2743
2744Buffer.prototype.writeUint8 =
2745Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
2746 value = +value
2747 offset = offset >>> 0
2748 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
2749 this[offset] = (value & 0xff)
2750 return offset + 1
2751}
2752
2753Buffer.prototype.writeUint16LE =
2754Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2755 value = +value
2756 offset = offset >>> 0
2757 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2758 this[offset] = (value & 0xff)
2759 this[offset + 1] = (value >>> 8)
2760 return offset + 2
2761}
2762
2763Buffer.prototype.writeUint16BE =
2764Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2765 value = +value
2766 offset = offset >>> 0
2767 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2768 this[offset] = (value >>> 8)
2769 this[offset + 1] = (value & 0xff)
2770 return offset + 2
2771}
2772
2773Buffer.prototype.writeUint32LE =
2774Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2775 value = +value
2776 offset = offset >>> 0
2777 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2778 this[offset + 3] = (value >>> 24)
2779 this[offset + 2] = (value >>> 16)
2780 this[offset + 1] = (value >>> 8)
2781 this[offset] = (value & 0xff)
2782 return offset + 4
2783}
2784
2785Buffer.prototype.writeUint32BE =
2786Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2787 value = +value
2788 offset = offset >>> 0
2789 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2790 this[offset] = (value >>> 24)
2791 this[offset + 1] = (value >>> 16)
2792 this[offset + 2] = (value >>> 8)
2793 this[offset + 3] = (value & 0xff)
2794 return offset + 4
2795}
2796
2797Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2798 value = +value
2799 offset = offset >>> 0
2800 if (!noAssert) {
2801 var limit = Math.pow(2, (8 * byteLength) - 1)
2802
2803 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2804 }
2805
2806 var i = 0
2807 var mul = 1
2808 var sub = 0
2809 this[offset] = value & 0xFF
2810 while (++i < byteLength && (mul *= 0x100)) {
2811 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2812 sub = 1
2813 }
2814 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2815 }
2816
2817 return offset + byteLength
2818}
2819
2820Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2821 value = +value
2822 offset = offset >>> 0
2823 if (!noAssert) {
2824 var limit = Math.pow(2, (8 * byteLength) - 1)
2825
2826 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2827 }
2828
2829 var i = byteLength - 1
2830 var mul = 1
2831 var sub = 0
2832 this[offset + i] = value & 0xFF
2833 while (--i >= 0 && (mul *= 0x100)) {
2834 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2835 sub = 1
2836 }
2837 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2838 }
2839
2840 return offset + byteLength
2841}
2842
2843Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2844 value = +value
2845 offset = offset >>> 0
2846 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2847 if (value < 0) value = 0xff + value + 1
2848 this[offset] = (value & 0xff)
2849 return offset + 1
2850}
2851
2852Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2853 value = +value
2854 offset = offset >>> 0
2855 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2856 this[offset] = (value & 0xff)
2857 this[offset + 1] = (value >>> 8)
2858 return offset + 2
2859}
2860
2861Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2862 value = +value
2863 offset = offset >>> 0
2864 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2865 this[offset] = (value >>> 8)
2866 this[offset + 1] = (value & 0xff)
2867 return offset + 2
2868}
2869
2870Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2871 value = +value
2872 offset = offset >>> 0
2873 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2874 this[offset] = (value & 0xff)
2875 this[offset + 1] = (value >>> 8)
2876 this[offset + 2] = (value >>> 16)
2877 this[offset + 3] = (value >>> 24)
2878 return offset + 4
2879}
2880
2881Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2882 value = +value
2883 offset = offset >>> 0
2884 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2885 if (value < 0) value = 0xffffffff + value + 1
2886 this[offset] = (value >>> 24)
2887 this[offset + 1] = (value >>> 16)
2888 this[offset + 2] = (value >>> 8)
2889 this[offset + 3] = (value & 0xff)
2890 return offset + 4
2891}
2892
2893function checkIEEE754 (buf, value, offset, ext, max, min) {
2894 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2895 if (offset < 0) throw new RangeError('Index out of range')
2896}
2897
2898function writeFloat (buf, value, offset, littleEndian, noAssert) {
2899 value = +value
2900 offset = offset >>> 0
2901 if (!noAssert) {
2902 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2903 }
2904 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2905 return offset + 4
2906}
2907
2908Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2909 return writeFloat(this, value, offset, true, noAssert)
2910}
2911
2912Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2913 return writeFloat(this, value, offset, false, noAssert)
2914}
2915
2916function writeDouble (buf, value, offset, littleEndian, noAssert) {
2917 value = +value
2918 offset = offset >>> 0
2919 if (!noAssert) {
2920 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2921 }
2922 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2923 return offset + 8
2924}
2925
2926Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2927 return writeDouble(this, value, offset, true, noAssert)
2928}
2929
2930Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2931 return writeDouble(this, value, offset, false, noAssert)
2932}
2933
2934// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2935Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2936 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
2937 if (!start) start = 0
2938 if (!end && end !== 0) end = this.length
2939 if (targetStart >= target.length) targetStart = target.length
2940 if (!targetStart) targetStart = 0
2941 if (end > 0 && end < start) end = start
2942
2943 // Copy 0 bytes; we're done
2944 if (end === start) return 0
2945 if (target.length === 0 || this.length === 0) return 0
2946
2947 // Fatal error conditions
2948 if (targetStart < 0) {
2949 throw new RangeError('targetStart out of bounds')
2950 }
2951 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
2952 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2953
2954 // Are we oob?
2955 if (end > this.length) end = this.length
2956 if (target.length - targetStart < end - start) {
2957 end = target.length - targetStart + start
2958 }
2959
2960 var len = end - start
2961
2962 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
2963 // Use built-in when available, missing from IE11
2964 this.copyWithin(targetStart, start, end)
2965 } else {
2966 Uint8Array.prototype.set.call(
2967 target,
2968 this.subarray(start, end),
2969 targetStart
2970 )
2971 }
2972
2973 return len
2974}
2975
2976// Usage:
2977// buffer.fill(number[, offset[, end]])
2978// buffer.fill(buffer[, offset[, end]])
2979// buffer.fill(string[, offset[, end]][, encoding])
2980Buffer.prototype.fill = function fill (val, start, end, encoding) {
2981 // Handle string cases:
2982 if (typeof val === 'string') {
2983 if (typeof start === 'string') {
2984 encoding = start
2985 start = 0
2986 end = this.length
2987 } else if (typeof end === 'string') {
2988 encoding = end
2989 end = this.length
2990 }
2991 if (encoding !== undefined && typeof encoding !== 'string') {
2992 throw new TypeError('encoding must be a string')
2993 }
2994 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2995 throw new TypeError('Unknown encoding: ' + encoding)
2996 }
2997 if (val.length === 1) {
2998 var code = val.charCodeAt(0)
2999 if ((encoding === 'utf8' && code < 128) ||
3000 encoding === 'latin1') {
3001 // Fast path: If `val` fits into a single byte, use that numeric value.
3002 val = code
3003 }
3004 }
3005 } else if (typeof val === 'number') {
3006 val = val & 255
3007 } else if (typeof val === 'boolean') {
3008 val = Number(val)
3009 }
3010
3011 // Invalid ranges are not set to a default, so can range check early.
3012 if (start < 0 || this.length < start || this.length < end) {
3013 throw new RangeError('Out of range index')
3014 }
3015
3016 if (end <= start) {
3017 return this
3018 }
3019
3020 start = start >>> 0
3021 end = end === undefined ? this.length : end >>> 0
3022
3023 if (!val) val = 0
3024
3025 var i
3026 if (typeof val === 'number') {
3027 for (i = start; i < end; ++i) {
3028 this[i] = val
3029 }
3030 } else {
3031 var bytes = Buffer.isBuffer(val)
3032 ? val
3033 : Buffer.from(val, encoding)
3034 var len = bytes.length
3035 if (len === 0) {
3036 throw new TypeError('The value "' + val +
3037 '" is invalid for argument "value"')
3038 }
3039 for (i = 0; i < end - start; ++i) {
3040 this[i + start] = bytes[i % len]
3041 }
3042 }
3043
3044 return this
3045}
3046
3047// HELPER FUNCTIONS
3048// ================
3049
3050var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3051
3052function base64clean (str) {
3053 // Node takes equal signs as end of the Base64 encoding
3054 str = str.split('=')[0]
3055 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3056 str = str.trim().replace(INVALID_BASE64_RE, '')
3057 // Node converts strings with length < 2 to ''
3058 if (str.length < 2) return ''
3059 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3060 while (str.length % 4 !== 0) {
3061 str = str + '='
3062 }
3063 return str
3064}
3065
3066function utf8ToBytes (string, units) {
3067 units = units || Infinity
3068 var codePoint
3069 var length = string.length
3070 var leadSurrogate = null
3071 var bytes = []
3072
3073 for (var i = 0; i < length; ++i) {
3074 codePoint = string.charCodeAt(i)
3075
3076 // is surrogate component
3077 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3078 // last char was a lead
3079 if (!leadSurrogate) {
3080 // no lead yet
3081 if (codePoint > 0xDBFF) {
3082 // unexpected trail
3083 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3084 continue
3085 } else if (i + 1 === length) {
3086 // unpaired lead
3087 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3088 continue
3089 }
3090
3091 // valid lead
3092 leadSurrogate = codePoint
3093
3094 continue
3095 }
3096
3097 // 2 leads in a row
3098 if (codePoint < 0xDC00) {
3099 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3100 leadSurrogate = codePoint
3101 continue
3102 }
3103
3104 // valid surrogate pair
3105 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3106 } else if (leadSurrogate) {
3107 // valid bmp char, but last char was a lead
3108 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3109 }
3110
3111 leadSurrogate = null
3112
3113 // encode utf8
3114 if (codePoint < 0x80) {
3115 if ((units -= 1) < 0) break
3116 bytes.push(codePoint)
3117 } else if (codePoint < 0x800) {
3118 if ((units -= 2) < 0) break
3119 bytes.push(
3120 codePoint >> 0x6 | 0xC0,
3121 codePoint & 0x3F | 0x80
3122 )
3123 } else if (codePoint < 0x10000) {
3124 if ((units -= 3) < 0) break
3125 bytes.push(
3126 codePoint >> 0xC | 0xE0,
3127 codePoint >> 0x6 & 0x3F | 0x80,
3128 codePoint & 0x3F | 0x80
3129 )
3130 } else if (codePoint < 0x110000) {
3131 if ((units -= 4) < 0) break
3132 bytes.push(
3133 codePoint >> 0x12 | 0xF0,
3134 codePoint >> 0xC & 0x3F | 0x80,
3135 codePoint >> 0x6 & 0x3F | 0x80,
3136 codePoint & 0x3F | 0x80
3137 )
3138 } else {
3139 throw new Error('Invalid code point')
3140 }
3141 }
3142
3143 return bytes
3144}
3145
3146function asciiToBytes (str) {
3147 var byteArray = []
3148 for (var i = 0; i < str.length; ++i) {
3149 // Node's code seems to be doing this and not & 0x7F..
3150 byteArray.push(str.charCodeAt(i) & 0xFF)
3151 }
3152 return byteArray
3153}
3154
3155function utf16leToBytes (str, units) {
3156 var c, hi, lo
3157 var byteArray = []
3158 for (var i = 0; i < str.length; ++i) {
3159 if ((units -= 2) < 0) break
3160
3161 c = str.charCodeAt(i)
3162 hi = c >> 8
3163 lo = c % 256
3164 byteArray.push(lo)
3165 byteArray.push(hi)
3166 }
3167
3168 return byteArray
3169}
3170
3171function base64ToBytes (str) {
3172 return base64.toByteArray(base64clean(str))
3173}
3174
3175function blitBuffer (src, dst, offset, length) {
3176 for (var i = 0; i < length; ++i) {
3177 if ((i + offset >= dst.length) || (i >= src.length)) break
3178 dst[i + offset] = src[i]
3179 }
3180 return i
3181}
3182
3183// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
3184// the `instanceof` check but they should be treated as of that type.
3185// See: https://github.com/feross/buffer/issues/166
3186function isInstance (obj, type) {
3187 return obj instanceof type ||
3188 (obj != null && obj.constructor != null && obj.constructor.name != null &&
3189 obj.constructor.name === type.name)
3190}
3191function numberIsNaN (obj) {
3192 // For IE11 support
3193 return obj !== obj // eslint-disable-line no-self-compare
3194}
3195
3196// Create lookup table for `toString('hex')`
3197// See: https://github.com/feross/buffer/issues/219
3198var hexSliceLookupTable = (function () {
3199 var alphabet = '0123456789abcdef'
3200 var table = new Array(256)
3201 for (var i = 0; i < 16; ++i) {
3202 var i16 = i * 16
3203 for (var j = 0; j < 16; ++j) {
3204 table[i16 + j] = alphabet[i] + alphabet[j]
3205 }
3206 }
3207 return table
3208})()
3209
3210}).call(this)}).call(this,_dereq_(9).Buffer)
3211},{"23":23,"6":6,"9":9}],10:[function(_dereq_,module,exports){
3212// Copyright Joyent, Inc. and other Node contributors.
3213//
3214// Permission is hereby granted, free of charge, to any person obtaining a
3215// copy of this software and associated documentation files (the
3216// "Software"), to deal in the Software without restriction, including
3217// without limitation the rights to use, copy, modify, merge, publish,
3218// distribute, sublicense, and/or sell copies of the Software, and to permit
3219// persons to whom the Software is furnished to do so, subject to the
3220// following conditions:
3221//
3222// The above copyright notice and this permission notice shall be included
3223// in all copies or substantial portions of the Software.
3224//
3225// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3226// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3227// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3228// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3229// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3230// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3231// USE OR OTHER DEALINGS IN THE SOFTWARE.
3232
3233// NOTE: These type checking functions intentionally don't use `instanceof`
3234// because it is fragile and can be easily faked with `Object.create()`.
3235
3236function isArray(arg) {
3237 if (Array.isArray) {
3238 return Array.isArray(arg);
3239 }
3240 return objectToString(arg) === '[object Array]';
3241}
3242exports.isArray = isArray;
3243
3244function isBoolean(arg) {
3245 return typeof arg === 'boolean';
3246}
3247exports.isBoolean = isBoolean;
3248
3249function isNull(arg) {
3250 return arg === null;
3251}
3252exports.isNull = isNull;
3253
3254function isNullOrUndefined(arg) {
3255 return arg == null;
3256}
3257exports.isNullOrUndefined = isNullOrUndefined;
3258
3259function isNumber(arg) {
3260 return typeof arg === 'number';
3261}
3262exports.isNumber = isNumber;
3263
3264function isString(arg) {
3265 return typeof arg === 'string';
3266}
3267exports.isString = isString;
3268
3269function isSymbol(arg) {
3270 return typeof arg === 'symbol';
3271}
3272exports.isSymbol = isSymbol;
3273
3274function isUndefined(arg) {
3275 return arg === void 0;
3276}
3277exports.isUndefined = isUndefined;
3278
3279function isRegExp(re) {
3280 return objectToString(re) === '[object RegExp]';
3281}
3282exports.isRegExp = isRegExp;
3283
3284function isObject(arg) {
3285 return typeof arg === 'object' && arg !== null;
3286}
3287exports.isObject = isObject;
3288
3289function isDate(d) {
3290 return objectToString(d) === '[object Date]';
3291}
3292exports.isDate = isDate;
3293
3294function isError(e) {
3295 return (objectToString(e) === '[object Error]' || e instanceof Error);
3296}
3297exports.isError = isError;
3298
3299function isFunction(arg) {
3300 return typeof arg === 'function';
3301}
3302exports.isFunction = isFunction;
3303
3304function isPrimitive(arg) {
3305 return arg === null ||
3306 typeof arg === 'boolean' ||
3307 typeof arg === 'number' ||
3308 typeof arg === 'string' ||
3309 typeof arg === 'symbol' || // ES6 symbol
3310 typeof arg === 'undefined';
3311}
3312exports.isPrimitive = isPrimitive;
3313
3314exports.isBuffer = _dereq_(9).Buffer.isBuffer;
3315
3316function objectToString(o) {
3317 return Object.prototype.toString.call(o);
3318}
3319
3320},{"9":9}],11:[function(_dereq_,module,exports){
3321var AbstractIterator = _dereq_(16).AbstractIterator
3322var inherits = _dereq_(30)
3323
3324function DeferredIterator (db, options) {
3325 AbstractIterator.call(this, db)
3326
3327 this._options = options
3328 this._iterator = null
3329 this._operations = []
3330}
3331
3332inherits(DeferredIterator, AbstractIterator)
3333
3334DeferredIterator.prototype.setDb = function (db) {
3335 var it = this._iterator = db.iterator(this._options)
3336 this._operations.forEach(function (op) {
3337 it[op.method].apply(it, op.args)
3338 })
3339}
3340
3341DeferredIterator.prototype._operation = function (method, args) {
3342 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
3343 this._operations.push({ method: method, args: args })
3344}
3345
3346'next end'.split(' ').forEach(function (m) {
3347 DeferredIterator.prototype['_' + m] = function () {
3348 this._operation(m, arguments)
3349 }
3350})
3351
3352// Must defer seek() rather than _seek() because it requires db._serializeKey to be available
3353DeferredIterator.prototype.seek = function () {
3354 this._operation('seek', arguments)
3355}
3356
3357module.exports = DeferredIterator
3358
3359},{"16":16,"30":30}],12:[function(_dereq_,module,exports){
3360var AbstractLevelDOWN = _dereq_(16).AbstractLevelDOWN
3361var inherits = _dereq_(30)
3362var DeferredIterator = _dereq_(11)
3363var deferrables = 'put get del batch clear'.split(' ')
3364var optionalDeferrables = 'approximateSize compactRange'.split(' ')
3365
3366function DeferredLevelDOWN (db) {
3367 AbstractLevelDOWN.call(this, db.supports || {})
3368
3369 // TODO (future major): remove this fallback; db must have manifest that
3370 // declares approximateSize and compactRange in additionalMethods.
3371 optionalDeferrables.forEach(function (m) {
3372 if (typeof db[m] === 'function' && !this.supports.additionalMethods[m]) {
3373 this.supports.additionalMethods[m] = true
3374 }
3375 }, this)
3376
3377 this._db = db
3378 this._operations = []
3379 closed(this)
3380}
3381
3382inherits(DeferredLevelDOWN, AbstractLevelDOWN)
3383
3384DeferredLevelDOWN.prototype.type = 'deferred-leveldown'
3385
3386DeferredLevelDOWN.prototype._open = function (options, callback) {
3387 var self = this
3388
3389 this._db.open(options, function (err) {
3390 if (err) return callback(err)
3391
3392 self._operations.forEach(function (op) {
3393 if (op.iterator) {
3394 op.iterator.setDb(self._db)
3395 } else {
3396 self._db[op.method].apply(self._db, op.args)
3397 }
3398 })
3399 self._operations = []
3400
3401 open(self)
3402 callback()
3403 })
3404}
3405
3406DeferredLevelDOWN.prototype._close = function (callback) {
3407 var self = this
3408
3409 this._db.close(function (err) {
3410 if (err) return callback(err)
3411 closed(self)
3412 callback()
3413 })
3414}
3415
3416function open (self) {
3417 deferrables.concat('iterator').forEach(function (m) {
3418 self['_' + m] = function () {
3419 return this._db[m].apply(this._db, arguments)
3420 }
3421 })
3422 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3423 self[m] = function () {
3424 return this._db[m].apply(this._db, arguments)
3425 }
3426 })
3427}
3428
3429function closed (self) {
3430 deferrables.forEach(function (m) {
3431 self['_' + m] = function () {
3432 this._operations.push({ method: m, args: arguments })
3433 }
3434 })
3435 Object.keys(self.supports.additionalMethods).forEach(function (m) {
3436 self[m] = function () {
3437 this._operations.push({ method: m, args: arguments })
3438 }
3439 })
3440 self._iterator = function (options) {
3441 var it = new DeferredIterator(self, options)
3442 this._operations.push({ iterator: it })
3443 return it
3444 }
3445}
3446
3447DeferredLevelDOWN.prototype._serializeKey = function (key) {
3448 return key
3449}
3450
3451DeferredLevelDOWN.prototype._serializeValue = function (value) {
3452 return value
3453}
3454
3455module.exports = DeferredLevelDOWN
3456module.exports.DeferredIterator = DeferredIterator
3457
3458},{"11":11,"16":16,"30":30}],13:[function(_dereq_,module,exports){
3459var nextTick = _dereq_(17)
3460
3461function AbstractChainedBatch (db) {
3462 if (typeof db !== 'object' || db === null) {
3463 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3464 }
3465
3466 this.db = db
3467 this._operations = []
3468 this._written = false
3469}
3470
3471AbstractChainedBatch.prototype._checkWritten = function () {
3472 if (this._written) {
3473 throw new Error('write() already called on this batch')
3474 }
3475}
3476
3477AbstractChainedBatch.prototype.put = function (key, value) {
3478 this._checkWritten()
3479
3480 var err = this.db._checkKey(key) || this.db._checkValue(value)
3481 if (err) throw err
3482
3483 key = this.db._serializeKey(key)
3484 value = this.db._serializeValue(value)
3485
3486 this._put(key, value)
3487
3488 return this
3489}
3490
3491AbstractChainedBatch.prototype._put = function (key, value) {
3492 this._operations.push({ type: 'put', key: key, value: value })
3493}
3494
3495AbstractChainedBatch.prototype.del = function (key) {
3496 this._checkWritten()
3497
3498 var err = this.db._checkKey(key)
3499 if (err) throw err
3500
3501 key = this.db._serializeKey(key)
3502 this._del(key)
3503
3504 return this
3505}
3506
3507AbstractChainedBatch.prototype._del = function (key) {
3508 this._operations.push({ type: 'del', key: key })
3509}
3510
3511AbstractChainedBatch.prototype.clear = function () {
3512 this._checkWritten()
3513 this._clear()
3514
3515 return this
3516}
3517
3518AbstractChainedBatch.prototype._clear = function () {
3519 this._operations = []
3520}
3521
3522AbstractChainedBatch.prototype.write = function (options, callback) {
3523 this._checkWritten()
3524
3525 if (typeof options === 'function') { callback = options }
3526 if (typeof callback !== 'function') {
3527 throw new Error('write() requires a callback argument')
3528 }
3529 if (typeof options !== 'object' || options === null) {
3530 options = {}
3531 }
3532
3533 this._written = true
3534 this._write(options, callback)
3535}
3536
3537AbstractChainedBatch.prototype._write = function (options, callback) {
3538 this.db._batch(this._operations, options, callback)
3539}
3540
3541// Expose browser-compatible nextTick for dependents
3542AbstractChainedBatch.prototype._nextTick = nextTick
3543
3544module.exports = AbstractChainedBatch
3545
3546},{"17":17}],14:[function(_dereq_,module,exports){
3547var nextTick = _dereq_(17)
3548
3549function AbstractIterator (db) {
3550 if (typeof db !== 'object' || db === null) {
3551 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3552 }
3553
3554 this.db = db
3555 this._ended = false
3556 this._nexting = false
3557}
3558
3559AbstractIterator.prototype.next = function (callback) {
3560 var self = this
3561
3562 if (typeof callback !== 'function') {
3563 throw new Error('next() requires a callback argument')
3564 }
3565
3566 if (self._ended) {
3567 nextTick(callback, new Error('cannot call next() after end()'))
3568 return self
3569 }
3570
3571 if (self._nexting) {
3572 nextTick(callback, new Error('cannot call next() before previous next() has completed'))
3573 return self
3574 }
3575
3576 self._nexting = true
3577 self._next(function () {
3578 self._nexting = false
3579 callback.apply(null, arguments)
3580 })
3581
3582 return self
3583}
3584
3585AbstractIterator.prototype._next = function (callback) {
3586 nextTick(callback)
3587}
3588
3589AbstractIterator.prototype.seek = function (target) {
3590 if (this._ended) {
3591 throw new Error('cannot call seek() after end()')
3592 }
3593 if (this._nexting) {
3594 throw new Error('cannot call seek() before next() has completed')
3595 }
3596
3597 target = this.db._serializeKey(target)
3598 this._seek(target)
3599}
3600
3601AbstractIterator.prototype._seek = function (target) {}
3602
3603AbstractIterator.prototype.end = function (callback) {
3604 if (typeof callback !== 'function') {
3605 throw new Error('end() requires a callback argument')
3606 }
3607
3608 if (this._ended) {
3609 return nextTick(callback, new Error('end() already called on iterator'))
3610 }
3611
3612 this._ended = true
3613 this._end(callback)
3614}
3615
3616AbstractIterator.prototype._end = function (callback) {
3617 nextTick(callback)
3618}
3619
3620// Expose browser-compatible nextTick for dependents
3621AbstractIterator.prototype._nextTick = nextTick
3622
3623module.exports = AbstractIterator
3624
3625},{"17":17}],15:[function(_dereq_,module,exports){
3626var xtend = _dereq_(134)
3627var supports = _dereq_(51)
3628var Buffer = _dereq_(9).Buffer
3629var AbstractIterator = _dereq_(14)
3630var AbstractChainedBatch = _dereq_(13)
3631var nextTick = _dereq_(17)
3632var hasOwnProperty = Object.prototype.hasOwnProperty
3633var rangeOptions = 'start end gt gte lt lte'.split(' ')
3634
3635function AbstractLevelDOWN (manifest) {
3636 this.status = 'new'
3637
3638 // TODO (next major): make this mandatory
3639 this.supports = supports(manifest, {
3640 status: true
3641 })
3642}
3643
3644AbstractLevelDOWN.prototype.open = function (options, callback) {
3645 var self = this
3646 var oldStatus = this.status
3647
3648 if (typeof options === 'function') callback = options
3649
3650 if (typeof callback !== 'function') {
3651 throw new Error('open() requires a callback argument')
3652 }
3653
3654 if (typeof options !== 'object' || options === null) options = {}
3655
3656 options.createIfMissing = options.createIfMissing !== false
3657 options.errorIfExists = !!options.errorIfExists
3658
3659 this.status = 'opening'
3660 this._open(options, function (err) {
3661 if (err) {
3662 self.status = oldStatus
3663 return callback(err)
3664 }
3665 self.status = 'open'
3666 callback()
3667 })
3668}
3669
3670AbstractLevelDOWN.prototype._open = function (options, callback) {
3671 nextTick(callback)
3672}
3673
3674AbstractLevelDOWN.prototype.close = function (callback) {
3675 var self = this
3676 var oldStatus = this.status
3677
3678 if (typeof callback !== 'function') {
3679 throw new Error('close() requires a callback argument')
3680 }
3681
3682 this.status = 'closing'
3683 this._close(function (err) {
3684 if (err) {
3685 self.status = oldStatus
3686 return callback(err)
3687 }
3688 self.status = 'closed'
3689 callback()
3690 })
3691}
3692
3693AbstractLevelDOWN.prototype._close = function (callback) {
3694 nextTick(callback)
3695}
3696
3697AbstractLevelDOWN.prototype.get = function (key, options, callback) {
3698 if (typeof options === 'function') callback = options
3699
3700 if (typeof callback !== 'function') {
3701 throw new Error('get() requires a callback argument')
3702 }
3703
3704 var err = this._checkKey(key)
3705 if (err) return nextTick(callback, err)
3706
3707 key = this._serializeKey(key)
3708
3709 if (typeof options !== 'object' || options === null) options = {}
3710
3711 options.asBuffer = options.asBuffer !== false
3712
3713 this._get(key, options, callback)
3714}
3715
3716AbstractLevelDOWN.prototype._get = function (key, options, callback) {
3717 nextTick(function () { callback(new Error('NotFound')) })
3718}
3719
3720AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
3721 if (typeof options === 'function') callback = options
3722
3723 if (typeof callback !== 'function') {
3724 throw new Error('put() requires a callback argument')
3725 }
3726
3727 var err = this._checkKey(key) || this._checkValue(value)
3728 if (err) return nextTick(callback, err)
3729
3730 key = this._serializeKey(key)
3731 value = this._serializeValue(value)
3732
3733 if (typeof options !== 'object' || options === null) options = {}
3734
3735 this._put(key, value, options, callback)
3736}
3737
3738AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
3739 nextTick(callback)
3740}
3741
3742AbstractLevelDOWN.prototype.del = function (key, options, callback) {
3743 if (typeof options === 'function') callback = options
3744
3745 if (typeof callback !== 'function') {
3746 throw new Error('del() requires a callback argument')
3747 }
3748
3749 var err = this._checkKey(key)
3750 if (err) return nextTick(callback, err)
3751
3752 key = this._serializeKey(key)
3753
3754 if (typeof options !== 'object' || options === null) options = {}
3755
3756 this._del(key, options, callback)
3757}
3758
3759AbstractLevelDOWN.prototype._del = function (key, options, callback) {
3760 nextTick(callback)
3761}
3762
3763AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
3764 if (!arguments.length) return this._chainedBatch()
3765
3766 if (typeof options === 'function') callback = options
3767
3768 if (typeof array === 'function') callback = array
3769
3770 if (typeof callback !== 'function') {
3771 throw new Error('batch(array) requires a callback argument')
3772 }
3773
3774 if (!Array.isArray(array)) {
3775 return nextTick(callback, new Error('batch(array) requires an array argument'))
3776 }
3777
3778 if (array.length === 0) {
3779 return nextTick(callback)
3780 }
3781
3782 if (typeof options !== 'object' || options === null) options = {}
3783
3784 var serialized = new Array(array.length)
3785
3786 for (var i = 0; i < array.length; i++) {
3787 if (typeof array[i] !== 'object' || array[i] === null) {
3788 return nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
3789 }
3790
3791 var e = xtend(array[i])
3792
3793 if (e.type !== 'put' && e.type !== 'del') {
3794 return nextTick(callback, new Error("`type` must be 'put' or 'del'"))
3795 }
3796
3797 var err = this._checkKey(e.key)
3798 if (err) return nextTick(callback, err)
3799
3800 e.key = this._serializeKey(e.key)
3801
3802 if (e.type === 'put') {
3803 var valueErr = this._checkValue(e.value)
3804 if (valueErr) return nextTick(callback, valueErr)
3805
3806 e.value = this._serializeValue(e.value)
3807 }
3808
3809 serialized[i] = e
3810 }
3811
3812 this._batch(serialized, options, callback)
3813}
3814
3815AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
3816 nextTick(callback)
3817}
3818
3819AbstractLevelDOWN.prototype.clear = function (options, callback) {
3820 if (typeof options === 'function') {
3821 callback = options
3822 } else if (typeof callback !== 'function') {
3823 throw new Error('clear() requires a callback argument')
3824 }
3825
3826 options = cleanRangeOptions(this, options)
3827 options.reverse = !!options.reverse
3828 options.limit = 'limit' in options ? options.limit : -1
3829
3830 this._clear(options, callback)
3831}
3832
3833AbstractLevelDOWN.prototype._clear = function (options, callback) {
3834 // Avoid setupIteratorOptions, would serialize range options a second time.
3835 options.keys = true
3836 options.values = false
3837 options.keyAsBuffer = true
3838 options.valueAsBuffer = true
3839
3840 var iterator = this._iterator(options)
3841 var emptyOptions = {}
3842 var self = this
3843
3844 var next = function (err) {
3845 if (err) {
3846 return iterator.end(function () {
3847 callback(err)
3848 })
3849 }
3850
3851 iterator.next(function (err, key) {
3852 if (err) return next(err)
3853 if (key === undefined) return iterator.end(callback)
3854
3855 // This could be optimized by using a batch, but the default _clear
3856 // is not meant to be fast. Implementations have more room to optimize
3857 // if they override _clear. Note: using _del bypasses key serialization.
3858 self._del(key, emptyOptions, next)
3859 })
3860 }
3861
3862 next()
3863}
3864
3865AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
3866 options = cleanRangeOptions(this, options)
3867
3868 options.reverse = !!options.reverse
3869 options.keys = options.keys !== false
3870 options.values = options.values !== false
3871 options.limit = 'limit' in options ? options.limit : -1
3872 options.keyAsBuffer = options.keyAsBuffer !== false
3873 options.valueAsBuffer = options.valueAsBuffer !== false
3874
3875 return options
3876}
3877
3878function cleanRangeOptions (db, options) {
3879 var result = {}
3880
3881 for (var k in options) {
3882 if (!hasOwnProperty.call(options, k)) continue
3883
3884 var opt = options[k]
3885
3886 if (isRangeOption(k)) {
3887 // Note that we don't reject nullish and empty options here. While
3888 // those types are invalid as keys, they are valid as range options.
3889 opt = db._serializeKey(opt)
3890 }
3891
3892 result[k] = opt
3893 }
3894
3895 return result
3896}
3897
3898function isRangeOption (k) {
3899 return rangeOptions.indexOf(k) !== -1
3900}
3901
3902AbstractLevelDOWN.prototype.iterator = function (options) {
3903 if (typeof options !== 'object' || options === null) options = {}
3904 options = this._setupIteratorOptions(options)
3905 return this._iterator(options)
3906}
3907
3908AbstractLevelDOWN.prototype._iterator = function (options) {
3909 return new AbstractIterator(this)
3910}
3911
3912AbstractLevelDOWN.prototype._chainedBatch = function () {
3913 return new AbstractChainedBatch(this)
3914}
3915
3916AbstractLevelDOWN.prototype._serializeKey = function (key) {
3917 return key
3918}
3919
3920AbstractLevelDOWN.prototype._serializeValue = function (value) {
3921 return value
3922}
3923
3924AbstractLevelDOWN.prototype._checkKey = function (key) {
3925 if (key === null || key === undefined) {
3926 return new Error('key cannot be `null` or `undefined`')
3927 } else if (Buffer.isBuffer(key) && key.length === 0) {
3928 return new Error('key cannot be an empty Buffer')
3929 } else if (key === '') {
3930 return new Error('key cannot be an empty String')
3931 } else if (Array.isArray(key) && key.length === 0) {
3932 return new Error('key cannot be an empty Array')
3933 }
3934}
3935
3936AbstractLevelDOWN.prototype._checkValue = function (value) {
3937 if (value === null || value === undefined) {
3938 return new Error('value cannot be `null` or `undefined`')
3939 }
3940}
3941
3942// Expose browser-compatible nextTick for dependents
3943AbstractLevelDOWN.prototype._nextTick = nextTick
3944
3945module.exports = AbstractLevelDOWN
3946
3947},{"13":13,"134":134,"14":14,"17":17,"51":51,"9":9}],16:[function(_dereq_,module,exports){
3948exports.AbstractLevelDOWN = _dereq_(15)
3949exports.AbstractIterator = _dereq_(14)
3950exports.AbstractChainedBatch = _dereq_(13)
3951
3952},{"13":13,"14":14,"15":15}],17:[function(_dereq_,module,exports){
3953module.exports = _dereq_(24)
3954
3955},{"24":24}],18:[function(_dereq_,module,exports){
3956/**
3957 * Copyright (c) 2013 Petka Antonov
3958 *
3959 * Permission is hereby granted, free of charge, to any person obtaining a copy
3960 * of this software and associated documentation files (the "Software"), to deal
3961 * in the Software without restriction, including without limitation the rights
3962 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3963 * copies of the Software, and to permit persons to whom the Software is
3964 * furnished to do so, subject to the following conditions:</p>
3965 *
3966 * The above copyright notice and this permission notice shall be included in
3967 * all copies or substantial portions of the Software.
3968 *
3969 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3970 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3971 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3972 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3973 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3974 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3975 * THE SOFTWARE.
3976 */
3977"use strict";
3978function Deque(capacity) {
3979 this._capacity = getCapacity(capacity);
3980 this._length = 0;
3981 this._front = 0;
3982 if (isArray(capacity)) {
3983 var len = capacity.length;
3984 for (var i = 0; i < len; ++i) {
3985 this[i] = capacity[i];
3986 }
3987 this._length = len;
3988 }
3989}
3990
3991Deque.prototype.toArray = function Deque$toArray() {
3992 var len = this._length;
3993 var ret = new Array(len);
3994 var front = this._front;
3995 var capacity = this._capacity;
3996 for (var j = 0; j < len; ++j) {
3997 ret[j] = this[(front + j) & (capacity - 1)];
3998 }
3999 return ret;
4000};
4001
4002Deque.prototype.push = function Deque$push(item) {
4003 var argsLength = arguments.length;
4004 var length = this._length;
4005 if (argsLength > 1) {
4006 var capacity = this._capacity;
4007 if (length + argsLength > capacity) {
4008 for (var i = 0; i < argsLength; ++i) {
4009 this._checkCapacity(length + 1);
4010 var j = (this._front + length) & (this._capacity - 1);
4011 this[j] = arguments[i];
4012 length++;
4013 this._length = length;
4014 }
4015 return length;
4016 }
4017 else {
4018 var j = this._front;
4019 for (var i = 0; i < argsLength; ++i) {
4020 this[(j + length) & (capacity - 1)] = arguments[i];
4021 j++;
4022 }
4023 this._length = length + argsLength;
4024 return length + argsLength;
4025 }
4026
4027 }
4028
4029 if (argsLength === 0) return length;
4030
4031 this._checkCapacity(length + 1);
4032 var i = (this._front + length) & (this._capacity - 1);
4033 this[i] = item;
4034 this._length = length + 1;
4035 return length + 1;
4036};
4037
4038Deque.prototype.pop = function Deque$pop() {
4039 var length = this._length;
4040 if (length === 0) {
4041 return void 0;
4042 }
4043 var i = (this._front + length - 1) & (this._capacity - 1);
4044 var ret = this[i];
4045 this[i] = void 0;
4046 this._length = length - 1;
4047 return ret;
4048};
4049
4050Deque.prototype.shift = function Deque$shift() {
4051 var length = this._length;
4052 if (length === 0) {
4053 return void 0;
4054 }
4055 var front = this._front;
4056 var ret = this[front];
4057 this[front] = void 0;
4058 this._front = (front + 1) & (this._capacity - 1);
4059 this._length = length - 1;
4060 return ret;
4061};
4062
4063Deque.prototype.unshift = function Deque$unshift(item) {
4064 var length = this._length;
4065 var argsLength = arguments.length;
4066
4067
4068 if (argsLength > 1) {
4069 var capacity = this._capacity;
4070 if (length + argsLength > capacity) {
4071 for (var i = argsLength - 1; i >= 0; i--) {
4072 this._checkCapacity(length + 1);
4073 var capacity = this._capacity;
4074 var j = (((( this._front - 1 ) &
4075 ( capacity - 1) ) ^ capacity ) - capacity );
4076 this[j] = arguments[i];
4077 length++;
4078 this._length = length;
4079 this._front = j;
4080 }
4081 return length;
4082 }
4083 else {
4084 var front = this._front;
4085 for (var i = argsLength - 1; i >= 0; i--) {
4086 var j = (((( front - 1 ) &
4087 ( capacity - 1) ) ^ capacity ) - capacity );
4088 this[j] = arguments[i];
4089 front = j;
4090 }
4091 this._front = front;
4092 this._length = length + argsLength;
4093 return length + argsLength;
4094 }
4095 }
4096
4097 if (argsLength === 0) return length;
4098
4099 this._checkCapacity(length + 1);
4100 var capacity = this._capacity;
4101 var i = (((( this._front - 1 ) &
4102 ( capacity - 1) ) ^ capacity ) - capacity );
4103 this[i] = item;
4104 this._length = length + 1;
4105 this._front = i;
4106 return length + 1;
4107};
4108
4109Deque.prototype.peekBack = function Deque$peekBack() {
4110 var length = this._length;
4111 if (length === 0) {
4112 return void 0;
4113 }
4114 var index = (this._front + length - 1) & (this._capacity - 1);
4115 return this[index];
4116};
4117
4118Deque.prototype.peekFront = function Deque$peekFront() {
4119 if (this._length === 0) {
4120 return void 0;
4121 }
4122 return this[this._front];
4123};
4124
4125Deque.prototype.get = function Deque$get(index) {
4126 var i = index;
4127 if ((i !== (i | 0))) {
4128 return void 0;
4129 }
4130 var len = this._length;
4131 if (i < 0) {
4132 i = i + len;
4133 }
4134 if (i < 0 || i >= len) {
4135 return void 0;
4136 }
4137 return this[(this._front + i) & (this._capacity - 1)];
4138};
4139
4140Deque.prototype.isEmpty = function Deque$isEmpty() {
4141 return this._length === 0;
4142};
4143
4144Deque.prototype.clear = function Deque$clear() {
4145 var len = this._length;
4146 var front = this._front;
4147 var capacity = this._capacity;
4148 for (var j = 0; j < len; ++j) {
4149 this[(front + j) & (capacity - 1)] = void 0;
4150 }
4151 this._length = 0;
4152 this._front = 0;
4153};
4154
4155Deque.prototype.toString = function Deque$toString() {
4156 return this.toArray().toString();
4157};
4158
4159Deque.prototype.valueOf = Deque.prototype.toString;
4160Deque.prototype.removeFront = Deque.prototype.shift;
4161Deque.prototype.removeBack = Deque.prototype.pop;
4162Deque.prototype.insertFront = Deque.prototype.unshift;
4163Deque.prototype.insertBack = Deque.prototype.push;
4164Deque.prototype.enqueue = Deque.prototype.push;
4165Deque.prototype.dequeue = Deque.prototype.shift;
4166Deque.prototype.toJSON = Deque.prototype.toArray;
4167
4168Object.defineProperty(Deque.prototype, "length", {
4169 get: function() {
4170 return this._length;
4171 },
4172 set: function() {
4173 throw new RangeError("");
4174 }
4175});
4176
4177Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
4178 if (this._capacity < size) {
4179 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
4180 }
4181};
4182
4183Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
4184 var oldCapacity = this._capacity;
4185 this._capacity = capacity;
4186 var front = this._front;
4187 var length = this._length;
4188 if (front + length > oldCapacity) {
4189 var moveItemsCount = (front + length) & (oldCapacity - 1);
4190 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4191 }
4192};
4193
4194
4195var isArray = Array.isArray;
4196
4197function arrayMove(src, srcIndex, dst, dstIndex, len) {
4198 for (var j = 0; j < len; ++j) {
4199 dst[j + dstIndex] = src[j + srcIndex];
4200 src[j + srcIndex] = void 0;
4201 }
4202}
4203
4204function pow2AtLeast(n) {
4205 n = n >>> 0;
4206 n = n - 1;
4207 n = n | (n >> 1);
4208 n = n | (n >> 2);
4209 n = n | (n >> 4);
4210 n = n | (n >> 8);
4211 n = n | (n >> 16);
4212 return n + 1;
4213}
4214
4215function getCapacity(capacity) {
4216 if (typeof capacity !== "number") {
4217 if (isArray(capacity)) {
4218 capacity = capacity.length;
4219 }
4220 else {
4221 return 16;
4222 }
4223 }
4224 return pow2AtLeast(
4225 Math.min(
4226 Math.max(16, capacity), 1073741824)
4227 );
4228}
4229
4230module.exports = Deque;
4231
4232},{}],19:[function(_dereq_,module,exports){
4233var prr = _dereq_(68)
4234
4235function init (type, message, cause) {
4236 if (!!message && typeof message != 'string') {
4237 message = message.message || message.name
4238 }
4239 prr(this, {
4240 type : type
4241 , name : type
4242 // can be passed just a 'cause'
4243 , cause : typeof message != 'string' ? message : cause
4244 , message : message
4245 }, 'ewr')
4246}
4247
4248// generic prototype, not intended to be actually used - helpful for `instanceof`
4249function CustomError (message, cause) {
4250 Error.call(this)
4251 if (Error.captureStackTrace)
4252 Error.captureStackTrace(this, this.constructor)
4253 init.call(this, 'CustomError', message, cause)
4254}
4255
4256CustomError.prototype = new Error()
4257
4258function createError (errno, type, proto) {
4259 var err = function (message, cause) {
4260 init.call(this, type, message, cause)
4261 //TODO: the specificity here is stupid, errno should be available everywhere
4262 if (type == 'FilesystemError') {
4263 this.code = this.cause.code
4264 this.path = this.cause.path
4265 this.errno = this.cause.errno
4266 this.message =
4267 (errno.errno[this.cause.errno]
4268 ? errno.errno[this.cause.errno].description
4269 : this.cause.message)
4270 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
4271 }
4272 Error.call(this)
4273 if (Error.captureStackTrace)
4274 Error.captureStackTrace(this, err)
4275 }
4276 err.prototype = !!proto ? new proto() : new CustomError()
4277 return err
4278}
4279
4280module.exports = function (errno) {
4281 var ce = function (type, proto) {
4282 return createError(errno, type, proto)
4283 }
4284 return {
4285 CustomError : CustomError
4286 , FilesystemError : ce('FilesystemError')
4287 , createError : ce
4288 }
4289}
4290
4291},{"68":68}],20:[function(_dereq_,module,exports){
4292var all = module.exports.all = [
4293 {
4294 errno: -2,
4295 code: 'ENOENT',
4296 description: 'no such file or directory'
4297 },
4298 {
4299 errno: -1,
4300 code: 'UNKNOWN',
4301 description: 'unknown error'
4302 },
4303 {
4304 errno: 0,
4305 code: 'OK',
4306 description: 'success'
4307 },
4308 {
4309 errno: 1,
4310 code: 'EOF',
4311 description: 'end of file'
4312 },
4313 {
4314 errno: 2,
4315 code: 'EADDRINFO',
4316 description: 'getaddrinfo error'
4317 },
4318 {
4319 errno: 3,
4320 code: 'EACCES',
4321 description: 'permission denied'
4322 },
4323 {
4324 errno: 4,
4325 code: 'EAGAIN',
4326 description: 'resource temporarily unavailable'
4327 },
4328 {
4329 errno: 5,
4330 code: 'EADDRINUSE',
4331 description: 'address already in use'
4332 },
4333 {
4334 errno: 6,
4335 code: 'EADDRNOTAVAIL',
4336 description: 'address not available'
4337 },
4338 {
4339 errno: 7,
4340 code: 'EAFNOSUPPORT',
4341 description: 'address family not supported'
4342 },
4343 {
4344 errno: 8,
4345 code: 'EALREADY',
4346 description: 'connection already in progress'
4347 },
4348 {
4349 errno: 9,
4350 code: 'EBADF',
4351 description: 'bad file descriptor'
4352 },
4353 {
4354 errno: 10,
4355 code: 'EBUSY',
4356 description: 'resource busy or locked'
4357 },
4358 {
4359 errno: 11,
4360 code: 'ECONNABORTED',
4361 description: 'software caused connection abort'
4362 },
4363 {
4364 errno: 12,
4365 code: 'ECONNREFUSED',
4366 description: 'connection refused'
4367 },
4368 {
4369 errno: 13,
4370 code: 'ECONNRESET',
4371 description: 'connection reset by peer'
4372 },
4373 {
4374 errno: 14,
4375 code: 'EDESTADDRREQ',
4376 description: 'destination address required'
4377 },
4378 {
4379 errno: 15,
4380 code: 'EFAULT',
4381 description: 'bad address in system call argument'
4382 },
4383 {
4384 errno: 16,
4385 code: 'EHOSTUNREACH',
4386 description: 'host is unreachable'
4387 },
4388 {
4389 errno: 17,
4390 code: 'EINTR',
4391 description: 'interrupted system call'
4392 },
4393 {
4394 errno: 18,
4395 code: 'EINVAL',
4396 description: 'invalid argument'
4397 },
4398 {
4399 errno: 19,
4400 code: 'EISCONN',
4401 description: 'socket is already connected'
4402 },
4403 {
4404 errno: 20,
4405 code: 'EMFILE',
4406 description: 'too many open files'
4407 },
4408 {
4409 errno: 21,
4410 code: 'EMSGSIZE',
4411 description: 'message too long'
4412 },
4413 {
4414 errno: 22,
4415 code: 'ENETDOWN',
4416 description: 'network is down'
4417 },
4418 {
4419 errno: 23,
4420 code: 'ENETUNREACH',
4421 description: 'network is unreachable'
4422 },
4423 {
4424 errno: 24,
4425 code: 'ENFILE',
4426 description: 'file table overflow'
4427 },
4428 {
4429 errno: 25,
4430 code: 'ENOBUFS',
4431 description: 'no buffer space available'
4432 },
4433 {
4434 errno: 26,
4435 code: 'ENOMEM',
4436 description: 'not enough memory'
4437 },
4438 {
4439 errno: 27,
4440 code: 'ENOTDIR',
4441 description: 'not a directory'
4442 },
4443 {
4444 errno: 28,
4445 code: 'EISDIR',
4446 description: 'illegal operation on a directory'
4447 },
4448 {
4449 errno: 29,
4450 code: 'ENONET',
4451 description: 'machine is not on the network'
4452 },
4453 {
4454 errno: 31,
4455 code: 'ENOTCONN',
4456 description: 'socket is not connected'
4457 },
4458 {
4459 errno: 32,
4460 code: 'ENOTSOCK',
4461 description: 'socket operation on non-socket'
4462 },
4463 {
4464 errno: 33,
4465 code: 'ENOTSUP',
4466 description: 'operation not supported on socket'
4467 },
4468 {
4469 errno: 34,
4470 code: 'ENOENT',
4471 description: 'no such file or directory'
4472 },
4473 {
4474 errno: 35,
4475 code: 'ENOSYS',
4476 description: 'function not implemented'
4477 },
4478 {
4479 errno: 36,
4480 code: 'EPIPE',
4481 description: 'broken pipe'
4482 },
4483 {
4484 errno: 37,
4485 code: 'EPROTO',
4486 description: 'protocol error'
4487 },
4488 {
4489 errno: 38,
4490 code: 'EPROTONOSUPPORT',
4491 description: 'protocol not supported'
4492 },
4493 {
4494 errno: 39,
4495 code: 'EPROTOTYPE',
4496 description: 'protocol wrong type for socket'
4497 },
4498 {
4499 errno: 40,
4500 code: 'ETIMEDOUT',
4501 description: 'connection timed out'
4502 },
4503 {
4504 errno: 41,
4505 code: 'ECHARSET',
4506 description: 'invalid Unicode character'
4507 },
4508 {
4509 errno: 42,
4510 code: 'EAIFAMNOSUPPORT',
4511 description: 'address family for hostname not supported'
4512 },
4513 {
4514 errno: 44,
4515 code: 'EAISERVICE',
4516 description: 'servname not supported for ai_socktype'
4517 },
4518 {
4519 errno: 45,
4520 code: 'EAISOCKTYPE',
4521 description: 'ai_socktype not supported'
4522 },
4523 {
4524 errno: 46,
4525 code: 'ESHUTDOWN',
4526 description: 'cannot send after transport endpoint shutdown'
4527 },
4528 {
4529 errno: 47,
4530 code: 'EEXIST',
4531 description: 'file already exists'
4532 },
4533 {
4534 errno: 48,
4535 code: 'ESRCH',
4536 description: 'no such process'
4537 },
4538 {
4539 errno: 49,
4540 code: 'ENAMETOOLONG',
4541 description: 'name too long'
4542 },
4543 {
4544 errno: 50,
4545 code: 'EPERM',
4546 description: 'operation not permitted'
4547 },
4548 {
4549 errno: 51,
4550 code: 'ELOOP',
4551 description: 'too many symbolic links encountered'
4552 },
4553 {
4554 errno: 52,
4555 code: 'EXDEV',
4556 description: 'cross-device link not permitted'
4557 },
4558 {
4559 errno: 53,
4560 code: 'ENOTEMPTY',
4561 description: 'directory not empty'
4562 },
4563 {
4564 errno: 54,
4565 code: 'ENOSPC',
4566 description: 'no space left on device'
4567 },
4568 {
4569 errno: 55,
4570 code: 'EIO',
4571 description: 'i/o error'
4572 },
4573 {
4574 errno: 56,
4575 code: 'EROFS',
4576 description: 'read-only file system'
4577 },
4578 {
4579 errno: 57,
4580 code: 'ENODEV',
4581 description: 'no such device'
4582 },
4583 {
4584 errno: 58,
4585 code: 'ESPIPE',
4586 description: 'invalid seek'
4587 },
4588 {
4589 errno: 59,
4590 code: 'ECANCELED',
4591 description: 'operation canceled'
4592 }
4593]
4594
4595module.exports.errno = {}
4596module.exports.code = {}
4597
4598all.forEach(function (error) {
4599 module.exports.errno[error.errno] = error
4600 module.exports.code[error.code] = error
4601})
4602
4603module.exports.custom = _dereq_(19)(module.exports)
4604module.exports.create = module.exports.custom.createError
4605
4606},{"19":19}],21:[function(_dereq_,module,exports){
4607// Copyright Joyent, Inc. and other Node contributors.
4608//
4609// Permission is hereby granted, free of charge, to any person obtaining a
4610// copy of this software and associated documentation files (the
4611// "Software"), to deal in the Software without restriction, including
4612// without limitation the rights to use, copy, modify, merge, publish,
4613// distribute, sublicense, and/or sell copies of the Software, and to permit
4614// persons to whom the Software is furnished to do so, subject to the
4615// following conditions:
4616//
4617// The above copyright notice and this permission notice shall be included
4618// in all copies or substantial portions of the Software.
4619//
4620// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4621// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4622// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4623// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4624// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4625// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4626// USE OR OTHER DEALINGS IN THE SOFTWARE.
4627
4628var objectCreate = Object.create || objectCreatePolyfill
4629var objectKeys = Object.keys || objectKeysPolyfill
4630var bind = Function.prototype.bind || functionBindPolyfill
4631
4632function EventEmitter() {
4633 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
4634 this._events = objectCreate(null);
4635 this._eventsCount = 0;
4636 }
4637
4638 this._maxListeners = this._maxListeners || undefined;
4639}
4640module.exports = EventEmitter;
4641
4642// Backwards-compat with node 0.10.x
4643EventEmitter.EventEmitter = EventEmitter;
4644
4645EventEmitter.prototype._events = undefined;
4646EventEmitter.prototype._maxListeners = undefined;
4647
4648// By default EventEmitters will print a warning if more than 10 listeners are
4649// added to it. This is a useful default which helps finding memory leaks.
4650var defaultMaxListeners = 10;
4651
4652var hasDefineProperty;
4653try {
4654 var o = {};
4655 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
4656 hasDefineProperty = o.x === 0;
4657} catch (err) { hasDefineProperty = false }
4658if (hasDefineProperty) {
4659 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
4660 enumerable: true,
4661 get: function() {
4662 return defaultMaxListeners;
4663 },
4664 set: function(arg) {
4665 // check whether the input is a positive number (whose value is zero or
4666 // greater and not a NaN).
4667 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
4668 throw new TypeError('"defaultMaxListeners" must be a positive number');
4669 defaultMaxListeners = arg;
4670 }
4671 });
4672} else {
4673 EventEmitter.defaultMaxListeners = defaultMaxListeners;
4674}
4675
4676// Obviously not all Emitters should be limited to 10. This function allows
4677// that to be increased. Set to zero for unlimited.
4678EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
4679 if (typeof n !== 'number' || n < 0 || isNaN(n))
4680 throw new TypeError('"n" argument must be a positive number');
4681 this._maxListeners = n;
4682 return this;
4683};
4684
4685function $getMaxListeners(that) {
4686 if (that._maxListeners === undefined)
4687 return EventEmitter.defaultMaxListeners;
4688 return that._maxListeners;
4689}
4690
4691EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
4692 return $getMaxListeners(this);
4693};
4694
4695// These standalone emit* functions are used to optimize calling of event
4696// handlers for fast cases because emit() itself often has a variable number of
4697// arguments and can be deoptimized because of that. These functions always have
4698// the same number of arguments and thus do not get deoptimized, so the code
4699// inside them can execute faster.
4700function emitNone(handler, isFn, self) {
4701 if (isFn)
4702 handler.call(self);
4703 else {
4704 var len = handler.length;
4705 var listeners = arrayClone(handler, len);
4706 for (var i = 0; i < len; ++i)
4707 listeners[i].call(self);
4708 }
4709}
4710function emitOne(handler, isFn, self, arg1) {
4711 if (isFn)
4712 handler.call(self, arg1);
4713 else {
4714 var len = handler.length;
4715 var listeners = arrayClone(handler, len);
4716 for (var i = 0; i < len; ++i)
4717 listeners[i].call(self, arg1);
4718 }
4719}
4720function emitTwo(handler, isFn, self, arg1, arg2) {
4721 if (isFn)
4722 handler.call(self, arg1, arg2);
4723 else {
4724 var len = handler.length;
4725 var listeners = arrayClone(handler, len);
4726 for (var i = 0; i < len; ++i)
4727 listeners[i].call(self, arg1, arg2);
4728 }
4729}
4730function emitThree(handler, isFn, self, arg1, arg2, arg3) {
4731 if (isFn)
4732 handler.call(self, arg1, arg2, arg3);
4733 else {
4734 var len = handler.length;
4735 var listeners = arrayClone(handler, len);
4736 for (var i = 0; i < len; ++i)
4737 listeners[i].call(self, arg1, arg2, arg3);
4738 }
4739}
4740
4741function emitMany(handler, isFn, self, args) {
4742 if (isFn)
4743 handler.apply(self, args);
4744 else {
4745 var len = handler.length;
4746 var listeners = arrayClone(handler, len);
4747 for (var i = 0; i < len; ++i)
4748 listeners[i].apply(self, args);
4749 }
4750}
4751
4752EventEmitter.prototype.emit = function emit(type) {
4753 var er, handler, len, args, i, events;
4754 var doError = (type === 'error');
4755
4756 events = this._events;
4757 if (events)
4758 doError = (doError && events.error == null);
4759 else if (!doError)
4760 return false;
4761
4762 // If there is no 'error' event listener then throw.
4763 if (doError) {
4764 if (arguments.length > 1)
4765 er = arguments[1];
4766 if (er instanceof Error) {
4767 throw er; // Unhandled 'error' event
4768 } else {
4769 // At least give some kind of context to the user
4770 var err = new Error('Unhandled "error" event. (' + er + ')');
4771 err.context = er;
4772 throw err;
4773 }
4774 return false;
4775 }
4776
4777 handler = events[type];
4778
4779 if (!handler)
4780 return false;
4781
4782 var isFn = typeof handler === 'function';
4783 len = arguments.length;
4784 switch (len) {
4785 // fast cases
4786 case 1:
4787 emitNone(handler, isFn, this);
4788 break;
4789 case 2:
4790 emitOne(handler, isFn, this, arguments[1]);
4791 break;
4792 case 3:
4793 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
4794 break;
4795 case 4:
4796 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
4797 break;
4798 // slower
4799 default:
4800 args = new Array(len - 1);
4801 for (i = 1; i < len; i++)
4802 args[i - 1] = arguments[i];
4803 emitMany(handler, isFn, this, args);
4804 }
4805
4806 return true;
4807};
4808
4809function _addListener(target, type, listener, prepend) {
4810 var m;
4811 var events;
4812 var existing;
4813
4814 if (typeof listener !== 'function')
4815 throw new TypeError('"listener" argument must be a function');
4816
4817 events = target._events;
4818 if (!events) {
4819 events = target._events = objectCreate(null);
4820 target._eventsCount = 0;
4821 } else {
4822 // To avoid recursion in the case that type === "newListener"! Before
4823 // adding it to the listeners, first emit "newListener".
4824 if (events.newListener) {
4825 target.emit('newListener', type,
4826 listener.listener ? listener.listener : listener);
4827
4828 // Re-assign `events` because a newListener handler could have caused the
4829 // this._events to be assigned to a new object
4830 events = target._events;
4831 }
4832 existing = events[type];
4833 }
4834
4835 if (!existing) {
4836 // Optimize the case of one listener. Don't need the extra array object.
4837 existing = events[type] = listener;
4838 ++target._eventsCount;
4839 } else {
4840 if (typeof existing === 'function') {
4841 // Adding the second element, need to change to array.
4842 existing = events[type] =
4843 prepend ? [listener, existing] : [existing, listener];
4844 } else {
4845 // If we've already got an array, just append.
4846 if (prepend) {
4847 existing.unshift(listener);
4848 } else {
4849 existing.push(listener);
4850 }
4851 }
4852
4853 // Check for listener leak
4854 if (!existing.warned) {
4855 m = $getMaxListeners(target);
4856 if (m && m > 0 && existing.length > m) {
4857 existing.warned = true;
4858 var w = new Error('Possible EventEmitter memory leak detected. ' +
4859 existing.length + ' "' + String(type) + '" listeners ' +
4860 'added. Use emitter.setMaxListeners() to ' +
4861 'increase limit.');
4862 w.name = 'MaxListenersExceededWarning';
4863 w.emitter = target;
4864 w.type = type;
4865 w.count = existing.length;
4866 if (typeof console === 'object' && console.warn) {
4867 console.warn('%s: %s', w.name, w.message);
4868 }
4869 }
4870 }
4871 }
4872
4873 return target;
4874}
4875
4876EventEmitter.prototype.addListener = function addListener(type, listener) {
4877 return _addListener(this, type, listener, false);
4878};
4879
4880EventEmitter.prototype.on = EventEmitter.prototype.addListener;
4881
4882EventEmitter.prototype.prependListener =
4883 function prependListener(type, listener) {
4884 return _addListener(this, type, listener, true);
4885 };
4886
4887function onceWrapper() {
4888 if (!this.fired) {
4889 this.target.removeListener(this.type, this.wrapFn);
4890 this.fired = true;
4891 switch (arguments.length) {
4892 case 0:
4893 return this.listener.call(this.target);
4894 case 1:
4895 return this.listener.call(this.target, arguments[0]);
4896 case 2:
4897 return this.listener.call(this.target, arguments[0], arguments[1]);
4898 case 3:
4899 return this.listener.call(this.target, arguments[0], arguments[1],
4900 arguments[2]);
4901 default:
4902 var args = new Array(arguments.length);
4903 for (var i = 0; i < args.length; ++i)
4904 args[i] = arguments[i];
4905 this.listener.apply(this.target, args);
4906 }
4907 }
4908}
4909
4910function _onceWrap(target, type, listener) {
4911 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
4912 var wrapped = bind.call(onceWrapper, state);
4913 wrapped.listener = listener;
4914 state.wrapFn = wrapped;
4915 return wrapped;
4916}
4917
4918EventEmitter.prototype.once = function once(type, listener) {
4919 if (typeof listener !== 'function')
4920 throw new TypeError('"listener" argument must be a function');
4921 this.on(type, _onceWrap(this, type, listener));
4922 return this;
4923};
4924
4925EventEmitter.prototype.prependOnceListener =
4926 function prependOnceListener(type, listener) {
4927 if (typeof listener !== 'function')
4928 throw new TypeError('"listener" argument must be a function');
4929 this.prependListener(type, _onceWrap(this, type, listener));
4930 return this;
4931 };
4932
4933// Emits a 'removeListener' event if and only if the listener was removed.
4934EventEmitter.prototype.removeListener =
4935 function removeListener(type, listener) {
4936 var list, events, position, i, originalListener;
4937
4938 if (typeof listener !== 'function')
4939 throw new TypeError('"listener" argument must be a function');
4940
4941 events = this._events;
4942 if (!events)
4943 return this;
4944
4945 list = events[type];
4946 if (!list)
4947 return this;
4948
4949 if (list === listener || list.listener === listener) {
4950 if (--this._eventsCount === 0)
4951 this._events = objectCreate(null);
4952 else {
4953 delete events[type];
4954 if (events.removeListener)
4955 this.emit('removeListener', type, list.listener || listener);
4956 }
4957 } else if (typeof list !== 'function') {
4958 position = -1;
4959
4960 for (i = list.length - 1; i >= 0; i--) {
4961 if (list[i] === listener || list[i].listener === listener) {
4962 originalListener = list[i].listener;
4963 position = i;
4964 break;
4965 }
4966 }
4967
4968 if (position < 0)
4969 return this;
4970
4971 if (position === 0)
4972 list.shift();
4973 else
4974 spliceOne(list, position);
4975
4976 if (list.length === 1)
4977 events[type] = list[0];
4978
4979 if (events.removeListener)
4980 this.emit('removeListener', type, originalListener || listener);
4981 }
4982
4983 return this;
4984 };
4985
4986EventEmitter.prototype.removeAllListeners =
4987 function removeAllListeners(type) {
4988 var listeners, events, i;
4989
4990 events = this._events;
4991 if (!events)
4992 return this;
4993
4994 // not listening for removeListener, no need to emit
4995 if (!events.removeListener) {
4996 if (arguments.length === 0) {
4997 this._events = objectCreate(null);
4998 this._eventsCount = 0;
4999 } else if (events[type]) {
5000 if (--this._eventsCount === 0)
5001 this._events = objectCreate(null);
5002 else
5003 delete events[type];
5004 }
5005 return this;
5006 }
5007
5008 // emit removeListener for all listeners on all events
5009 if (arguments.length === 0) {
5010 var keys = objectKeys(events);
5011 var key;
5012 for (i = 0; i < keys.length; ++i) {
5013 key = keys[i];
5014 if (key === 'removeListener') continue;
5015 this.removeAllListeners(key);
5016 }
5017 this.removeAllListeners('removeListener');
5018 this._events = objectCreate(null);
5019 this._eventsCount = 0;
5020 return this;
5021 }
5022
5023 listeners = events[type];
5024
5025 if (typeof listeners === 'function') {
5026 this.removeListener(type, listeners);
5027 } else if (listeners) {
5028 // LIFO order
5029 for (i = listeners.length - 1; i >= 0; i--) {
5030 this.removeListener(type, listeners[i]);
5031 }
5032 }
5033
5034 return this;
5035 };
5036
5037function _listeners(target, type, unwrap) {
5038 var events = target._events;
5039
5040 if (!events)
5041 return [];
5042
5043 var evlistener = events[type];
5044 if (!evlistener)
5045 return [];
5046
5047 if (typeof evlistener === 'function')
5048 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
5049
5050 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
5051}
5052
5053EventEmitter.prototype.listeners = function listeners(type) {
5054 return _listeners(this, type, true);
5055};
5056
5057EventEmitter.prototype.rawListeners = function rawListeners(type) {
5058 return _listeners(this, type, false);
5059};
5060
5061EventEmitter.listenerCount = function(emitter, type) {
5062 if (typeof emitter.listenerCount === 'function') {
5063 return emitter.listenerCount(type);
5064 } else {
5065 return listenerCount.call(emitter, type);
5066 }
5067};
5068
5069EventEmitter.prototype.listenerCount = listenerCount;
5070function listenerCount(type) {
5071 var events = this._events;
5072
5073 if (events) {
5074 var evlistener = events[type];
5075
5076 if (typeof evlistener === 'function') {
5077 return 1;
5078 } else if (evlistener) {
5079 return evlistener.length;
5080 }
5081 }
5082
5083 return 0;
5084}
5085
5086EventEmitter.prototype.eventNames = function eventNames() {
5087 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
5088};
5089
5090// About 1.5x faster than the two-arg version of Array#splice().
5091function spliceOne(list, index) {
5092 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
5093 list[i] = list[k];
5094 list.pop();
5095}
5096
5097function arrayClone(arr, n) {
5098 var copy = new Array(n);
5099 for (var i = 0; i < n; ++i)
5100 copy[i] = arr[i];
5101 return copy;
5102}
5103
5104function unwrapListeners(arr) {
5105 var ret = new Array(arr.length);
5106 for (var i = 0; i < ret.length; ++i) {
5107 ret[i] = arr[i].listener || arr[i];
5108 }
5109 return ret;
5110}
5111
5112function objectCreatePolyfill(proto) {
5113 var F = function() {};
5114 F.prototype = proto;
5115 return new F;
5116}
5117function objectKeysPolyfill(obj) {
5118 var keys = [];
5119 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
5120 keys.push(k);
5121 }
5122 return k;
5123}
5124function functionBindPolyfill(context) {
5125 var fn = this;
5126 return function () {
5127 return fn.apply(context, arguments);
5128 };
5129}
5130
5131},{}],22:[function(_dereq_,module,exports){
5132"use strict"
5133
5134module.exports = createRBTree
5135
5136var RED = 0
5137var BLACK = 1
5138
5139function RBNode(color, key, value, left, right, count) {
5140 this._color = color
5141 this.key = key
5142 this.value = value
5143 this.left = left
5144 this.right = right
5145 this._count = count
5146}
5147
5148function cloneNode(node) {
5149 return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
5150}
5151
5152function repaint(color, node) {
5153 return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
5154}
5155
5156function recount(node) {
5157 node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
5158}
5159
5160function RedBlackTree(compare, root) {
5161 this._compare = compare
5162 this.root = root
5163}
5164
5165var proto = RedBlackTree.prototype
5166
5167Object.defineProperty(proto, "keys", {
5168 get: function() {
5169 var result = []
5170 this.forEach(function(k,v) {
5171 result.push(k)
5172 })
5173 return result
5174 }
5175})
5176
5177Object.defineProperty(proto, "values", {
5178 get: function() {
5179 var result = []
5180 this.forEach(function(k,v) {
5181 result.push(v)
5182 })
5183 return result
5184 }
5185})
5186
5187//Returns the number of nodes in the tree
5188Object.defineProperty(proto, "length", {
5189 get: function() {
5190 if(this.root) {
5191 return this.root._count
5192 }
5193 return 0
5194 }
5195})
5196
5197//Insert a new item into the tree
5198proto.insert = function(key, value) {
5199 var cmp = this._compare
5200 //Find point to insert new node at
5201 var n = this.root
5202 var n_stack = []
5203 var d_stack = []
5204 while(n) {
5205 var d = cmp(key, n.key)
5206 n_stack.push(n)
5207 d_stack.push(d)
5208 if(d <= 0) {
5209 n = n.left
5210 } else {
5211 n = n.right
5212 }
5213 }
5214 //Rebuild path to leaf node
5215 n_stack.push(new RBNode(RED, key, value, null, null, 1))
5216 for(var s=n_stack.length-2; s>=0; --s) {
5217 var n = n_stack[s]
5218 if(d_stack[s] <= 0) {
5219 n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
5220 } else {
5221 n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
5222 }
5223 }
5224 //Rebalance tree using rotations
5225 //console.log("start insert", key, d_stack)
5226 for(var s=n_stack.length-1; s>1; --s) {
5227 var p = n_stack[s-1]
5228 var n = n_stack[s]
5229 if(p._color === BLACK || n._color === BLACK) {
5230 break
5231 }
5232 var pp = n_stack[s-2]
5233 if(pp.left === p) {
5234 if(p.left === n) {
5235 var y = pp.right
5236 if(y && y._color === RED) {
5237 //console.log("LLr")
5238 p._color = BLACK
5239 pp.right = repaint(BLACK, y)
5240 pp._color = RED
5241 s -= 1
5242 } else {
5243 //console.log("LLb")
5244 pp._color = RED
5245 pp.left = p.right
5246 p._color = BLACK
5247 p.right = pp
5248 n_stack[s-2] = p
5249 n_stack[s-1] = n
5250 recount(pp)
5251 recount(p)
5252 if(s >= 3) {
5253 var ppp = n_stack[s-3]
5254 if(ppp.left === pp) {
5255 ppp.left = p
5256 } else {
5257 ppp.right = p
5258 }
5259 }
5260 break
5261 }
5262 } else {
5263 var y = pp.right
5264 if(y && y._color === RED) {
5265 //console.log("LRr")
5266 p._color = BLACK
5267 pp.right = repaint(BLACK, y)
5268 pp._color = RED
5269 s -= 1
5270 } else {
5271 //console.log("LRb")
5272 p.right = n.left
5273 pp._color = RED
5274 pp.left = n.right
5275 n._color = BLACK
5276 n.left = p
5277 n.right = pp
5278 n_stack[s-2] = n
5279 n_stack[s-1] = p
5280 recount(pp)
5281 recount(p)
5282 recount(n)
5283 if(s >= 3) {
5284 var ppp = n_stack[s-3]
5285 if(ppp.left === pp) {
5286 ppp.left = n
5287 } else {
5288 ppp.right = n
5289 }
5290 }
5291 break
5292 }
5293 }
5294 } else {
5295 if(p.right === n) {
5296 var y = pp.left
5297 if(y && y._color === RED) {
5298 //console.log("RRr", y.key)
5299 p._color = BLACK
5300 pp.left = repaint(BLACK, y)
5301 pp._color = RED
5302 s -= 1
5303 } else {
5304 //console.log("RRb")
5305 pp._color = RED
5306 pp.right = p.left
5307 p._color = BLACK
5308 p.left = pp
5309 n_stack[s-2] = p
5310 n_stack[s-1] = n
5311 recount(pp)
5312 recount(p)
5313 if(s >= 3) {
5314 var ppp = n_stack[s-3]
5315 if(ppp.right === pp) {
5316 ppp.right = p
5317 } else {
5318 ppp.left = p
5319 }
5320 }
5321 break
5322 }
5323 } else {
5324 var y = pp.left
5325 if(y && y._color === RED) {
5326 //console.log("RLr")
5327 p._color = BLACK
5328 pp.left = repaint(BLACK, y)
5329 pp._color = RED
5330 s -= 1
5331 } else {
5332 //console.log("RLb")
5333 p.left = n.right
5334 pp._color = RED
5335 pp.right = n.left
5336 n._color = BLACK
5337 n.right = p
5338 n.left = pp
5339 n_stack[s-2] = n
5340 n_stack[s-1] = p
5341 recount(pp)
5342 recount(p)
5343 recount(n)
5344 if(s >= 3) {
5345 var ppp = n_stack[s-3]
5346 if(ppp.right === pp) {
5347 ppp.right = n
5348 } else {
5349 ppp.left = n
5350 }
5351 }
5352 break
5353 }
5354 }
5355 }
5356 }
5357 //Return new tree
5358 n_stack[0]._color = BLACK
5359 return new RedBlackTree(cmp, n_stack[0])
5360}
5361
5362
5363//Visit all nodes inorder
5364function doVisitFull(visit, node) {
5365 if(node.left) {
5366 var v = doVisitFull(visit, node.left)
5367 if(v) { return v }
5368 }
5369 var v = visit(node.key, node.value)
5370 if(v) { return v }
5371 if(node.right) {
5372 return doVisitFull(visit, node.right)
5373 }
5374}
5375
5376//Visit half nodes in order
5377function doVisitHalf(lo, compare, visit, node) {
5378 var l = compare(lo, node.key)
5379 if(l <= 0) {
5380 if(node.left) {
5381 var v = doVisitHalf(lo, compare, visit, node.left)
5382 if(v) { return v }
5383 }
5384 var v = visit(node.key, node.value)
5385 if(v) { return v }
5386 }
5387 if(node.right) {
5388 return doVisitHalf(lo, compare, visit, node.right)
5389 }
5390}
5391
5392//Visit all nodes within a range
5393function doVisit(lo, hi, compare, visit, node) {
5394 var l = compare(lo, node.key)
5395 var h = compare(hi, node.key)
5396 var v
5397 if(l <= 0) {
5398 if(node.left) {
5399 v = doVisit(lo, hi, compare, visit, node.left)
5400 if(v) { return v }
5401 }
5402 if(h > 0) {
5403 v = visit(node.key, node.value)
5404 if(v) { return v }
5405 }
5406 }
5407 if(h > 0 && node.right) {
5408 return doVisit(lo, hi, compare, visit, node.right)
5409 }
5410}
5411
5412
5413proto.forEach = function rbTreeForEach(visit, lo, hi) {
5414 if(!this.root) {
5415 return
5416 }
5417 switch(arguments.length) {
5418 case 1:
5419 return doVisitFull(visit, this.root)
5420 break
5421
5422 case 2:
5423 return doVisitHalf(lo, this._compare, visit, this.root)
5424 break
5425
5426 case 3:
5427 if(this._compare(lo, hi) >= 0) {
5428 return
5429 }
5430 return doVisit(lo, hi, this._compare, visit, this.root)
5431 break
5432 }
5433}
5434
5435//First item in list
5436Object.defineProperty(proto, "begin", {
5437 get: function() {
5438 var stack = []
5439 var n = this.root
5440 while(n) {
5441 stack.push(n)
5442 n = n.left
5443 }
5444 return new RedBlackTreeIterator(this, stack)
5445 }
5446})
5447
5448//Last item in list
5449Object.defineProperty(proto, "end", {
5450 get: function() {
5451 var stack = []
5452 var n = this.root
5453 while(n) {
5454 stack.push(n)
5455 n = n.right
5456 }
5457 return new RedBlackTreeIterator(this, stack)
5458 }
5459})
5460
5461//Find the ith item in the tree
5462proto.at = function(idx) {
5463 if(idx < 0) {
5464 return new RedBlackTreeIterator(this, [])
5465 }
5466 var n = this.root
5467 var stack = []
5468 while(true) {
5469 stack.push(n)
5470 if(n.left) {
5471 if(idx < n.left._count) {
5472 n = n.left
5473 continue
5474 }
5475 idx -= n.left._count
5476 }
5477 if(!idx) {
5478 return new RedBlackTreeIterator(this, stack)
5479 }
5480 idx -= 1
5481 if(n.right) {
5482 if(idx >= n.right._count) {
5483 break
5484 }
5485 n = n.right
5486 } else {
5487 break
5488 }
5489 }
5490 return new RedBlackTreeIterator(this, [])
5491}
5492
5493proto.ge = function(key) {
5494 var cmp = this._compare
5495 var n = this.root
5496 var stack = []
5497 var last_ptr = 0
5498 while(n) {
5499 var d = cmp(key, n.key)
5500 stack.push(n)
5501 if(d <= 0) {
5502 last_ptr = stack.length
5503 }
5504 if(d <= 0) {
5505 n = n.left
5506 } else {
5507 n = n.right
5508 }
5509 }
5510 stack.length = last_ptr
5511 return new RedBlackTreeIterator(this, stack)
5512}
5513
5514proto.gt = function(key) {
5515 var cmp = this._compare
5516 var n = this.root
5517 var stack = []
5518 var last_ptr = 0
5519 while(n) {
5520 var d = cmp(key, n.key)
5521 stack.push(n)
5522 if(d < 0) {
5523 last_ptr = stack.length
5524 }
5525 if(d < 0) {
5526 n = n.left
5527 } else {
5528 n = n.right
5529 }
5530 }
5531 stack.length = last_ptr
5532 return new RedBlackTreeIterator(this, stack)
5533}
5534
5535proto.lt = function(key) {
5536 var cmp = this._compare
5537 var n = this.root
5538 var stack = []
5539 var last_ptr = 0
5540 while(n) {
5541 var d = cmp(key, n.key)
5542 stack.push(n)
5543 if(d > 0) {
5544 last_ptr = stack.length
5545 }
5546 if(d <= 0) {
5547 n = n.left
5548 } else {
5549 n = n.right
5550 }
5551 }
5552 stack.length = last_ptr
5553 return new RedBlackTreeIterator(this, stack)
5554}
5555
5556proto.le = function(key) {
5557 var cmp = this._compare
5558 var n = this.root
5559 var stack = []
5560 var last_ptr = 0
5561 while(n) {
5562 var d = cmp(key, n.key)
5563 stack.push(n)
5564 if(d >= 0) {
5565 last_ptr = stack.length
5566 }
5567 if(d < 0) {
5568 n = n.left
5569 } else {
5570 n = n.right
5571 }
5572 }
5573 stack.length = last_ptr
5574 return new RedBlackTreeIterator(this, stack)
5575}
5576
5577//Finds the item with key if it exists
5578proto.find = function(key) {
5579 var cmp = this._compare
5580 var n = this.root
5581 var stack = []
5582 while(n) {
5583 var d = cmp(key, n.key)
5584 stack.push(n)
5585 if(d === 0) {
5586 return new RedBlackTreeIterator(this, stack)
5587 }
5588 if(d <= 0) {
5589 n = n.left
5590 } else {
5591 n = n.right
5592 }
5593 }
5594 return new RedBlackTreeIterator(this, [])
5595}
5596
5597//Removes item with key from tree
5598proto.remove = function(key) {
5599 var iter = this.find(key)
5600 if(iter) {
5601 return iter.remove()
5602 }
5603 return this
5604}
5605
5606//Returns the item at `key`
5607proto.get = function(key) {
5608 var cmp = this._compare
5609 var n = this.root
5610 while(n) {
5611 var d = cmp(key, n.key)
5612 if(d === 0) {
5613 return n.value
5614 }
5615 if(d <= 0) {
5616 n = n.left
5617 } else {
5618 n = n.right
5619 }
5620 }
5621 return
5622}
5623
5624//Iterator for red black tree
5625function RedBlackTreeIterator(tree, stack) {
5626 this.tree = tree
5627 this._stack = stack
5628}
5629
5630var iproto = RedBlackTreeIterator.prototype
5631
5632//Test if iterator is valid
5633Object.defineProperty(iproto, "valid", {
5634 get: function() {
5635 return this._stack.length > 0
5636 }
5637})
5638
5639//Node of the iterator
5640Object.defineProperty(iproto, "node", {
5641 get: function() {
5642 if(this._stack.length > 0) {
5643 return this._stack[this._stack.length-1]
5644 }
5645 return null
5646 },
5647 enumerable: true
5648})
5649
5650//Makes a copy of an iterator
5651iproto.clone = function() {
5652 return new RedBlackTreeIterator(this.tree, this._stack.slice())
5653}
5654
5655//Swaps two nodes
5656function swapNode(n, v) {
5657 n.key = v.key
5658 n.value = v.value
5659 n.left = v.left
5660 n.right = v.right
5661 n._color = v._color
5662 n._count = v._count
5663}
5664
5665//Fix up a double black node in a tree
5666function fixDoubleBlack(stack) {
5667 var n, p, s, z
5668 for(var i=stack.length-1; i>=0; --i) {
5669 n = stack[i]
5670 if(i === 0) {
5671 n._color = BLACK
5672 return
5673 }
5674 //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
5675 p = stack[i-1]
5676 if(p.left === n) {
5677 //console.log("left child")
5678 s = p.right
5679 if(s.right && s.right._color === RED) {
5680 //console.log("case 1: right sibling child red")
5681 s = p.right = cloneNode(s)
5682 z = s.right = cloneNode(s.right)
5683 p.right = s.left
5684 s.left = p
5685 s.right = z
5686 s._color = p._color
5687 n._color = BLACK
5688 p._color = BLACK
5689 z._color = BLACK
5690 recount(p)
5691 recount(s)
5692 if(i > 1) {
5693 var pp = stack[i-2]
5694 if(pp.left === p) {
5695 pp.left = s
5696 } else {
5697 pp.right = s
5698 }
5699 }
5700 stack[i-1] = s
5701 return
5702 } else if(s.left && s.left._color === RED) {
5703 //console.log("case 1: left sibling child red")
5704 s = p.right = cloneNode(s)
5705 z = s.left = cloneNode(s.left)
5706 p.right = z.left
5707 s.left = z.right
5708 z.left = p
5709 z.right = s
5710 z._color = p._color
5711 p._color = BLACK
5712 s._color = BLACK
5713 n._color = BLACK
5714 recount(p)
5715 recount(s)
5716 recount(z)
5717 if(i > 1) {
5718 var pp = stack[i-2]
5719 if(pp.left === p) {
5720 pp.left = z
5721 } else {
5722 pp.right = z
5723 }
5724 }
5725 stack[i-1] = z
5726 return
5727 }
5728 if(s._color === BLACK) {
5729 if(p._color === RED) {
5730 //console.log("case 2: black sibling, red parent", p.right.value)
5731 p._color = BLACK
5732 p.right = repaint(RED, s)
5733 return
5734 } else {
5735 //console.log("case 2: black sibling, black parent", p.right.value)
5736 p.right = repaint(RED, s)
5737 continue
5738 }
5739 } else {
5740 //console.log("case 3: red sibling")
5741 s = cloneNode(s)
5742 p.right = s.left
5743 s.left = p
5744 s._color = p._color
5745 p._color = RED
5746 recount(p)
5747 recount(s)
5748 if(i > 1) {
5749 var pp = stack[i-2]
5750 if(pp.left === p) {
5751 pp.left = s
5752 } else {
5753 pp.right = s
5754 }
5755 }
5756 stack[i-1] = s
5757 stack[i] = p
5758 if(i+1 < stack.length) {
5759 stack[i+1] = n
5760 } else {
5761 stack.push(n)
5762 }
5763 i = i+2
5764 }
5765 } else {
5766 //console.log("right child")
5767 s = p.left
5768 if(s.left && s.left._color === RED) {
5769 //console.log("case 1: left sibling child red", p.value, p._color)
5770 s = p.left = cloneNode(s)
5771 z = s.left = cloneNode(s.left)
5772 p.left = s.right
5773 s.right = p
5774 s.left = z
5775 s._color = p._color
5776 n._color = BLACK
5777 p._color = BLACK
5778 z._color = BLACK
5779 recount(p)
5780 recount(s)
5781 if(i > 1) {
5782 var pp = stack[i-2]
5783 if(pp.right === p) {
5784 pp.right = s
5785 } else {
5786 pp.left = s
5787 }
5788 }
5789 stack[i-1] = s
5790 return
5791 } else if(s.right && s.right._color === RED) {
5792 //console.log("case 1: right sibling child red")
5793 s = p.left = cloneNode(s)
5794 z = s.right = cloneNode(s.right)
5795 p.left = z.right
5796 s.right = z.left
5797 z.right = p
5798 z.left = s
5799 z._color = p._color
5800 p._color = BLACK
5801 s._color = BLACK
5802 n._color = BLACK
5803 recount(p)
5804 recount(s)
5805 recount(z)
5806 if(i > 1) {
5807 var pp = stack[i-2]
5808 if(pp.right === p) {
5809 pp.right = z
5810 } else {
5811 pp.left = z
5812 }
5813 }
5814 stack[i-1] = z
5815 return
5816 }
5817 if(s._color === BLACK) {
5818 if(p._color === RED) {
5819 //console.log("case 2: black sibling, red parent")
5820 p._color = BLACK
5821 p.left = repaint(RED, s)
5822 return
5823 } else {
5824 //console.log("case 2: black sibling, black parent")
5825 p.left = repaint(RED, s)
5826 continue
5827 }
5828 } else {
5829 //console.log("case 3: red sibling")
5830 s = cloneNode(s)
5831 p.left = s.right
5832 s.right = p
5833 s._color = p._color
5834 p._color = RED
5835 recount(p)
5836 recount(s)
5837 if(i > 1) {
5838 var pp = stack[i-2]
5839 if(pp.right === p) {
5840 pp.right = s
5841 } else {
5842 pp.left = s
5843 }
5844 }
5845 stack[i-1] = s
5846 stack[i] = p
5847 if(i+1 < stack.length) {
5848 stack[i+1] = n
5849 } else {
5850 stack.push(n)
5851 }
5852 i = i+2
5853 }
5854 }
5855 }
5856}
5857
5858//Removes item at iterator from tree
5859iproto.remove = function() {
5860 var stack = this._stack
5861 if(stack.length === 0) {
5862 return this.tree
5863 }
5864 //First copy path to node
5865 var cstack = new Array(stack.length)
5866 var n = stack[stack.length-1]
5867 cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
5868 for(var i=stack.length-2; i>=0; --i) {
5869 var n = stack[i]
5870 if(n.left === stack[i+1]) {
5871 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5872 } else {
5873 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5874 }
5875 }
5876
5877 //Get node
5878 n = cstack[cstack.length-1]
5879 //console.log("start remove: ", n.value)
5880
5881 //If not leaf, then swap with previous node
5882 if(n.left && n.right) {
5883 //console.log("moving to leaf")
5884
5885 //First walk to previous leaf
5886 var split = cstack.length
5887 n = n.left
5888 while(n.right) {
5889 cstack.push(n)
5890 n = n.right
5891 }
5892 //Copy path to leaf
5893 var v = cstack[split-1]
5894 cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
5895 cstack[split-1].key = n.key
5896 cstack[split-1].value = n.value
5897
5898 //Fix up stack
5899 for(var i=cstack.length-2; i>=split; --i) {
5900 n = cstack[i]
5901 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5902 }
5903 cstack[split-1].left = cstack[split]
5904 }
5905 //console.log("stack=", cstack.map(function(v) { return v.value }))
5906
5907 //Remove leaf node
5908 n = cstack[cstack.length-1]
5909 if(n._color === RED) {
5910 //Easy case: removing red leaf
5911 //console.log("RED leaf")
5912 var p = cstack[cstack.length-2]
5913 if(p.left === n) {
5914 p.left = null
5915 } else if(p.right === n) {
5916 p.right = null
5917 }
5918 cstack.pop()
5919 for(var i=0; i<cstack.length; ++i) {
5920 cstack[i]._count--
5921 }
5922 return new RedBlackTree(this.tree._compare, cstack[0])
5923 } else {
5924 if(n.left || n.right) {
5925 //Second easy case: Single child black parent
5926 //console.log("BLACK single child")
5927 if(n.left) {
5928 swapNode(n, n.left)
5929 } else if(n.right) {
5930 swapNode(n, n.right)
5931 }
5932 //Child must be red, so repaint it black to balance color
5933 n._color = BLACK
5934 for(var i=0; i<cstack.length-1; ++i) {
5935 cstack[i]._count--
5936 }
5937 return new RedBlackTree(this.tree._compare, cstack[0])
5938 } else if(cstack.length === 1) {
5939 //Third easy case: root
5940 //console.log("ROOT")
5941 return new RedBlackTree(this.tree._compare, null)
5942 } else {
5943 //Hard case: Repaint n, and then do some nasty stuff
5944 //console.log("BLACK leaf no children")
5945 for(var i=0; i<cstack.length; ++i) {
5946 cstack[i]._count--
5947 }
5948 var parent = cstack[cstack.length-2]
5949 fixDoubleBlack(cstack)
5950 //Fix up links
5951 if(parent.left === n) {
5952 parent.left = null
5953 } else {
5954 parent.right = null
5955 }
5956 }
5957 }
5958 return new RedBlackTree(this.tree._compare, cstack[0])
5959}
5960
5961//Returns key
5962Object.defineProperty(iproto, "key", {
5963 get: function() {
5964 if(this._stack.length > 0) {
5965 return this._stack[this._stack.length-1].key
5966 }
5967 return
5968 },
5969 enumerable: true
5970})
5971
5972//Returns value
5973Object.defineProperty(iproto, "value", {
5974 get: function() {
5975 if(this._stack.length > 0) {
5976 return this._stack[this._stack.length-1].value
5977 }
5978 return
5979 },
5980 enumerable: true
5981})
5982
5983
5984//Returns the position of this iterator in the sorted list
5985Object.defineProperty(iproto, "index", {
5986 get: function() {
5987 var idx = 0
5988 var stack = this._stack
5989 if(stack.length === 0) {
5990 var r = this.tree.root
5991 if(r) {
5992 return r._count
5993 }
5994 return 0
5995 } else if(stack[stack.length-1].left) {
5996 idx = stack[stack.length-1].left._count
5997 }
5998 for(var s=stack.length-2; s>=0; --s) {
5999 if(stack[s+1] === stack[s].right) {
6000 ++idx
6001 if(stack[s].left) {
6002 idx += stack[s].left._count
6003 }
6004 }
6005 }
6006 return idx
6007 },
6008 enumerable: true
6009})
6010
6011//Advances iterator to next element in list
6012iproto.next = function() {
6013 var stack = this._stack
6014 if(stack.length === 0) {
6015 return
6016 }
6017 var n = stack[stack.length-1]
6018 if(n.right) {
6019 n = n.right
6020 while(n) {
6021 stack.push(n)
6022 n = n.left
6023 }
6024 } else {
6025 stack.pop()
6026 while(stack.length > 0 && stack[stack.length-1].right === n) {
6027 n = stack[stack.length-1]
6028 stack.pop()
6029 }
6030 }
6031}
6032
6033//Checks if iterator is at end of tree
6034Object.defineProperty(iproto, "hasNext", {
6035 get: function() {
6036 var stack = this._stack
6037 if(stack.length === 0) {
6038 return false
6039 }
6040 if(stack[stack.length-1].right) {
6041 return true
6042 }
6043 for(var s=stack.length-1; s>0; --s) {
6044 if(stack[s-1].left === stack[s]) {
6045 return true
6046 }
6047 }
6048 return false
6049 }
6050})
6051
6052//Update value
6053iproto.update = function(value) {
6054 var stack = this._stack
6055 if(stack.length === 0) {
6056 throw new Error("Can't update empty node!")
6057 }
6058 var cstack = new Array(stack.length)
6059 var n = stack[stack.length-1]
6060 cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
6061 for(var i=stack.length-2; i>=0; --i) {
6062 n = stack[i]
6063 if(n.left === stack[i+1]) {
6064 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
6065 } else {
6066 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
6067 }
6068 }
6069 return new RedBlackTree(this.tree._compare, cstack[0])
6070}
6071
6072//Moves iterator backward one element
6073iproto.prev = function() {
6074 var stack = this._stack
6075 if(stack.length === 0) {
6076 return
6077 }
6078 var n = stack[stack.length-1]
6079 if(n.left) {
6080 n = n.left
6081 while(n) {
6082 stack.push(n)
6083 n = n.right
6084 }
6085 } else {
6086 stack.pop()
6087 while(stack.length > 0 && stack[stack.length-1].left === n) {
6088 n = stack[stack.length-1]
6089 stack.pop()
6090 }
6091 }
6092}
6093
6094//Checks if iterator is at start of tree
6095Object.defineProperty(iproto, "hasPrev", {
6096 get: function() {
6097 var stack = this._stack
6098 if(stack.length === 0) {
6099 return false
6100 }
6101 if(stack[stack.length-1].left) {
6102 return true
6103 }
6104 for(var s=stack.length-1; s>0; --s) {
6105 if(stack[s-1].right === stack[s]) {
6106 return true
6107 }
6108 }
6109 return false
6110 }
6111})
6112
6113//Default comparison function
6114function defaultCompare(a, b) {
6115 if(a < b) {
6116 return -1
6117 }
6118 if(a > b) {
6119 return 1
6120 }
6121 return 0
6122}
6123
6124//Build a tree
6125function createRBTree(compare) {
6126 return new RedBlackTree(compare || defaultCompare, null)
6127}
6128},{}],23:[function(_dereq_,module,exports){
6129/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
6130exports.read = function (buffer, offset, isLE, mLen, nBytes) {
6131 var e, m
6132 var eLen = (nBytes * 8) - mLen - 1
6133 var eMax = (1 << eLen) - 1
6134 var eBias = eMax >> 1
6135 var nBits = -7
6136 var i = isLE ? (nBytes - 1) : 0
6137 var d = isLE ? -1 : 1
6138 var s = buffer[offset + i]
6139
6140 i += d
6141
6142 e = s & ((1 << (-nBits)) - 1)
6143 s >>= (-nBits)
6144 nBits += eLen
6145 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6146
6147 m = e & ((1 << (-nBits)) - 1)
6148 e >>= (-nBits)
6149 nBits += mLen
6150 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6151
6152 if (e === 0) {
6153 e = 1 - eBias
6154 } else if (e === eMax) {
6155 return m ? NaN : ((s ? -1 : 1) * Infinity)
6156 } else {
6157 m = m + Math.pow(2, mLen)
6158 e = e - eBias
6159 }
6160 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
6161}
6162
6163exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
6164 var e, m, c
6165 var eLen = (nBytes * 8) - mLen - 1
6166 var eMax = (1 << eLen) - 1
6167 var eBias = eMax >> 1
6168 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
6169 var i = isLE ? 0 : (nBytes - 1)
6170 var d = isLE ? 1 : -1
6171 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
6172
6173 value = Math.abs(value)
6174
6175 if (isNaN(value) || value === Infinity) {
6176 m = isNaN(value) ? 1 : 0
6177 e = eMax
6178 } else {
6179 e = Math.floor(Math.log(value) / Math.LN2)
6180 if (value * (c = Math.pow(2, -e)) < 1) {
6181 e--
6182 c *= 2
6183 }
6184 if (e + eBias >= 1) {
6185 value += rt / c
6186 } else {
6187 value += rt * Math.pow(2, 1 - eBias)
6188 }
6189 if (value * c >= 2) {
6190 e++
6191 c /= 2
6192 }
6193
6194 if (e + eBias >= eMax) {
6195 m = 0
6196 e = eMax
6197 } else if (e + eBias >= 1) {
6198 m = ((value * c) - 1) * Math.pow(2, mLen)
6199 e = e + eBias
6200 } else {
6201 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
6202 e = 0
6203 }
6204 }
6205
6206 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
6207
6208 e = (e << mLen) | m
6209 eLen += mLen
6210 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
6211
6212 buffer[offset + i - d] |= s * 128
6213}
6214
6215},{}],24:[function(_dereq_,module,exports){
6216'use strict';
6217var types = [
6218 _dereq_(7),
6219 _dereq_(27),
6220 _dereq_(26),
6221 _dereq_(25),
6222 _dereq_(28),
6223 _dereq_(29)
6224];
6225var draining;
6226var currentQueue;
6227var queueIndex = -1;
6228var queue = [];
6229var scheduled = false;
6230function cleanUpNextTick() {
6231 if (!draining || !currentQueue) {
6232 return;
6233 }
6234 draining = false;
6235 if (currentQueue.length) {
6236 queue = currentQueue.concat(queue);
6237 } else {
6238 queueIndex = -1;
6239 }
6240 if (queue.length) {
6241 nextTick();
6242 }
6243}
6244
6245//named nextTick for less confusing stack traces
6246function nextTick() {
6247 if (draining) {
6248 return;
6249 }
6250 scheduled = false;
6251 draining = true;
6252 var len = queue.length;
6253 var timeout = setTimeout(cleanUpNextTick);
6254 while (len) {
6255 currentQueue = queue;
6256 queue = [];
6257 while (currentQueue && ++queueIndex < len) {
6258 currentQueue[queueIndex].run();
6259 }
6260 queueIndex = -1;
6261 len = queue.length;
6262 }
6263 currentQueue = null;
6264 queueIndex = -1;
6265 draining = false;
6266 clearTimeout(timeout);
6267}
6268var scheduleDrain;
6269var i = -1;
6270var len = types.length;
6271while (++i < len) {
6272 if (types[i] && types[i].test && types[i].test()) {
6273 scheduleDrain = types[i].install(nextTick);
6274 break;
6275 }
6276}
6277// v8 likes predictible objects
6278function Item(fun, array) {
6279 this.fun = fun;
6280 this.array = array;
6281}
6282Item.prototype.run = function () {
6283 var fun = this.fun;
6284 var array = this.array;
6285 switch (array.length) {
6286 case 0:
6287 return fun();
6288 case 1:
6289 return fun(array[0]);
6290 case 2:
6291 return fun(array[0], array[1]);
6292 case 3:
6293 return fun(array[0], array[1], array[2]);
6294 default:
6295 return fun.apply(null, array);
6296 }
6297
6298};
6299module.exports = immediate;
6300function immediate(task) {
6301 var args = new Array(arguments.length - 1);
6302 if (arguments.length > 1) {
6303 for (var i = 1; i < arguments.length; i++) {
6304 args[i - 1] = arguments[i];
6305 }
6306 }
6307 queue.push(new Item(task, args));
6308 if (!scheduled && !draining) {
6309 scheduled = true;
6310 scheduleDrain();
6311 }
6312}
6313
6314},{"25":25,"26":26,"27":27,"28":28,"29":29,"7":7}],25:[function(_dereq_,module,exports){
6315(function (global){(function (){
6316'use strict';
6317
6318exports.test = function () {
6319 if (global.setImmediate) {
6320 // we can only get here in IE10
6321 // which doesn't handel postMessage well
6322 return false;
6323 }
6324 return typeof global.MessageChannel !== 'undefined';
6325};
6326
6327exports.install = function (func) {
6328 var channel = new global.MessageChannel();
6329 channel.port1.onmessage = func;
6330 return function () {
6331 channel.port2.postMessage(0);
6332 };
6333};
6334}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6335},{}],26:[function(_dereq_,module,exports){
6336(function (global){(function (){
6337'use strict';
6338//based off rsvp https://github.com/tildeio/rsvp.js
6339//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
6340//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
6341
6342var Mutation = global.MutationObserver || global.WebKitMutationObserver;
6343
6344exports.test = function () {
6345 return Mutation;
6346};
6347
6348exports.install = function (handle) {
6349 var called = 0;
6350 var observer = new Mutation(handle);
6351 var element = global.document.createTextNode('');
6352 observer.observe(element, {
6353 characterData: true
6354 });
6355 return function () {
6356 element.data = (called = ++called % 2);
6357 };
6358};
6359}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6360},{}],27:[function(_dereq_,module,exports){
6361(function (global){(function (){
6362'use strict';
6363exports.test = function () {
6364 return typeof global.queueMicrotask === 'function';
6365};
6366
6367exports.install = function (func) {
6368 return function () {
6369 global.queueMicrotask(func);
6370 };
6371};
6372
6373}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6374},{}],28:[function(_dereq_,module,exports){
6375(function (global){(function (){
6376'use strict';
6377
6378exports.test = function () {
6379 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
6380};
6381
6382exports.install = function (handle) {
6383 return function () {
6384
6385 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
6386 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
6387 var scriptEl = global.document.createElement('script');
6388 scriptEl.onreadystatechange = function () {
6389 handle();
6390
6391 scriptEl.onreadystatechange = null;
6392 scriptEl.parentNode.removeChild(scriptEl);
6393 scriptEl = null;
6394 };
6395 global.document.documentElement.appendChild(scriptEl);
6396
6397 return handle;
6398 };
6399};
6400}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6401},{}],29:[function(_dereq_,module,exports){
6402'use strict';
6403exports.test = function () {
6404 return true;
6405};
6406
6407exports.install = function (t) {
6408 return function () {
6409 setTimeout(t, 0);
6410 };
6411};
6412},{}],30:[function(_dereq_,module,exports){
6413if (typeof Object.create === 'function') {
6414 // implementation from standard node.js 'util' module
6415 module.exports = function inherits(ctor, superCtor) {
6416 if (superCtor) {
6417 ctor.super_ = superCtor
6418 ctor.prototype = Object.create(superCtor.prototype, {
6419 constructor: {
6420 value: ctor,
6421 enumerable: false,
6422 writable: true,
6423 configurable: true
6424 }
6425 })
6426 }
6427 };
6428} else {
6429 // old school shim for old browsers
6430 module.exports = function inherits(ctor, superCtor) {
6431 if (superCtor) {
6432 ctor.super_ = superCtor
6433 var TempCtor = function () {}
6434 TempCtor.prototype = superCtor.prototype
6435 ctor.prototype = new TempCtor()
6436 ctor.prototype.constructor = ctor
6437 }
6438 }
6439}
6440
6441},{}],31:[function(_dereq_,module,exports){
6442/*!
6443 * Determine if an object is a Buffer
6444 *
6445 * @author Feross Aboukhadijeh <https://feross.org>
6446 * @license MIT
6447 */
6448
6449// The _isBuffer check is for Safari 5-7 support, because it's missing
6450// Object.prototype.constructor. Remove this eventually
6451module.exports = function (obj) {
6452 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
6453}
6454
6455function isBuffer (obj) {
6456 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
6457}
6458
6459// For Node v0.10 support. Remove this eventually.
6460function isSlowBuffer (obj) {
6461 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
6462}
6463
6464},{}],32:[function(_dereq_,module,exports){
6465var encodings = _dereq_(33)
6466
6467module.exports = Codec
6468
6469function Codec (opts) {
6470 if (!(this instanceof Codec)) {
6471 return new Codec(opts)
6472 }
6473 this.opts = opts || {}
6474 this.encodings = encodings
6475}
6476
6477Codec.prototype._encoding = function (encoding) {
6478 if (typeof encoding === 'string') encoding = encodings[encoding]
6479 if (!encoding) encoding = encodings.id
6480 return encoding
6481}
6482
6483Codec.prototype._keyEncoding = function (opts, batchOpts) {
6484 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
6485 (opts && opts.keyEncoding) ||
6486 this.opts.keyEncoding)
6487}
6488
6489Codec.prototype._valueEncoding = function (opts, batchOpts) {
6490 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
6491 (opts && (opts.valueEncoding || opts.encoding)) ||
6492 (this.opts.valueEncoding || this.opts.encoding))
6493}
6494
6495Codec.prototype.encodeKey = function (key, opts, batchOpts) {
6496 return this._keyEncoding(opts, batchOpts).encode(key)
6497}
6498
6499Codec.prototype.encodeValue = function (value, opts, batchOpts) {
6500 return this._valueEncoding(opts, batchOpts).encode(value)
6501}
6502
6503Codec.prototype.decodeKey = function (key, opts) {
6504 return this._keyEncoding(opts).decode(key)
6505}
6506
6507Codec.prototype.decodeValue = function (value, opts) {
6508 return this._valueEncoding(opts).decode(value)
6509}
6510
6511Codec.prototype.encodeBatch = function (ops, opts) {
6512 var self = this
6513
6514 return ops.map(function (_op) {
6515 var op = {
6516 type: _op.type,
6517 key: self.encodeKey(_op.key, opts, _op)
6518 }
6519 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
6520 if (_op.prefix) op.prefix = _op.prefix
6521 if ('value' in _op) {
6522 op.value = self.encodeValue(_op.value, opts, _op)
6523 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
6524 }
6525 return op
6526 })
6527}
6528
6529var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
6530
6531Codec.prototype.encodeLtgt = function (ltgt) {
6532 var self = this
6533 var ret = {}
6534 Object.keys(ltgt).forEach(function (key) {
6535 ret[key] = ltgtKeys.indexOf(key) > -1
6536 ? self.encodeKey(ltgt[key], ltgt)
6537 : ltgt[key]
6538 })
6539 return ret
6540}
6541
6542Codec.prototype.createStreamDecoder = function (opts) {
6543 var self = this
6544
6545 if (opts.keys && opts.values) {
6546 return function (key, value) {
6547 return {
6548 key: self.decodeKey(key, opts),
6549 value: self.decodeValue(value, opts)
6550 }
6551 }
6552 } else if (opts.keys) {
6553 return function (key) {
6554 return self.decodeKey(key, opts)
6555 }
6556 } else if (opts.values) {
6557 return function (_, value) {
6558 return self.decodeValue(value, opts)
6559 }
6560 } else {
6561 return function () {}
6562 }
6563}
6564
6565Codec.prototype.keyAsBuffer = function (opts) {
6566 return this._keyEncoding(opts).buffer
6567}
6568
6569Codec.prototype.valueAsBuffer = function (opts) {
6570 return this._valueEncoding(opts).buffer
6571}
6572
6573},{"33":33}],33:[function(_dereq_,module,exports){
6574var Buffer = _dereq_(9).Buffer
6575
6576exports.utf8 = exports['utf-8'] = {
6577 encode: function (data) {
6578 return isBinary(data) ? data : String(data)
6579 },
6580 decode: identity,
6581 buffer: false,
6582 type: 'utf8'
6583}
6584
6585exports.json = {
6586 encode: JSON.stringify,
6587 decode: JSON.parse,
6588 buffer: false,
6589 type: 'json'
6590}
6591
6592exports.binary = {
6593 encode: function (data) {
6594 return isBinary(data) ? data : Buffer.from(data)
6595 },
6596 decode: identity,
6597 buffer: true,
6598 type: 'binary'
6599}
6600
6601exports.none = {
6602 encode: identity,
6603 decode: identity,
6604 buffer: false,
6605 type: 'id'
6606}
6607
6608exports.id = exports.none
6609
6610var bufferEncodings = [
6611 'hex',
6612 'ascii',
6613 'base64',
6614 'ucs2',
6615 'ucs-2',
6616 'utf16le',
6617 'utf-16le'
6618]
6619
6620bufferEncodings.forEach(function (type) {
6621 exports[type] = {
6622 encode: function (data) {
6623 return isBinary(data) ? data : Buffer.from(data, type)
6624 },
6625 decode: function (buffer) {
6626 return buffer.toString(type)
6627 },
6628 buffer: true,
6629 type: type
6630 }
6631})
6632
6633function identity (value) {
6634 return value
6635}
6636
6637function isBinary (data) {
6638 return data === undefined || data === null || Buffer.isBuffer(data)
6639}
6640
6641},{"9":9}],34:[function(_dereq_,module,exports){
6642var createError = _dereq_(20).create
6643var LevelUPError = createError('LevelUPError')
6644var NotFoundError = createError('NotFoundError', LevelUPError)
6645
6646NotFoundError.prototype.notFound = true
6647NotFoundError.prototype.status = 404
6648
6649module.exports = {
6650 LevelUPError: LevelUPError,
6651 InitializationError: createError('InitializationError', LevelUPError),
6652 OpenError: createError('OpenError', LevelUPError),
6653 ReadError: createError('ReadError', LevelUPError),
6654 WriteError: createError('WriteError', LevelUPError),
6655 NotFoundError: NotFoundError,
6656 EncodingError: createError('EncodingError', LevelUPError)
6657}
6658
6659},{"20":20}],35:[function(_dereq_,module,exports){
6660var inherits = _dereq_(30)
6661var Readable = _dereq_(50).Readable
6662var extend = _dereq_(134)
6663
6664module.exports = ReadStream
6665inherits(ReadStream, Readable)
6666
6667function ReadStream (iterator, options) {
6668 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
6669 options = options || {}
6670 Readable.call(this, extend(options, {
6671 objectMode: true
6672 }))
6673 this._iterator = iterator
6674 this._options = options
6675 this.on('end', this.destroy.bind(this, null, null))
6676}
6677
6678ReadStream.prototype._read = function () {
6679 var self = this
6680 var options = this._options
6681 if (this.destroyed) return
6682
6683 this._iterator.next(function (err, key, value) {
6684 if (self.destroyed) return
6685 if (err) return self.destroy(err)
6686
6687 if (key === undefined && value === undefined) {
6688 self.push(null)
6689 } else if (options.keys !== false && options.values === false) {
6690 self.push(key)
6691 } else if (options.keys === false && options.values !== false) {
6692 self.push(value)
6693 } else {
6694 self.push({ key: key, value: value })
6695 }
6696 })
6697}
6698
6699ReadStream.prototype._destroy = function (err, callback) {
6700 this._iterator.end(function (err2) {
6701 callback(err || err2)
6702 })
6703}
6704
6705},{"134":134,"30":30,"50":50}],36:[function(_dereq_,module,exports){
6706'use strict';
6707
6708function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
6709
6710var codes = {};
6711
6712function createErrorType(code, message, Base) {
6713 if (!Base) {
6714 Base = Error;
6715 }
6716
6717 function getMessage(arg1, arg2, arg3) {
6718 if (typeof message === 'string') {
6719 return message;
6720 } else {
6721 return message(arg1, arg2, arg3);
6722 }
6723 }
6724
6725 var NodeError =
6726 /*#__PURE__*/
6727 function (_Base) {
6728 _inheritsLoose(NodeError, _Base);
6729
6730 function NodeError(arg1, arg2, arg3) {
6731 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
6732 }
6733
6734 return NodeError;
6735 }(Base);
6736
6737 NodeError.prototype.name = Base.name;
6738 NodeError.prototype.code = code;
6739 codes[code] = NodeError;
6740} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
6741
6742
6743function oneOf(expected, thing) {
6744 if (Array.isArray(expected)) {
6745 var len = expected.length;
6746 expected = expected.map(function (i) {
6747 return String(i);
6748 });
6749
6750 if (len > 2) {
6751 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
6752 } else if (len === 2) {
6753 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
6754 } else {
6755 return "of ".concat(thing, " ").concat(expected[0]);
6756 }
6757 } else {
6758 return "of ".concat(thing, " ").concat(String(expected));
6759 }
6760} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
6761
6762
6763function startsWith(str, search, pos) {
6764 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
6765} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
6766
6767
6768function endsWith(str, search, this_len) {
6769 if (this_len === undefined || this_len > str.length) {
6770 this_len = str.length;
6771 }
6772
6773 return str.substring(this_len - search.length, this_len) === search;
6774} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
6775
6776
6777function includes(str, search, start) {
6778 if (typeof start !== 'number') {
6779 start = 0;
6780 }
6781
6782 if (start + search.length > str.length) {
6783 return false;
6784 } else {
6785 return str.indexOf(search, start) !== -1;
6786 }
6787}
6788
6789createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
6790 return 'The value "' + value + '" is invalid for option "' + name + '"';
6791}, TypeError);
6792createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
6793 // determiner: 'must be' or 'must not be'
6794 var determiner;
6795
6796 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
6797 determiner = 'must not be';
6798 expected = expected.replace(/^not /, '');
6799 } else {
6800 determiner = 'must be';
6801 }
6802
6803 var msg;
6804
6805 if (endsWith(name, ' argument')) {
6806 // For cases like 'first argument'
6807 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6808 } else {
6809 var type = includes(name, '.') ? 'property' : 'argument';
6810 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6811 }
6812
6813 msg += ". Received type ".concat(typeof actual);
6814 return msg;
6815}, TypeError);
6816createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
6817createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
6818 return 'The ' + name + ' method is not implemented';
6819});
6820createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
6821createErrorType('ERR_STREAM_DESTROYED', function (name) {
6822 return 'Cannot call ' + name + ' after a stream was destroyed';
6823});
6824createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
6825createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
6826createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
6827createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
6828createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
6829 return 'Unknown encoding: ' + arg;
6830}, TypeError);
6831createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
6832module.exports.codes = codes;
6833
6834},{}],37:[function(_dereq_,module,exports){
6835(function (process){(function (){
6836// Copyright Joyent, Inc. and other Node contributors.
6837//
6838// Permission is hereby granted, free of charge, to any person obtaining a
6839// copy of this software and associated documentation files (the
6840// "Software"), to deal in the Software without restriction, including
6841// without limitation the rights to use, copy, modify, merge, publish,
6842// distribute, sublicense, and/or sell copies of the Software, and to permit
6843// persons to whom the Software is furnished to do so, subject to the
6844// following conditions:
6845//
6846// The above copyright notice and this permission notice shall be included
6847// in all copies or substantial portions of the Software.
6848//
6849// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6850// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6851// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6852// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6853// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6854// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6855// USE OR OTHER DEALINGS IN THE SOFTWARE.
6856// a duplex stream is just a stream that is both readable and writable.
6857// Since JS doesn't have multiple prototypal inheritance, this class
6858// prototypally inherits from Readable, and then parasitically from
6859// Writable.
6860'use strict';
6861/*<replacement>*/
6862
6863var objectKeys = Object.keys || function (obj) {
6864 var keys = [];
6865
6866 for (var key in obj) {
6867 keys.push(key);
6868 }
6869
6870 return keys;
6871};
6872/*</replacement>*/
6873
6874
6875module.exports = Duplex;
6876
6877var Readable = _dereq_(39);
6878
6879var Writable = _dereq_(41);
6880
6881_dereq_(30)(Duplex, Readable);
6882
6883{
6884 // Allow the keys array to be GC'ed.
6885 var keys = objectKeys(Writable.prototype);
6886
6887 for (var v = 0; v < keys.length; v++) {
6888 var method = keys[v];
6889 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
6890 }
6891}
6892
6893function Duplex(options) {
6894 if (!(this instanceof Duplex)) return new Duplex(options);
6895 Readable.call(this, options);
6896 Writable.call(this, options);
6897 this.allowHalfOpen = true;
6898
6899 if (options) {
6900 if (options.readable === false) this.readable = false;
6901 if (options.writable === false) this.writable = false;
6902
6903 if (options.allowHalfOpen === false) {
6904 this.allowHalfOpen = false;
6905 this.once('end', onend);
6906 }
6907 }
6908}
6909
6910Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
6911 // making it explicit this property is not enumerable
6912 // because otherwise some prototype manipulation in
6913 // userland will fail
6914 enumerable: false,
6915 get: function get() {
6916 return this._writableState.highWaterMark;
6917 }
6918});
6919Object.defineProperty(Duplex.prototype, 'writableBuffer', {
6920 // making it explicit this property is not enumerable
6921 // because otherwise some prototype manipulation in
6922 // userland will fail
6923 enumerable: false,
6924 get: function get() {
6925 return this._writableState && this._writableState.getBuffer();
6926 }
6927});
6928Object.defineProperty(Duplex.prototype, 'writableLength', {
6929 // making it explicit this property is not enumerable
6930 // because otherwise some prototype manipulation in
6931 // userland will fail
6932 enumerable: false,
6933 get: function get() {
6934 return this._writableState.length;
6935 }
6936}); // the no-half-open enforcer
6937
6938function onend() {
6939 // If the writable side ended, then we're ok.
6940 if (this._writableState.ended) return; // no more data can be written.
6941 // But allow more writes to happen in this tick.
6942
6943 process.nextTick(onEndNT, this);
6944}
6945
6946function onEndNT(self) {
6947 self.end();
6948}
6949
6950Object.defineProperty(Duplex.prototype, 'destroyed', {
6951 // making it explicit this property is not enumerable
6952 // because otherwise some prototype manipulation in
6953 // userland will fail
6954 enumerable: false,
6955 get: function get() {
6956 if (this._readableState === undefined || this._writableState === undefined) {
6957 return false;
6958 }
6959
6960 return this._readableState.destroyed && this._writableState.destroyed;
6961 },
6962 set: function set(value) {
6963 // we ignore the value if the stream
6964 // has not been initialized yet
6965 if (this._readableState === undefined || this._writableState === undefined) {
6966 return;
6967 } // backward compatibility, the user is explicitly
6968 // managing destroyed
6969
6970
6971 this._readableState.destroyed = value;
6972 this._writableState.destroyed = value;
6973 }
6974});
6975}).call(this)}).call(this,_dereq_(67))
6976},{"30":30,"39":39,"41":41,"67":67}],38:[function(_dereq_,module,exports){
6977// Copyright Joyent, Inc. and other Node contributors.
6978//
6979// Permission is hereby granted, free of charge, to any person obtaining a
6980// copy of this software and associated documentation files (the
6981// "Software"), to deal in the Software without restriction, including
6982// without limitation the rights to use, copy, modify, merge, publish,
6983// distribute, sublicense, and/or sell copies of the Software, and to permit
6984// persons to whom the Software is furnished to do so, subject to the
6985// following conditions:
6986//
6987// The above copyright notice and this permission notice shall be included
6988// in all copies or substantial portions of the Software.
6989//
6990// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6991// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6992// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6993// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6994// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6995// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6996// USE OR OTHER DEALINGS IN THE SOFTWARE.
6997// a passthrough stream.
6998// basically just the most minimal sort of Transform stream.
6999// Every written chunk gets output as-is.
7000'use strict';
7001
7002module.exports = PassThrough;
7003
7004var Transform = _dereq_(40);
7005
7006_dereq_(30)(PassThrough, Transform);
7007
7008function PassThrough(options) {
7009 if (!(this instanceof PassThrough)) return new PassThrough(options);
7010 Transform.call(this, options);
7011}
7012
7013PassThrough.prototype._transform = function (chunk, encoding, cb) {
7014 cb(null, chunk);
7015};
7016},{"30":30,"40":40}],39:[function(_dereq_,module,exports){
7017(function (process,global){(function (){
7018// Copyright Joyent, Inc. and other Node contributors.
7019//
7020// Permission is hereby granted, free of charge, to any person obtaining a
7021// copy of this software and associated documentation files (the
7022// "Software"), to deal in the Software without restriction, including
7023// without limitation the rights to use, copy, modify, merge, publish,
7024// distribute, sublicense, and/or sell copies of the Software, and to permit
7025// persons to whom the Software is furnished to do so, subject to the
7026// following conditions:
7027//
7028// The above copyright notice and this permission notice shall be included
7029// in all copies or substantial portions of the Software.
7030//
7031// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7032// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7033// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7034// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7035// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7036// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7037// USE OR OTHER DEALINGS IN THE SOFTWARE.
7038'use strict';
7039
7040module.exports = Readable;
7041/*<replacement>*/
7042
7043var Duplex;
7044/*</replacement>*/
7045
7046Readable.ReadableState = ReadableState;
7047/*<replacement>*/
7048
7049var EE = _dereq_(21).EventEmitter;
7050
7051var EElistenerCount = function EElistenerCount(emitter, type) {
7052 return emitter.listeners(type).length;
7053};
7054/*</replacement>*/
7055
7056/*<replacement>*/
7057
7058
7059var Stream = _dereq_(49);
7060/*</replacement>*/
7061
7062
7063var Buffer = _dereq_(9).Buffer;
7064
7065var OurUint8Array = global.Uint8Array || function () {};
7066
7067function _uint8ArrayToBuffer(chunk) {
7068 return Buffer.from(chunk);
7069}
7070
7071function _isUint8Array(obj) {
7072 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
7073}
7074/*<replacement>*/
7075
7076
7077var debugUtil = _dereq_(7);
7078
7079var debug;
7080
7081if (debugUtil && debugUtil.debuglog) {
7082 debug = debugUtil.debuglog('stream');
7083} else {
7084 debug = function debug() {};
7085}
7086/*</replacement>*/
7087
7088
7089var BufferList = _dereq_(43);
7090
7091var destroyImpl = _dereq_(44);
7092
7093var _require = _dereq_(48),
7094 getHighWaterMark = _require.getHighWaterMark;
7095
7096var _require$codes = _dereq_(36).codes,
7097 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
7098 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
7099 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7100 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
7101
7102
7103var StringDecoder;
7104var createReadableStreamAsyncIterator;
7105var from;
7106
7107_dereq_(30)(Readable, Stream);
7108
7109var errorOrDestroy = destroyImpl.errorOrDestroy;
7110var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
7111
7112function prependListener(emitter, event, fn) {
7113 // Sadly this is not cacheable as some libraries bundle their own
7114 // event emitter implementation with them.
7115 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
7116 // userland ones. NEVER DO THIS. This is here only because this code needs
7117 // to continue to work with older versions of Node.js that do not include
7118 // the prependListener() method. The goal is to eventually remove this hack.
7119
7120 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]];
7121}
7122
7123function ReadableState(options, stream, isDuplex) {
7124 Duplex = Duplex || _dereq_(37);
7125 options = options || {}; // Duplex streams are both readable and writable, but share
7126 // the same options object.
7127 // However, some cases require setting options to different
7128 // values for the readable and the writable sides of the duplex stream.
7129 // These options can be provided separately as readableXXX and writableXXX.
7130
7131 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
7132 // make all the buffer merging and length checks go away
7133
7134 this.objectMode = !!options.objectMode;
7135 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
7136 // Note: 0 is a valid value, means "don't call _read preemptively ever"
7137
7138 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
7139 // linked list can remove elements from the beginning faster than
7140 // array.shift()
7141
7142 this.buffer = new BufferList();
7143 this.length = 0;
7144 this.pipes = null;
7145 this.pipesCount = 0;
7146 this.flowing = null;
7147 this.ended = false;
7148 this.endEmitted = false;
7149 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
7150 // immediately, or on a later tick. We set this to true at first, because
7151 // any actions that shouldn't happen until "later" should generally also
7152 // not happen before the first read call.
7153
7154 this.sync = true; // whenever we return null, then we set a flag to say
7155 // that we're awaiting a 'readable' event emission.
7156
7157 this.needReadable = false;
7158 this.emittedReadable = false;
7159 this.readableListening = false;
7160 this.resumeScheduled = false;
7161 this.paused = true; // Should close be emitted on destroy. Defaults to true.
7162
7163 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
7164
7165 this.autoDestroy = !!options.autoDestroy; // has it been destroyed
7166
7167 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
7168 // encoding is 'binary' so we have to make this configurable.
7169 // Everything else in the universe uses 'utf8', though.
7170
7171 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
7172
7173 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
7174
7175 this.readingMore = false;
7176 this.decoder = null;
7177 this.encoding = null;
7178
7179 if (options.encoding) {
7180 if (!StringDecoder) StringDecoder = _dereq_(96).StringDecoder;
7181 this.decoder = new StringDecoder(options.encoding);
7182 this.encoding = options.encoding;
7183 }
7184}
7185
7186function Readable(options) {
7187 Duplex = Duplex || _dereq_(37);
7188 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
7189 // the ReadableState constructor, at least with V8 6.5
7190
7191 var isDuplex = this instanceof Duplex;
7192 this._readableState = new ReadableState(options, this, isDuplex); // legacy
7193
7194 this.readable = true;
7195
7196 if (options) {
7197 if (typeof options.read === 'function') this._read = options.read;
7198 if (typeof options.destroy === 'function') this._destroy = options.destroy;
7199 }
7200
7201 Stream.call(this);
7202}
7203
7204Object.defineProperty(Readable.prototype, 'destroyed', {
7205 // making it explicit this property is not enumerable
7206 // because otherwise some prototype manipulation in
7207 // userland will fail
7208 enumerable: false,
7209 get: function get() {
7210 if (this._readableState === undefined) {
7211 return false;
7212 }
7213
7214 return this._readableState.destroyed;
7215 },
7216 set: function set(value) {
7217 // we ignore the value if the stream
7218 // has not been initialized yet
7219 if (!this._readableState) {
7220 return;
7221 } // backward compatibility, the user is explicitly
7222 // managing destroyed
7223
7224
7225 this._readableState.destroyed = value;
7226 }
7227});
7228Readable.prototype.destroy = destroyImpl.destroy;
7229Readable.prototype._undestroy = destroyImpl.undestroy;
7230
7231Readable.prototype._destroy = function (err, cb) {
7232 cb(err);
7233}; // Manually shove something into the read() buffer.
7234// This returns true if the highWaterMark has not been hit yet,
7235// similar to how Writable.write() returns true if you should
7236// write() some more.
7237
7238
7239Readable.prototype.push = function (chunk, encoding) {
7240 var state = this._readableState;
7241 var skipChunkCheck;
7242
7243 if (!state.objectMode) {
7244 if (typeof chunk === 'string') {
7245 encoding = encoding || state.defaultEncoding;
7246
7247 if (encoding !== state.encoding) {
7248 chunk = Buffer.from(chunk, encoding);
7249 encoding = '';
7250 }
7251
7252 skipChunkCheck = true;
7253 }
7254 } else {
7255 skipChunkCheck = true;
7256 }
7257
7258 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
7259}; // Unshift should *always* be something directly out of read()
7260
7261
7262Readable.prototype.unshift = function (chunk) {
7263 return readableAddChunk(this, chunk, null, true, false);
7264};
7265
7266function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
7267 debug('readableAddChunk', chunk);
7268 var state = stream._readableState;
7269
7270 if (chunk === null) {
7271 state.reading = false;
7272 onEofChunk(stream, state);
7273 } else {
7274 var er;
7275 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
7276
7277 if (er) {
7278 errorOrDestroy(stream, er);
7279 } else if (state.objectMode || chunk && chunk.length > 0) {
7280 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
7281 chunk = _uint8ArrayToBuffer(chunk);
7282 }
7283
7284 if (addToFront) {
7285 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
7286 } else if (state.ended) {
7287 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
7288 } else if (state.destroyed) {
7289 return false;
7290 } else {
7291 state.reading = false;
7292
7293 if (state.decoder && !encoding) {
7294 chunk = state.decoder.write(chunk);
7295 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
7296 } else {
7297 addChunk(stream, state, chunk, false);
7298 }
7299 }
7300 } else if (!addToFront) {
7301 state.reading = false;
7302 maybeReadMore(stream, state);
7303 }
7304 } // We can push more data if we are below the highWaterMark.
7305 // Also, if we have no data yet, we can stand some more bytes.
7306 // This is to work around cases where hwm=0, such as the repl.
7307
7308
7309 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
7310}
7311
7312function addChunk(stream, state, chunk, addToFront) {
7313 if (state.flowing && state.length === 0 && !state.sync) {
7314 state.awaitDrain = 0;
7315 stream.emit('data', chunk);
7316 } else {
7317 // update the buffer info.
7318 state.length += state.objectMode ? 1 : chunk.length;
7319 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
7320 if (state.needReadable) emitReadable(stream);
7321 }
7322
7323 maybeReadMore(stream, state);
7324}
7325
7326function chunkInvalid(state, chunk) {
7327 var er;
7328
7329 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
7330 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
7331 }
7332
7333 return er;
7334}
7335
7336Readable.prototype.isPaused = function () {
7337 return this._readableState.flowing === false;
7338}; // backwards compatibility.
7339
7340
7341Readable.prototype.setEncoding = function (enc) {
7342 if (!StringDecoder) StringDecoder = _dereq_(96).StringDecoder;
7343 var decoder = new StringDecoder(enc);
7344 this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
7345
7346 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
7347
7348 var p = this._readableState.buffer.head;
7349 var content = '';
7350
7351 while (p !== null) {
7352 content += decoder.write(p.data);
7353 p = p.next;
7354 }
7355
7356 this._readableState.buffer.clear();
7357
7358 if (content !== '') this._readableState.buffer.push(content);
7359 this._readableState.length = content.length;
7360 return this;
7361}; // Don't raise the hwm > 1GB
7362
7363
7364var MAX_HWM = 0x40000000;
7365
7366function computeNewHighWaterMark(n) {
7367 if (n >= MAX_HWM) {
7368 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
7369 n = MAX_HWM;
7370 } else {
7371 // Get the next highest power of 2 to prevent increasing hwm excessively in
7372 // tiny amounts
7373 n--;
7374 n |= n >>> 1;
7375 n |= n >>> 2;
7376 n |= n >>> 4;
7377 n |= n >>> 8;
7378 n |= n >>> 16;
7379 n++;
7380 }
7381
7382 return n;
7383} // This function is designed to be inlinable, so please take care when making
7384// changes to the function body.
7385
7386
7387function howMuchToRead(n, state) {
7388 if (n <= 0 || state.length === 0 && state.ended) return 0;
7389 if (state.objectMode) return 1;
7390
7391 if (n !== n) {
7392 // Only flow one buffer at a time
7393 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
7394 } // If we're asking for more than the current hwm, then raise the hwm.
7395
7396
7397 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
7398 if (n <= state.length) return n; // Don't have enough
7399
7400 if (!state.ended) {
7401 state.needReadable = true;
7402 return 0;
7403 }
7404
7405 return state.length;
7406} // you can override either this method, or the async _read(n) below.
7407
7408
7409Readable.prototype.read = function (n) {
7410 debug('read', n);
7411 n = parseInt(n, 10);
7412 var state = this._readableState;
7413 var nOrig = n;
7414 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
7415 // already have a bunch of data in the buffer, then just trigger
7416 // the 'readable' event and move on.
7417
7418 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
7419 debug('read: emitReadable', state.length, state.ended);
7420 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
7421 return null;
7422 }
7423
7424 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
7425
7426 if (n === 0 && state.ended) {
7427 if (state.length === 0) endReadable(this);
7428 return null;
7429 } // All the actual chunk generation logic needs to be
7430 // *below* the call to _read. The reason is that in certain
7431 // synthetic stream cases, such as passthrough streams, _read
7432 // may be a completely synchronous operation which may change
7433 // the state of the read buffer, providing enough data when
7434 // before there was *not* enough.
7435 //
7436 // So, the steps are:
7437 // 1. Figure out what the state of things will be after we do
7438 // a read from the buffer.
7439 //
7440 // 2. If that resulting state will trigger a _read, then call _read.
7441 // Note that this may be asynchronous, or synchronous. Yes, it is
7442 // deeply ugly to write APIs this way, but that still doesn't mean
7443 // that the Readable class should behave improperly, as streams are
7444 // designed to be sync/async agnostic.
7445 // Take note if the _read call is sync or async (ie, if the read call
7446 // has returned yet), so that we know whether or not it's safe to emit
7447 // 'readable' etc.
7448 //
7449 // 3. Actually pull the requested chunks out of the buffer and return.
7450 // if we need a readable event, then we need to do some reading.
7451
7452
7453 var doRead = state.needReadable;
7454 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
7455
7456 if (state.length === 0 || state.length - n < state.highWaterMark) {
7457 doRead = true;
7458 debug('length less than watermark', doRead);
7459 } // however, if we've ended, then there's no point, and if we're already
7460 // reading, then it's unnecessary.
7461
7462
7463 if (state.ended || state.reading) {
7464 doRead = false;
7465 debug('reading or ended', doRead);
7466 } else if (doRead) {
7467 debug('do read');
7468 state.reading = true;
7469 state.sync = true; // if the length is currently zero, then we *need* a readable event.
7470
7471 if (state.length === 0) state.needReadable = true; // call internal read method
7472
7473 this._read(state.highWaterMark);
7474
7475 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
7476 // and we need to re-evaluate how much data we can return to the user.
7477
7478 if (!state.reading) n = howMuchToRead(nOrig, state);
7479 }
7480
7481 var ret;
7482 if (n > 0) ret = fromList(n, state);else ret = null;
7483
7484 if (ret === null) {
7485 state.needReadable = state.length <= state.highWaterMark;
7486 n = 0;
7487 } else {
7488 state.length -= n;
7489 state.awaitDrain = 0;
7490 }
7491
7492 if (state.length === 0) {
7493 // If we have nothing in the buffer, then we want to know
7494 // as soon as we *do* get something into the buffer.
7495 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
7496
7497 if (nOrig !== n && state.ended) endReadable(this);
7498 }
7499
7500 if (ret !== null) this.emit('data', ret);
7501 return ret;
7502};
7503
7504function onEofChunk(stream, state) {
7505 debug('onEofChunk');
7506 if (state.ended) return;
7507
7508 if (state.decoder) {
7509 var chunk = state.decoder.end();
7510
7511 if (chunk && chunk.length) {
7512 state.buffer.push(chunk);
7513 state.length += state.objectMode ? 1 : chunk.length;
7514 }
7515 }
7516
7517 state.ended = true;
7518
7519 if (state.sync) {
7520 // if we are sync, wait until next tick to emit the data.
7521 // Otherwise we risk emitting data in the flow()
7522 // the readable code triggers during a read() call
7523 emitReadable(stream);
7524 } else {
7525 // emit 'readable' now to make sure it gets picked up.
7526 state.needReadable = false;
7527
7528 if (!state.emittedReadable) {
7529 state.emittedReadable = true;
7530 emitReadable_(stream);
7531 }
7532 }
7533} // Don't emit readable right away in sync mode, because this can trigger
7534// another read() call => stack overflow. This way, it might trigger
7535// a nextTick recursion warning, but that's not so bad.
7536
7537
7538function emitReadable(stream) {
7539 var state = stream._readableState;
7540 debug('emitReadable', state.needReadable, state.emittedReadable);
7541 state.needReadable = false;
7542
7543 if (!state.emittedReadable) {
7544 debug('emitReadable', state.flowing);
7545 state.emittedReadable = true;
7546 process.nextTick(emitReadable_, stream);
7547 }
7548}
7549
7550function emitReadable_(stream) {
7551 var state = stream._readableState;
7552 debug('emitReadable_', state.destroyed, state.length, state.ended);
7553
7554 if (!state.destroyed && (state.length || state.ended)) {
7555 stream.emit('readable');
7556 state.emittedReadable = false;
7557 } // The stream needs another readable event if
7558 // 1. It is not flowing, as the flow mechanism will take
7559 // care of it.
7560 // 2. It is not ended.
7561 // 3. It is below the highWaterMark, so we can schedule
7562 // another readable later.
7563
7564
7565 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
7566 flow(stream);
7567} // at this point, the user has presumably seen the 'readable' event,
7568// and called read() to consume some data. that may have triggered
7569// in turn another _read(n) call, in which case reading = true if
7570// it's in progress.
7571// However, if we're not ended, or reading, and the length < hwm,
7572// then go ahead and try to read some more preemptively.
7573
7574
7575function maybeReadMore(stream, state) {
7576 if (!state.readingMore) {
7577 state.readingMore = true;
7578 process.nextTick(maybeReadMore_, stream, state);
7579 }
7580}
7581
7582function maybeReadMore_(stream, state) {
7583 // Attempt to read more data if we should.
7584 //
7585 // The conditions for reading more data are (one of):
7586 // - Not enough data buffered (state.length < state.highWaterMark). The loop
7587 // is responsible for filling the buffer with enough data if such data
7588 // is available. If highWaterMark is 0 and we are not in the flowing mode
7589 // we should _not_ attempt to buffer any extra data. We'll get more data
7590 // when the stream consumer calls read() instead.
7591 // - No data in the buffer, and the stream is in flowing mode. In this mode
7592 // the loop below is responsible for ensuring read() is called. Failing to
7593 // call read here would abort the flow and there's no other mechanism for
7594 // continuing the flow if the stream consumer has just subscribed to the
7595 // 'data' event.
7596 //
7597 // In addition to the above conditions to keep reading data, the following
7598 // conditions prevent the data from being read:
7599 // - The stream has ended (state.ended).
7600 // - There is already a pending 'read' operation (state.reading). This is a
7601 // case where the the stream has called the implementation defined _read()
7602 // method, but they are processing the call asynchronously and have _not_
7603 // called push() with new data. In this case we skip performing more
7604 // read()s. The execution ends in this method again after the _read() ends
7605 // up calling push() with more data.
7606 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
7607 var len = state.length;
7608 debug('maybeReadMore read 0');
7609 stream.read(0);
7610 if (len === state.length) // didn't get any data, stop spinning.
7611 break;
7612 }
7613
7614 state.readingMore = false;
7615} // abstract method. to be overridden in specific implementation classes.
7616// call cb(er, data) where data is <= n in length.
7617// for virtual (non-string, non-buffer) streams, "length" is somewhat
7618// arbitrary, and perhaps not very meaningful.
7619
7620
7621Readable.prototype._read = function (n) {
7622 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
7623};
7624
7625Readable.prototype.pipe = function (dest, pipeOpts) {
7626 var src = this;
7627 var state = this._readableState;
7628
7629 switch (state.pipesCount) {
7630 case 0:
7631 state.pipes = dest;
7632 break;
7633
7634 case 1:
7635 state.pipes = [state.pipes, dest];
7636 break;
7637
7638 default:
7639 state.pipes.push(dest);
7640 break;
7641 }
7642
7643 state.pipesCount += 1;
7644 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
7645 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
7646 var endFn = doEnd ? onend : unpipe;
7647 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
7648 dest.on('unpipe', onunpipe);
7649
7650 function onunpipe(readable, unpipeInfo) {
7651 debug('onunpipe');
7652
7653 if (readable === src) {
7654 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
7655 unpipeInfo.hasUnpiped = true;
7656 cleanup();
7657 }
7658 }
7659 }
7660
7661 function onend() {
7662 debug('onend');
7663 dest.end();
7664 } // when the dest drains, it reduces the awaitDrain counter
7665 // on the source. This would be more elegant with a .once()
7666 // handler in flow(), but adding and removing repeatedly is
7667 // too slow.
7668
7669
7670 var ondrain = pipeOnDrain(src);
7671 dest.on('drain', ondrain);
7672 var cleanedUp = false;
7673
7674 function cleanup() {
7675 debug('cleanup'); // cleanup event handlers once the pipe is broken
7676
7677 dest.removeListener('close', onclose);
7678 dest.removeListener('finish', onfinish);
7679 dest.removeListener('drain', ondrain);
7680 dest.removeListener('error', onerror);
7681 dest.removeListener('unpipe', onunpipe);
7682 src.removeListener('end', onend);
7683 src.removeListener('end', unpipe);
7684 src.removeListener('data', ondata);
7685 cleanedUp = true; // if the reader is waiting for a drain event from this
7686 // specific writer, then it would cause it to never start
7687 // flowing again.
7688 // So, if this is awaiting a drain, then we just call it now.
7689 // If we don't know, then assume that we are waiting for one.
7690
7691 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
7692 }
7693
7694 src.on('data', ondata);
7695
7696 function ondata(chunk) {
7697 debug('ondata');
7698 var ret = dest.write(chunk);
7699 debug('dest.write', ret);
7700
7701 if (ret === false) {
7702 // If the user unpiped during `dest.write()`, it is possible
7703 // to get stuck in a permanently paused state if that write
7704 // also returned false.
7705 // => Check whether `dest` is still a piping destination.
7706 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
7707 debug('false write response, pause', state.awaitDrain);
7708 state.awaitDrain++;
7709 }
7710
7711 src.pause();
7712 }
7713 } // if the dest has an error, then stop piping into it.
7714 // however, don't suppress the throwing behavior for this.
7715
7716
7717 function onerror(er) {
7718 debug('onerror', er);
7719 unpipe();
7720 dest.removeListener('error', onerror);
7721 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
7722 } // Make sure our error handler is attached before userland ones.
7723
7724
7725 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
7726
7727 function onclose() {
7728 dest.removeListener('finish', onfinish);
7729 unpipe();
7730 }
7731
7732 dest.once('close', onclose);
7733
7734 function onfinish() {
7735 debug('onfinish');
7736 dest.removeListener('close', onclose);
7737 unpipe();
7738 }
7739
7740 dest.once('finish', onfinish);
7741
7742 function unpipe() {
7743 debug('unpipe');
7744 src.unpipe(dest);
7745 } // tell the dest that it's being piped to
7746
7747
7748 dest.emit('pipe', src); // start the flow if it hasn't been started already.
7749
7750 if (!state.flowing) {
7751 debug('pipe resume');
7752 src.resume();
7753 }
7754
7755 return dest;
7756};
7757
7758function pipeOnDrain(src) {
7759 return function pipeOnDrainFunctionResult() {
7760 var state = src._readableState;
7761 debug('pipeOnDrain', state.awaitDrain);
7762 if (state.awaitDrain) state.awaitDrain--;
7763
7764 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
7765 state.flowing = true;
7766 flow(src);
7767 }
7768 };
7769}
7770
7771Readable.prototype.unpipe = function (dest) {
7772 var state = this._readableState;
7773 var unpipeInfo = {
7774 hasUnpiped: false
7775 }; // if we're not piping anywhere, then do nothing.
7776
7777 if (state.pipesCount === 0) return this; // just one destination. most common case.
7778
7779 if (state.pipesCount === 1) {
7780 // passed in one, but it's not the right one.
7781 if (dest && dest !== state.pipes) return this;
7782 if (!dest) dest = state.pipes; // got a match.
7783
7784 state.pipes = null;
7785 state.pipesCount = 0;
7786 state.flowing = false;
7787 if (dest) dest.emit('unpipe', this, unpipeInfo);
7788 return this;
7789 } // slow case. multiple pipe destinations.
7790
7791
7792 if (!dest) {
7793 // remove all.
7794 var dests = state.pipes;
7795 var len = state.pipesCount;
7796 state.pipes = null;
7797 state.pipesCount = 0;
7798 state.flowing = false;
7799
7800 for (var i = 0; i < len; i++) {
7801 dests[i].emit('unpipe', this, {
7802 hasUnpiped: false
7803 });
7804 }
7805
7806 return this;
7807 } // try to find the right one.
7808
7809
7810 var index = indexOf(state.pipes, dest);
7811 if (index === -1) return this;
7812 state.pipes.splice(index, 1);
7813 state.pipesCount -= 1;
7814 if (state.pipesCount === 1) state.pipes = state.pipes[0];
7815 dest.emit('unpipe', this, unpipeInfo);
7816 return this;
7817}; // set up data events if they are asked for
7818// Ensure readable listeners eventually get something
7819
7820
7821Readable.prototype.on = function (ev, fn) {
7822 var res = Stream.prototype.on.call(this, ev, fn);
7823 var state = this._readableState;
7824
7825 if (ev === 'data') {
7826 // update readableListening so that resume() may be a no-op
7827 // a few lines down. This is needed to support once('readable').
7828 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
7829
7830 if (state.flowing !== false) this.resume();
7831 } else if (ev === 'readable') {
7832 if (!state.endEmitted && !state.readableListening) {
7833 state.readableListening = state.needReadable = true;
7834 state.flowing = false;
7835 state.emittedReadable = false;
7836 debug('on readable', state.length, state.reading);
7837
7838 if (state.length) {
7839 emitReadable(this);
7840 } else if (!state.reading) {
7841 process.nextTick(nReadingNextTick, this);
7842 }
7843 }
7844 }
7845
7846 return res;
7847};
7848
7849Readable.prototype.addListener = Readable.prototype.on;
7850
7851Readable.prototype.removeListener = function (ev, fn) {
7852 var res = Stream.prototype.removeListener.call(this, ev, fn);
7853
7854 if (ev === 'readable') {
7855 // We need to check if there is someone still listening to
7856 // readable and reset the state. However this needs to happen
7857 // after readable has been emitted but before I/O (nextTick) to
7858 // support once('readable', fn) cycles. This means that calling
7859 // resume within the same tick will have no
7860 // effect.
7861 process.nextTick(updateReadableListening, this);
7862 }
7863
7864 return res;
7865};
7866
7867Readable.prototype.removeAllListeners = function (ev) {
7868 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
7869
7870 if (ev === 'readable' || ev === undefined) {
7871 // We need to check if there is someone still listening to
7872 // readable and reset the state. However this needs to happen
7873 // after readable has been emitted but before I/O (nextTick) to
7874 // support once('readable', fn) cycles. This means that calling
7875 // resume within the same tick will have no
7876 // effect.
7877 process.nextTick(updateReadableListening, this);
7878 }
7879
7880 return res;
7881};
7882
7883function updateReadableListening(self) {
7884 var state = self._readableState;
7885 state.readableListening = self.listenerCount('readable') > 0;
7886
7887 if (state.resumeScheduled && !state.paused) {
7888 // flowing needs to be set to true now, otherwise
7889 // the upcoming resume will not flow.
7890 state.flowing = true; // crude way to check if we should resume
7891 } else if (self.listenerCount('data') > 0) {
7892 self.resume();
7893 }
7894}
7895
7896function nReadingNextTick(self) {
7897 debug('readable nexttick read 0');
7898 self.read(0);
7899} // pause() and resume() are remnants of the legacy readable stream API
7900// If the user uses them, then switch into old mode.
7901
7902
7903Readable.prototype.resume = function () {
7904 var state = this._readableState;
7905
7906 if (!state.flowing) {
7907 debug('resume'); // we flow only if there is no one listening
7908 // for readable, but we still have to call
7909 // resume()
7910
7911 state.flowing = !state.readableListening;
7912 resume(this, state);
7913 }
7914
7915 state.paused = false;
7916 return this;
7917};
7918
7919function resume(stream, state) {
7920 if (!state.resumeScheduled) {
7921 state.resumeScheduled = true;
7922 process.nextTick(resume_, stream, state);
7923 }
7924}
7925
7926function resume_(stream, state) {
7927 debug('resume', state.reading);
7928
7929 if (!state.reading) {
7930 stream.read(0);
7931 }
7932
7933 state.resumeScheduled = false;
7934 stream.emit('resume');
7935 flow(stream);
7936 if (state.flowing && !state.reading) stream.read(0);
7937}
7938
7939Readable.prototype.pause = function () {
7940 debug('call pause flowing=%j', this._readableState.flowing);
7941
7942 if (this._readableState.flowing !== false) {
7943 debug('pause');
7944 this._readableState.flowing = false;
7945 this.emit('pause');
7946 }
7947
7948 this._readableState.paused = true;
7949 return this;
7950};
7951
7952function flow(stream) {
7953 var state = stream._readableState;
7954 debug('flow', state.flowing);
7955
7956 while (state.flowing && stream.read() !== null) {
7957 ;
7958 }
7959} // wrap an old-style stream as the async data source.
7960// This is *not* part of the readable stream interface.
7961// It is an ugly unfortunate mess of history.
7962
7963
7964Readable.prototype.wrap = function (stream) {
7965 var _this = this;
7966
7967 var state = this._readableState;
7968 var paused = false;
7969 stream.on('end', function () {
7970 debug('wrapped end');
7971
7972 if (state.decoder && !state.ended) {
7973 var chunk = state.decoder.end();
7974 if (chunk && chunk.length) _this.push(chunk);
7975 }
7976
7977 _this.push(null);
7978 });
7979 stream.on('data', function (chunk) {
7980 debug('wrapped data');
7981 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
7982
7983 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
7984
7985 var ret = _this.push(chunk);
7986
7987 if (!ret) {
7988 paused = true;
7989 stream.pause();
7990 }
7991 }); // proxy all the other methods.
7992 // important when wrapping filters and duplexes.
7993
7994 for (var i in stream) {
7995 if (this[i] === undefined && typeof stream[i] === 'function') {
7996 this[i] = function methodWrap(method) {
7997 return function methodWrapReturnFunction() {
7998 return stream[method].apply(stream, arguments);
7999 };
8000 }(i);
8001 }
8002 } // proxy certain important events.
8003
8004
8005 for (var n = 0; n < kProxyEvents.length; n++) {
8006 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
8007 } // when we try to consume some more bytes, simply unpause the
8008 // underlying stream.
8009
8010
8011 this._read = function (n) {
8012 debug('wrapped _read', n);
8013
8014 if (paused) {
8015 paused = false;
8016 stream.resume();
8017 }
8018 };
8019
8020 return this;
8021};
8022
8023if (typeof Symbol === 'function') {
8024 Readable.prototype[Symbol.asyncIterator] = function () {
8025 if (createReadableStreamAsyncIterator === undefined) {
8026 createReadableStreamAsyncIterator = _dereq_(42);
8027 }
8028
8029 return createReadableStreamAsyncIterator(this);
8030 };
8031}
8032
8033Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
8034 // making it explicit this property is not enumerable
8035 // because otherwise some prototype manipulation in
8036 // userland will fail
8037 enumerable: false,
8038 get: function get() {
8039 return this._readableState.highWaterMark;
8040 }
8041});
8042Object.defineProperty(Readable.prototype, 'readableBuffer', {
8043 // making it explicit this property is not enumerable
8044 // because otherwise some prototype manipulation in
8045 // userland will fail
8046 enumerable: false,
8047 get: function get() {
8048 return this._readableState && this._readableState.buffer;
8049 }
8050});
8051Object.defineProperty(Readable.prototype, 'readableFlowing', {
8052 // making it explicit this property is not enumerable
8053 // because otherwise some prototype manipulation in
8054 // userland will fail
8055 enumerable: false,
8056 get: function get() {
8057 return this._readableState.flowing;
8058 },
8059 set: function set(state) {
8060 if (this._readableState) {
8061 this._readableState.flowing = state;
8062 }
8063 }
8064}); // exposed for testing purposes only.
8065
8066Readable._fromList = fromList;
8067Object.defineProperty(Readable.prototype, 'readableLength', {
8068 // making it explicit this property is not enumerable
8069 // because otherwise some prototype manipulation in
8070 // userland will fail
8071 enumerable: false,
8072 get: function get() {
8073 return this._readableState.length;
8074 }
8075}); // Pluck off n bytes from an array of buffers.
8076// Length is the combined lengths of all the buffers in the list.
8077// This function is designed to be inlinable, so please take care when making
8078// changes to the function body.
8079
8080function fromList(n, state) {
8081 // nothing buffered
8082 if (state.length === 0) return null;
8083 var ret;
8084 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
8085 // read it all, truncate the list
8086 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
8087 state.buffer.clear();
8088 } else {
8089 // read part of list
8090 ret = state.buffer.consume(n, state.decoder);
8091 }
8092 return ret;
8093}
8094
8095function endReadable(stream) {
8096 var state = stream._readableState;
8097 debug('endReadable', state.endEmitted);
8098
8099 if (!state.endEmitted) {
8100 state.ended = true;
8101 process.nextTick(endReadableNT, state, stream);
8102 }
8103}
8104
8105function endReadableNT(state, stream) {
8106 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
8107
8108 if (!state.endEmitted && state.length === 0) {
8109 state.endEmitted = true;
8110 stream.readable = false;
8111 stream.emit('end');
8112
8113 if (state.autoDestroy) {
8114 // In case of duplex streams we need a way to detect
8115 // if the writable side is ready for autoDestroy as well
8116 var wState = stream._writableState;
8117
8118 if (!wState || wState.autoDestroy && wState.finished) {
8119 stream.destroy();
8120 }
8121 }
8122 }
8123}
8124
8125if (typeof Symbol === 'function') {
8126 Readable.from = function (iterable, opts) {
8127 if (from === undefined) {
8128 from = _dereq_(46);
8129 }
8130
8131 return from(Readable, iterable, opts);
8132 };
8133}
8134
8135function indexOf(xs, x) {
8136 for (var i = 0, l = xs.length; i < l; i++) {
8137 if (xs[i] === x) return i;
8138 }
8139
8140 return -1;
8141}
8142}).call(this)}).call(this,_dereq_(67),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8143},{"21":21,"30":30,"36":36,"37":37,"42":42,"43":43,"44":44,"46":46,"48":48,"49":49,"67":67,"7":7,"9":9,"96":96}],40:[function(_dereq_,module,exports){
8144// Copyright Joyent, Inc. and other Node contributors.
8145//
8146// Permission is hereby granted, free of charge, to any person obtaining a
8147// copy of this software and associated documentation files (the
8148// "Software"), to deal in the Software without restriction, including
8149// without limitation the rights to use, copy, modify, merge, publish,
8150// distribute, sublicense, and/or sell copies of the Software, and to permit
8151// persons to whom the Software is furnished to do so, subject to the
8152// following conditions:
8153//
8154// The above copyright notice and this permission notice shall be included
8155// in all copies or substantial portions of the Software.
8156//
8157// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8158// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8159// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8160// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8161// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8162// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8163// USE OR OTHER DEALINGS IN THE SOFTWARE.
8164// a transform stream is a readable/writable stream where you do
8165// something with the data. Sometimes it's called a "filter",
8166// but that's not a great name for it, since that implies a thing where
8167// some bits pass through, and others are simply ignored. (That would
8168// be a valid example of a transform, of course.)
8169//
8170// While the output is causally related to the input, it's not a
8171// necessarily symmetric or synchronous transformation. For example,
8172// a zlib stream might take multiple plain-text writes(), and then
8173// emit a single compressed chunk some time in the future.
8174//
8175// Here's how this works:
8176//
8177// The Transform stream has all the aspects of the readable and writable
8178// stream classes. When you write(chunk), that calls _write(chunk,cb)
8179// internally, and returns false if there's a lot of pending writes
8180// buffered up. When you call read(), that calls _read(n) until
8181// there's enough pending readable data buffered up.
8182//
8183// In a transform stream, the written data is placed in a buffer. When
8184// _read(n) is called, it transforms the queued up data, calling the
8185// buffered _write cb's as it consumes chunks. If consuming a single
8186// written chunk would result in multiple output chunks, then the first
8187// outputted bit calls the readcb, and subsequent chunks just go into
8188// the read buffer, and will cause it to emit 'readable' if necessary.
8189//
8190// This way, back-pressure is actually determined by the reading side,
8191// since _read has to be called to start processing a new chunk. However,
8192// a pathological inflate type of transform can cause excessive buffering
8193// here. For example, imagine a stream where every byte of input is
8194// interpreted as an integer from 0-255, and then results in that many
8195// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
8196// 1kb of data being output. In this case, you could write a very small
8197// amount of input, and end up with a very large amount of output. In
8198// such a pathological inflating mechanism, there'd be no way to tell
8199// the system to stop doing the transform. A single 4MB write could
8200// cause the system to run out of memory.
8201//
8202// However, even in such a pathological case, only a single written chunk
8203// would be consumed, and then the rest would wait (un-transformed) until
8204// the results of the previous transformed chunk were consumed.
8205'use strict';
8206
8207module.exports = Transform;
8208
8209var _require$codes = _dereq_(36).codes,
8210 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
8211 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
8212 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
8213 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
8214
8215var Duplex = _dereq_(37);
8216
8217_dereq_(30)(Transform, Duplex);
8218
8219function afterTransform(er, data) {
8220 var ts = this._transformState;
8221 ts.transforming = false;
8222 var cb = ts.writecb;
8223
8224 if (cb === null) {
8225 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
8226 }
8227
8228 ts.writechunk = null;
8229 ts.writecb = null;
8230 if (data != null) // single equals check for both `null` and `undefined`
8231 this.push(data);
8232 cb(er);
8233 var rs = this._readableState;
8234 rs.reading = false;
8235
8236 if (rs.needReadable || rs.length < rs.highWaterMark) {
8237 this._read(rs.highWaterMark);
8238 }
8239}
8240
8241function Transform(options) {
8242 if (!(this instanceof Transform)) return new Transform(options);
8243 Duplex.call(this, options);
8244 this._transformState = {
8245 afterTransform: afterTransform.bind(this),
8246 needTransform: false,
8247 transforming: false,
8248 writecb: null,
8249 writechunk: null,
8250 writeencoding: null
8251 }; // start out asking for a readable event once data is transformed.
8252
8253 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
8254 // that Readable wants before the first _read call, so unset the
8255 // sync guard flag.
8256
8257 this._readableState.sync = false;
8258
8259 if (options) {
8260 if (typeof options.transform === 'function') this._transform = options.transform;
8261 if (typeof options.flush === 'function') this._flush = options.flush;
8262 } // When the writable side finishes, then flush out anything remaining.
8263
8264
8265 this.on('prefinish', prefinish);
8266}
8267
8268function prefinish() {
8269 var _this = this;
8270
8271 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
8272 this._flush(function (er, data) {
8273 done(_this, er, data);
8274 });
8275 } else {
8276 done(this, null, null);
8277 }
8278}
8279
8280Transform.prototype.push = function (chunk, encoding) {
8281 this._transformState.needTransform = false;
8282 return Duplex.prototype.push.call(this, chunk, encoding);
8283}; // This is the part where you do stuff!
8284// override this function in implementation classes.
8285// 'chunk' is an input chunk.
8286//
8287// Call `push(newChunk)` to pass along transformed output
8288// to the readable side. You may call 'push' zero or more times.
8289//
8290// Call `cb(err)` when you are done with this chunk. If you pass
8291// an error, then that'll put the hurt on the whole operation. If you
8292// never call cb(), then you'll never get another chunk.
8293
8294
8295Transform.prototype._transform = function (chunk, encoding, cb) {
8296 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
8297};
8298
8299Transform.prototype._write = function (chunk, encoding, cb) {
8300 var ts = this._transformState;
8301 ts.writecb = cb;
8302 ts.writechunk = chunk;
8303 ts.writeencoding = encoding;
8304
8305 if (!ts.transforming) {
8306 var rs = this._readableState;
8307 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
8308 }
8309}; // Doesn't matter what the args are here.
8310// _transform does all the work.
8311// That we got here means that the readable side wants more data.
8312
8313
8314Transform.prototype._read = function (n) {
8315 var ts = this._transformState;
8316
8317 if (ts.writechunk !== null && !ts.transforming) {
8318 ts.transforming = true;
8319
8320 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
8321 } else {
8322 // mark that we need a transform, so that any data that comes in
8323 // will get processed, now that we've asked for it.
8324 ts.needTransform = true;
8325 }
8326};
8327
8328Transform.prototype._destroy = function (err, cb) {
8329 Duplex.prototype._destroy.call(this, err, function (err2) {
8330 cb(err2);
8331 });
8332};
8333
8334function done(stream, er, data) {
8335 if (er) return stream.emit('error', er);
8336 if (data != null) // single equals check for both `null` and `undefined`
8337 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
8338 // if there's nothing in the write buffer, then that means
8339 // that nothing more will ever be provided
8340
8341 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
8342 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
8343 return stream.push(null);
8344}
8345},{"30":30,"36":36,"37":37}],41:[function(_dereq_,module,exports){
8346(function (process,global){(function (){
8347// Copyright Joyent, Inc. and other Node contributors.
8348//
8349// Permission is hereby granted, free of charge, to any person obtaining a
8350// copy of this software and associated documentation files (the
8351// "Software"), to deal in the Software without restriction, including
8352// without limitation the rights to use, copy, modify, merge, publish,
8353// distribute, sublicense, and/or sell copies of the Software, and to permit
8354// persons to whom the Software is furnished to do so, subject to the
8355// following conditions:
8356//
8357// The above copyright notice and this permission notice shall be included
8358// in all copies or substantial portions of the Software.
8359//
8360// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8361// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8362// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8363// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8364// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8365// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8366// USE OR OTHER DEALINGS IN THE SOFTWARE.
8367// A bit simpler than readable streams.
8368// Implement an async ._write(chunk, encoding, cb), and it'll handle all
8369// the drain event emission and buffering.
8370'use strict';
8371
8372module.exports = Writable;
8373/* <replacement> */
8374
8375function WriteReq(chunk, encoding, cb) {
8376 this.chunk = chunk;
8377 this.encoding = encoding;
8378 this.callback = cb;
8379 this.next = null;
8380} // It seems a linked list but it is not
8381// there will be only 2 of these for each stream
8382
8383
8384function CorkedRequest(state) {
8385 var _this = this;
8386
8387 this.next = null;
8388 this.entry = null;
8389
8390 this.finish = function () {
8391 onCorkedFinish(_this, state);
8392 };
8393}
8394/* </replacement> */
8395
8396/*<replacement>*/
8397
8398
8399var Duplex;
8400/*</replacement>*/
8401
8402Writable.WritableState = WritableState;
8403/*<replacement>*/
8404
8405var internalUtil = {
8406 deprecate: _dereq_(114)
8407};
8408/*</replacement>*/
8409
8410/*<replacement>*/
8411
8412var Stream = _dereq_(49);
8413/*</replacement>*/
8414
8415
8416var Buffer = _dereq_(9).Buffer;
8417
8418var OurUint8Array = global.Uint8Array || function () {};
8419
8420function _uint8ArrayToBuffer(chunk) {
8421 return Buffer.from(chunk);
8422}
8423
8424function _isUint8Array(obj) {
8425 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
8426}
8427
8428var destroyImpl = _dereq_(44);
8429
8430var _require = _dereq_(48),
8431 getHighWaterMark = _require.getHighWaterMark;
8432
8433var _require$codes = _dereq_(36).codes,
8434 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
8435 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
8436 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
8437 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
8438 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
8439 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
8440 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
8441 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
8442
8443var errorOrDestroy = destroyImpl.errorOrDestroy;
8444
8445_dereq_(30)(Writable, Stream);
8446
8447function nop() {}
8448
8449function WritableState(options, stream, isDuplex) {
8450 Duplex = Duplex || _dereq_(37);
8451 options = options || {}; // Duplex streams are both readable and writable, but share
8452 // the same options object.
8453 // However, some cases require setting options to different
8454 // values for the readable and the writable sides of the duplex stream,
8455 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
8456
8457 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
8458 // contains buffers or objects.
8459
8460 this.objectMode = !!options.objectMode;
8461 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
8462 // Note: 0 is a valid value, means that we always return false if
8463 // the entire buffer is not flushed immediately on write()
8464
8465 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
8466
8467 this.finalCalled = false; // drain event flag.
8468
8469 this.needDrain = false; // at the start of calling end()
8470
8471 this.ending = false; // when end() has been called, and returned
8472
8473 this.ended = false; // when 'finish' is emitted
8474
8475 this.finished = false; // has it been destroyed
8476
8477 this.destroyed = false; // should we decode strings into buffers before passing to _write?
8478 // this is here so that some node-core streams can optimize string
8479 // handling at a lower level.
8480
8481 var noDecode = options.decodeStrings === false;
8482 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
8483 // encoding is 'binary' so we have to make this configurable.
8484 // Everything else in the universe uses 'utf8', though.
8485
8486 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
8487 // of how much we're waiting to get pushed to some underlying
8488 // socket or file.
8489
8490 this.length = 0; // a flag to see when we're in the middle of a write.
8491
8492 this.writing = false; // when true all writes will be buffered until .uncork() call
8493
8494 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
8495 // or on a later tick. We set this to true at first, because any
8496 // actions that shouldn't happen until "later" should generally also
8497 // not happen before the first write call.
8498
8499 this.sync = true; // a flag to know if we're processing previously buffered items, which
8500 // may call the _write() callback in the same tick, so that we don't
8501 // end up in an overlapped onwrite situation.
8502
8503 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
8504
8505 this.onwrite = function (er) {
8506 onwrite(stream, er);
8507 }; // the callback that the user supplies to write(chunk,encoding,cb)
8508
8509
8510 this.writecb = null; // the amount that is being written when _write is called.
8511
8512 this.writelen = 0;
8513 this.bufferedRequest = null;
8514 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
8515 // this must be 0 before 'finish' can be emitted
8516
8517 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
8518 // This is relevant for synchronous Transform streams
8519
8520 this.prefinished = false; // True if the error was already emitted and should not be thrown again
8521
8522 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
8523
8524 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
8525
8526 this.autoDestroy = !!options.autoDestroy; // count buffered requests
8527
8528 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
8529 // one allocated and free to use, and we maintain at most two
8530
8531 this.corkedRequestsFree = new CorkedRequest(this);
8532}
8533
8534WritableState.prototype.getBuffer = function getBuffer() {
8535 var current = this.bufferedRequest;
8536 var out = [];
8537
8538 while (current) {
8539 out.push(current);
8540 current = current.next;
8541 }
8542
8543 return out;
8544};
8545
8546(function () {
8547 try {
8548 Object.defineProperty(WritableState.prototype, 'buffer', {
8549 get: internalUtil.deprecate(function writableStateBufferGetter() {
8550 return this.getBuffer();
8551 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
8552 });
8553 } catch (_) {}
8554})(); // Test _writableState for inheritance to account for Duplex streams,
8555// whose prototype chain only points to Readable.
8556
8557
8558var realHasInstance;
8559
8560if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
8561 realHasInstance = Function.prototype[Symbol.hasInstance];
8562 Object.defineProperty(Writable, Symbol.hasInstance, {
8563 value: function value(object) {
8564 if (realHasInstance.call(this, object)) return true;
8565 if (this !== Writable) return false;
8566 return object && object._writableState instanceof WritableState;
8567 }
8568 });
8569} else {
8570 realHasInstance = function realHasInstance(object) {
8571 return object instanceof this;
8572 };
8573}
8574
8575function Writable(options) {
8576 Duplex = Duplex || _dereq_(37); // Writable ctor is applied to Duplexes, too.
8577 // `realHasInstance` is necessary because using plain `instanceof`
8578 // would return false, as no `_writableState` property is attached.
8579 // Trying to use the custom `instanceof` for Writable here will also break the
8580 // Node.js LazyTransform implementation, which has a non-trivial getter for
8581 // `_writableState` that would lead to infinite recursion.
8582 // Checking for a Stream.Duplex instance is faster here instead of inside
8583 // the WritableState constructor, at least with V8 6.5
8584
8585 var isDuplex = this instanceof Duplex;
8586 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
8587 this._writableState = new WritableState(options, this, isDuplex); // legacy.
8588
8589 this.writable = true;
8590
8591 if (options) {
8592 if (typeof options.write === 'function') this._write = options.write;
8593 if (typeof options.writev === 'function') this._writev = options.writev;
8594 if (typeof options.destroy === 'function') this._destroy = options.destroy;
8595 if (typeof options.final === 'function') this._final = options.final;
8596 }
8597
8598 Stream.call(this);
8599} // Otherwise people can pipe Writable streams, which is just wrong.
8600
8601
8602Writable.prototype.pipe = function () {
8603 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
8604};
8605
8606function writeAfterEnd(stream, cb) {
8607 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
8608
8609 errorOrDestroy(stream, er);
8610 process.nextTick(cb, er);
8611} // Checks that a user-supplied chunk is valid, especially for the particular
8612// mode the stream is in. Currently this means that `null` is never accepted
8613// and undefined/non-string values are only allowed in object mode.
8614
8615
8616function validChunk(stream, state, chunk, cb) {
8617 var er;
8618
8619 if (chunk === null) {
8620 er = new ERR_STREAM_NULL_VALUES();
8621 } else if (typeof chunk !== 'string' && !state.objectMode) {
8622 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
8623 }
8624
8625 if (er) {
8626 errorOrDestroy(stream, er);
8627 process.nextTick(cb, er);
8628 return false;
8629 }
8630
8631 return true;
8632}
8633
8634Writable.prototype.write = function (chunk, encoding, cb) {
8635 var state = this._writableState;
8636 var ret = false;
8637
8638 var isBuf = !state.objectMode && _isUint8Array(chunk);
8639
8640 if (isBuf && !Buffer.isBuffer(chunk)) {
8641 chunk = _uint8ArrayToBuffer(chunk);
8642 }
8643
8644 if (typeof encoding === 'function') {
8645 cb = encoding;
8646 encoding = null;
8647 }
8648
8649 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
8650 if (typeof cb !== 'function') cb = nop;
8651 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
8652 state.pendingcb++;
8653 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
8654 }
8655 return ret;
8656};
8657
8658Writable.prototype.cork = function () {
8659 this._writableState.corked++;
8660};
8661
8662Writable.prototype.uncork = function () {
8663 var state = this._writableState;
8664
8665 if (state.corked) {
8666 state.corked--;
8667 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
8668 }
8669};
8670
8671Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
8672 // node::ParseEncoding() requires lower case.
8673 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
8674 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);
8675 this._writableState.defaultEncoding = encoding;
8676 return this;
8677};
8678
8679Object.defineProperty(Writable.prototype, 'writableBuffer', {
8680 // making it explicit this property is not enumerable
8681 // because otherwise some prototype manipulation in
8682 // userland will fail
8683 enumerable: false,
8684 get: function get() {
8685 return this._writableState && this._writableState.getBuffer();
8686 }
8687});
8688
8689function decodeChunk(state, chunk, encoding) {
8690 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
8691 chunk = Buffer.from(chunk, encoding);
8692 }
8693
8694 return chunk;
8695}
8696
8697Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
8698 // making it explicit this property is not enumerable
8699 // because otherwise some prototype manipulation in
8700 // userland will fail
8701 enumerable: false,
8702 get: function get() {
8703 return this._writableState.highWaterMark;
8704 }
8705}); // if we're already writing something, then just put this
8706// in the queue, and wait our turn. Otherwise, call _write
8707// If we return false, then we need a drain event, so set that flag.
8708
8709function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
8710 if (!isBuf) {
8711 var newChunk = decodeChunk(state, chunk, encoding);
8712
8713 if (chunk !== newChunk) {
8714 isBuf = true;
8715 encoding = 'buffer';
8716 chunk = newChunk;
8717 }
8718 }
8719
8720 var len = state.objectMode ? 1 : chunk.length;
8721 state.length += len;
8722 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
8723
8724 if (!ret) state.needDrain = true;
8725
8726 if (state.writing || state.corked) {
8727 var last = state.lastBufferedRequest;
8728 state.lastBufferedRequest = {
8729 chunk: chunk,
8730 encoding: encoding,
8731 isBuf: isBuf,
8732 callback: cb,
8733 next: null
8734 };
8735
8736 if (last) {
8737 last.next = state.lastBufferedRequest;
8738 } else {
8739 state.bufferedRequest = state.lastBufferedRequest;
8740 }
8741
8742 state.bufferedRequestCount += 1;
8743 } else {
8744 doWrite(stream, state, false, len, chunk, encoding, cb);
8745 }
8746
8747 return ret;
8748}
8749
8750function doWrite(stream, state, writev, len, chunk, encoding, cb) {
8751 state.writelen = len;
8752 state.writecb = cb;
8753 state.writing = true;
8754 state.sync = true;
8755 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);
8756 state.sync = false;
8757}
8758
8759function onwriteError(stream, state, sync, er, cb) {
8760 --state.pendingcb;
8761
8762 if (sync) {
8763 // defer the callback if we are being called synchronously
8764 // to avoid piling up things on the stack
8765 process.nextTick(cb, er); // this can emit finish, and it will always happen
8766 // after error
8767
8768 process.nextTick(finishMaybe, stream, state);
8769 stream._writableState.errorEmitted = true;
8770 errorOrDestroy(stream, er);
8771 } else {
8772 // the caller expect this to happen before if
8773 // it is async
8774 cb(er);
8775 stream._writableState.errorEmitted = true;
8776 errorOrDestroy(stream, er); // this can emit finish, but finish must
8777 // always follow error
8778
8779 finishMaybe(stream, state);
8780 }
8781}
8782
8783function onwriteStateUpdate(state) {
8784 state.writing = false;
8785 state.writecb = null;
8786 state.length -= state.writelen;
8787 state.writelen = 0;
8788}
8789
8790function onwrite(stream, er) {
8791 var state = stream._writableState;
8792 var sync = state.sync;
8793 var cb = state.writecb;
8794 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
8795 onwriteStateUpdate(state);
8796 if (er) onwriteError(stream, state, sync, er, cb);else {
8797 // Check if we're actually ready to finish, but don't emit yet
8798 var finished = needFinish(state) || stream.destroyed;
8799
8800 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
8801 clearBuffer(stream, state);
8802 }
8803
8804 if (sync) {
8805 process.nextTick(afterWrite, stream, state, finished, cb);
8806 } else {
8807 afterWrite(stream, state, finished, cb);
8808 }
8809 }
8810}
8811
8812function afterWrite(stream, state, finished, cb) {
8813 if (!finished) onwriteDrain(stream, state);
8814 state.pendingcb--;
8815 cb();
8816 finishMaybe(stream, state);
8817} // Must force callback to be called on nextTick, so that we don't
8818// emit 'drain' before the write() consumer gets the 'false' return
8819// value, and has a chance to attach a 'drain' listener.
8820
8821
8822function onwriteDrain(stream, state) {
8823 if (state.length === 0 && state.needDrain) {
8824 state.needDrain = false;
8825 stream.emit('drain');
8826 }
8827} // if there's something in the buffer waiting, then process it
8828
8829
8830function clearBuffer(stream, state) {
8831 state.bufferProcessing = true;
8832 var entry = state.bufferedRequest;
8833
8834 if (stream._writev && entry && entry.next) {
8835 // Fast case, write everything using _writev()
8836 var l = state.bufferedRequestCount;
8837 var buffer = new Array(l);
8838 var holder = state.corkedRequestsFree;
8839 holder.entry = entry;
8840 var count = 0;
8841 var allBuffers = true;
8842
8843 while (entry) {
8844 buffer[count] = entry;
8845 if (!entry.isBuf) allBuffers = false;
8846 entry = entry.next;
8847 count += 1;
8848 }
8849
8850 buffer.allBuffers = allBuffers;
8851 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
8852 // as the hot path ends with doWrite
8853
8854 state.pendingcb++;
8855 state.lastBufferedRequest = null;
8856
8857 if (holder.next) {
8858 state.corkedRequestsFree = holder.next;
8859 holder.next = null;
8860 } else {
8861 state.corkedRequestsFree = new CorkedRequest(state);
8862 }
8863
8864 state.bufferedRequestCount = 0;
8865 } else {
8866 // Slow case, write chunks one-by-one
8867 while (entry) {
8868 var chunk = entry.chunk;
8869 var encoding = entry.encoding;
8870 var cb = entry.callback;
8871 var len = state.objectMode ? 1 : chunk.length;
8872 doWrite(stream, state, false, len, chunk, encoding, cb);
8873 entry = entry.next;
8874 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
8875 // it means that we need to wait until it does.
8876 // also, that means that the chunk and cb are currently
8877 // being processed, so move the buffer counter past them.
8878
8879 if (state.writing) {
8880 break;
8881 }
8882 }
8883
8884 if (entry === null) state.lastBufferedRequest = null;
8885 }
8886
8887 state.bufferedRequest = entry;
8888 state.bufferProcessing = false;
8889}
8890
8891Writable.prototype._write = function (chunk, encoding, cb) {
8892 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
8893};
8894
8895Writable.prototype._writev = null;
8896
8897Writable.prototype.end = function (chunk, encoding, cb) {
8898 var state = this._writableState;
8899
8900 if (typeof chunk === 'function') {
8901 cb = chunk;
8902 chunk = null;
8903 encoding = null;
8904 } else if (typeof encoding === 'function') {
8905 cb = encoding;
8906 encoding = null;
8907 }
8908
8909 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
8910
8911 if (state.corked) {
8912 state.corked = 1;
8913 this.uncork();
8914 } // ignore unnecessary end() calls.
8915
8916
8917 if (!state.ending) endWritable(this, state, cb);
8918 return this;
8919};
8920
8921Object.defineProperty(Writable.prototype, 'writableLength', {
8922 // making it explicit this property is not enumerable
8923 // because otherwise some prototype manipulation in
8924 // userland will fail
8925 enumerable: false,
8926 get: function get() {
8927 return this._writableState.length;
8928 }
8929});
8930
8931function needFinish(state) {
8932 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
8933}
8934
8935function callFinal(stream, state) {
8936 stream._final(function (err) {
8937 state.pendingcb--;
8938
8939 if (err) {
8940 errorOrDestroy(stream, err);
8941 }
8942
8943 state.prefinished = true;
8944 stream.emit('prefinish');
8945 finishMaybe(stream, state);
8946 });
8947}
8948
8949function prefinish(stream, state) {
8950 if (!state.prefinished && !state.finalCalled) {
8951 if (typeof stream._final === 'function' && !state.destroyed) {
8952 state.pendingcb++;
8953 state.finalCalled = true;
8954 process.nextTick(callFinal, stream, state);
8955 } else {
8956 state.prefinished = true;
8957 stream.emit('prefinish');
8958 }
8959 }
8960}
8961
8962function finishMaybe(stream, state) {
8963 var need = needFinish(state);
8964
8965 if (need) {
8966 prefinish(stream, state);
8967
8968 if (state.pendingcb === 0) {
8969 state.finished = true;
8970 stream.emit('finish');
8971
8972 if (state.autoDestroy) {
8973 // In case of duplex streams we need a way to detect
8974 // if the readable side is ready for autoDestroy as well
8975 var rState = stream._readableState;
8976
8977 if (!rState || rState.autoDestroy && rState.endEmitted) {
8978 stream.destroy();
8979 }
8980 }
8981 }
8982 }
8983
8984 return need;
8985}
8986
8987function endWritable(stream, state, cb) {
8988 state.ending = true;
8989 finishMaybe(stream, state);
8990
8991 if (cb) {
8992 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
8993 }
8994
8995 state.ended = true;
8996 stream.writable = false;
8997}
8998
8999function onCorkedFinish(corkReq, state, err) {
9000 var entry = corkReq.entry;
9001 corkReq.entry = null;
9002
9003 while (entry) {
9004 var cb = entry.callback;
9005 state.pendingcb--;
9006 cb(err);
9007 entry = entry.next;
9008 } // reuse the free corkReq.
9009
9010
9011 state.corkedRequestsFree.next = corkReq;
9012}
9013
9014Object.defineProperty(Writable.prototype, 'destroyed', {
9015 // making it explicit this property is not enumerable
9016 // because otherwise some prototype manipulation in
9017 // userland will fail
9018 enumerable: false,
9019 get: function get() {
9020 if (this._writableState === undefined) {
9021 return false;
9022 }
9023
9024 return this._writableState.destroyed;
9025 },
9026 set: function set(value) {
9027 // we ignore the value if the stream
9028 // has not been initialized yet
9029 if (!this._writableState) {
9030 return;
9031 } // backward compatibility, the user is explicitly
9032 // managing destroyed
9033
9034
9035 this._writableState.destroyed = value;
9036 }
9037});
9038Writable.prototype.destroy = destroyImpl.destroy;
9039Writable.prototype._undestroy = destroyImpl.undestroy;
9040
9041Writable.prototype._destroy = function (err, cb) {
9042 cb(err);
9043};
9044}).call(this)}).call(this,_dereq_(67),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9045},{"114":114,"30":30,"36":36,"37":37,"44":44,"48":48,"49":49,"67":67,"9":9}],42:[function(_dereq_,module,exports){
9046(function (process){(function (){
9047'use strict';
9048
9049var _Object$setPrototypeO;
9050
9051function _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; }
9052
9053var finished = _dereq_(45);
9054
9055var kLastResolve = Symbol('lastResolve');
9056var kLastReject = Symbol('lastReject');
9057var kError = Symbol('error');
9058var kEnded = Symbol('ended');
9059var kLastPromise = Symbol('lastPromise');
9060var kHandlePromise = Symbol('handlePromise');
9061var kStream = Symbol('stream');
9062
9063function createIterResult(value, done) {
9064 return {
9065 value: value,
9066 done: done
9067 };
9068}
9069
9070function readAndResolve(iter) {
9071 var resolve = iter[kLastResolve];
9072
9073 if (resolve !== null) {
9074 var data = iter[kStream].read(); // we defer if data is null
9075 // we can be expecting either 'end' or
9076 // 'error'
9077
9078 if (data !== null) {
9079 iter[kLastPromise] = null;
9080 iter[kLastResolve] = null;
9081 iter[kLastReject] = null;
9082 resolve(createIterResult(data, false));
9083 }
9084 }
9085}
9086
9087function onReadable(iter) {
9088 // we wait for the next tick, because it might
9089 // emit an error with process.nextTick
9090 process.nextTick(readAndResolve, iter);
9091}
9092
9093function wrapForNext(lastPromise, iter) {
9094 return function (resolve, reject) {
9095 lastPromise.then(function () {
9096 if (iter[kEnded]) {
9097 resolve(createIterResult(undefined, true));
9098 return;
9099 }
9100
9101 iter[kHandlePromise](resolve, reject);
9102 }, reject);
9103 };
9104}
9105
9106var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
9107var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
9108 get stream() {
9109 return this[kStream];
9110 },
9111
9112 next: function next() {
9113 var _this = this;
9114
9115 // if we have detected an error in the meanwhile
9116 // reject straight away
9117 var error = this[kError];
9118
9119 if (error !== null) {
9120 return Promise.reject(error);
9121 }
9122
9123 if (this[kEnded]) {
9124 return Promise.resolve(createIterResult(undefined, true));
9125 }
9126
9127 if (this[kStream].destroyed) {
9128 // We need to defer via nextTick because if .destroy(err) is
9129 // called, the error will be emitted via nextTick, and
9130 // we cannot guarantee that there is no error lingering around
9131 // waiting to be emitted.
9132 return new Promise(function (resolve, reject) {
9133 process.nextTick(function () {
9134 if (_this[kError]) {
9135 reject(_this[kError]);
9136 } else {
9137 resolve(createIterResult(undefined, true));
9138 }
9139 });
9140 });
9141 } // if we have multiple next() calls
9142 // we will wait for the previous Promise to finish
9143 // this logic is optimized to support for await loops,
9144 // where next() is only called once at a time
9145
9146
9147 var lastPromise = this[kLastPromise];
9148 var promise;
9149
9150 if (lastPromise) {
9151 promise = new Promise(wrapForNext(lastPromise, this));
9152 } else {
9153 // fast path needed to support multiple this.push()
9154 // without triggering the next() queue
9155 var data = this[kStream].read();
9156
9157 if (data !== null) {
9158 return Promise.resolve(createIterResult(data, false));
9159 }
9160
9161 promise = new Promise(this[kHandlePromise]);
9162 }
9163
9164 this[kLastPromise] = promise;
9165 return promise;
9166 }
9167}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
9168 return this;
9169}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
9170 var _this2 = this;
9171
9172 // destroy(err, cb) is a private API
9173 // we can guarantee we have that here, because we control the
9174 // Readable class this is attached to
9175 return new Promise(function (resolve, reject) {
9176 _this2[kStream].destroy(null, function (err) {
9177 if (err) {
9178 reject(err);
9179 return;
9180 }
9181
9182 resolve(createIterResult(undefined, true));
9183 });
9184 });
9185}), _Object$setPrototypeO), AsyncIteratorPrototype);
9186
9187var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
9188 var _Object$create;
9189
9190 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
9191 value: stream,
9192 writable: true
9193 }), _defineProperty(_Object$create, kLastResolve, {
9194 value: null,
9195 writable: true
9196 }), _defineProperty(_Object$create, kLastReject, {
9197 value: null,
9198 writable: true
9199 }), _defineProperty(_Object$create, kError, {
9200 value: null,
9201 writable: true
9202 }), _defineProperty(_Object$create, kEnded, {
9203 value: stream._readableState.endEmitted,
9204 writable: true
9205 }), _defineProperty(_Object$create, kHandlePromise, {
9206 value: function value(resolve, reject) {
9207 var data = iterator[kStream].read();
9208
9209 if (data) {
9210 iterator[kLastPromise] = null;
9211 iterator[kLastResolve] = null;
9212 iterator[kLastReject] = null;
9213 resolve(createIterResult(data, false));
9214 } else {
9215 iterator[kLastResolve] = resolve;
9216 iterator[kLastReject] = reject;
9217 }
9218 },
9219 writable: true
9220 }), _Object$create));
9221 iterator[kLastPromise] = null;
9222 finished(stream, function (err) {
9223 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
9224 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
9225 // returned by next() and store the error
9226
9227 if (reject !== null) {
9228 iterator[kLastPromise] = null;
9229 iterator[kLastResolve] = null;
9230 iterator[kLastReject] = null;
9231 reject(err);
9232 }
9233
9234 iterator[kError] = err;
9235 return;
9236 }
9237
9238 var resolve = iterator[kLastResolve];
9239
9240 if (resolve !== null) {
9241 iterator[kLastPromise] = null;
9242 iterator[kLastResolve] = null;
9243 iterator[kLastReject] = null;
9244 resolve(createIterResult(undefined, true));
9245 }
9246
9247 iterator[kEnded] = true;
9248 });
9249 stream.on('readable', onReadable.bind(null, iterator));
9250 return iterator;
9251};
9252
9253module.exports = createReadableStreamAsyncIterator;
9254}).call(this)}).call(this,_dereq_(67))
9255},{"45":45,"67":67}],43:[function(_dereq_,module,exports){
9256'use strict';
9257
9258function 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; }
9259
9260function _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; }
9261
9262function _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; }
9263
9264function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
9265
9266function _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); } }
9267
9268function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
9269
9270var _require = _dereq_(9),
9271 Buffer = _require.Buffer;
9272
9273var _require2 = _dereq_(7),
9274 inspect = _require2.inspect;
9275
9276var custom = inspect && inspect.custom || 'inspect';
9277
9278function copyBuffer(src, target, offset) {
9279 Buffer.prototype.copy.call(src, target, offset);
9280}
9281
9282module.exports =
9283/*#__PURE__*/
9284function () {
9285 function BufferList() {
9286 _classCallCheck(this, BufferList);
9287
9288 this.head = null;
9289 this.tail = null;
9290 this.length = 0;
9291 }
9292
9293 _createClass(BufferList, [{
9294 key: "push",
9295 value: function push(v) {
9296 var entry = {
9297 data: v,
9298 next: null
9299 };
9300 if (this.length > 0) this.tail.next = entry;else this.head = entry;
9301 this.tail = entry;
9302 ++this.length;
9303 }
9304 }, {
9305 key: "unshift",
9306 value: function unshift(v) {
9307 var entry = {
9308 data: v,
9309 next: this.head
9310 };
9311 if (this.length === 0) this.tail = entry;
9312 this.head = entry;
9313 ++this.length;
9314 }
9315 }, {
9316 key: "shift",
9317 value: function shift() {
9318 if (this.length === 0) return;
9319 var ret = this.head.data;
9320 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
9321 --this.length;
9322 return ret;
9323 }
9324 }, {
9325 key: "clear",
9326 value: function clear() {
9327 this.head = this.tail = null;
9328 this.length = 0;
9329 }
9330 }, {
9331 key: "join",
9332 value: function join(s) {
9333 if (this.length === 0) return '';
9334 var p = this.head;
9335 var ret = '' + p.data;
9336
9337 while (p = p.next) {
9338 ret += s + p.data;
9339 }
9340
9341 return ret;
9342 }
9343 }, {
9344 key: "concat",
9345 value: function concat(n) {
9346 if (this.length === 0) return Buffer.alloc(0);
9347 var ret = Buffer.allocUnsafe(n >>> 0);
9348 var p = this.head;
9349 var i = 0;
9350
9351 while (p) {
9352 copyBuffer(p.data, ret, i);
9353 i += p.data.length;
9354 p = p.next;
9355 }
9356
9357 return ret;
9358 } // Consumes a specified amount of bytes or characters from the buffered data.
9359
9360 }, {
9361 key: "consume",
9362 value: function consume(n, hasStrings) {
9363 var ret;
9364
9365 if (n < this.head.data.length) {
9366 // `slice` is the same for buffers and strings.
9367 ret = this.head.data.slice(0, n);
9368 this.head.data = this.head.data.slice(n);
9369 } else if (n === this.head.data.length) {
9370 // First chunk is a perfect match.
9371 ret = this.shift();
9372 } else {
9373 // Result spans more than one buffer.
9374 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
9375 }
9376
9377 return ret;
9378 }
9379 }, {
9380 key: "first",
9381 value: function first() {
9382 return this.head.data;
9383 } // Consumes a specified amount of characters from the buffered data.
9384
9385 }, {
9386 key: "_getString",
9387 value: function _getString(n) {
9388 var p = this.head;
9389 var c = 1;
9390 var ret = p.data;
9391 n -= ret.length;
9392
9393 while (p = p.next) {
9394 var str = p.data;
9395 var nb = n > str.length ? str.length : n;
9396 if (nb === str.length) ret += str;else ret += str.slice(0, n);
9397 n -= nb;
9398
9399 if (n === 0) {
9400 if (nb === str.length) {
9401 ++c;
9402 if (p.next) this.head = p.next;else this.head = this.tail = null;
9403 } else {
9404 this.head = p;
9405 p.data = str.slice(nb);
9406 }
9407
9408 break;
9409 }
9410
9411 ++c;
9412 }
9413
9414 this.length -= c;
9415 return ret;
9416 } // Consumes a specified amount of bytes from the buffered data.
9417
9418 }, {
9419 key: "_getBuffer",
9420 value: function _getBuffer(n) {
9421 var ret = Buffer.allocUnsafe(n);
9422 var p = this.head;
9423 var c = 1;
9424 p.data.copy(ret);
9425 n -= p.data.length;
9426
9427 while (p = p.next) {
9428 var buf = p.data;
9429 var nb = n > buf.length ? buf.length : n;
9430 buf.copy(ret, ret.length - n, 0, nb);
9431 n -= nb;
9432
9433 if (n === 0) {
9434 if (nb === buf.length) {
9435 ++c;
9436 if (p.next) this.head = p.next;else this.head = this.tail = null;
9437 } else {
9438 this.head = p;
9439 p.data = buf.slice(nb);
9440 }
9441
9442 break;
9443 }
9444
9445 ++c;
9446 }
9447
9448 this.length -= c;
9449 return ret;
9450 } // Make sure the linked list only shows the minimal necessary information.
9451
9452 }, {
9453 key: custom,
9454 value: function value(_, options) {
9455 return inspect(this, _objectSpread({}, options, {
9456 // Only inspect one level.
9457 depth: 0,
9458 // It should not recurse.
9459 customInspect: false
9460 }));
9461 }
9462 }]);
9463
9464 return BufferList;
9465}();
9466},{"7":7,"9":9}],44:[function(_dereq_,module,exports){
9467(function (process){(function (){
9468'use strict'; // undocumented cb() API, needed for core, not for public API
9469
9470function destroy(err, cb) {
9471 var _this = this;
9472
9473 var readableDestroyed = this._readableState && this._readableState.destroyed;
9474 var writableDestroyed = this._writableState && this._writableState.destroyed;
9475
9476 if (readableDestroyed || writableDestroyed) {
9477 if (cb) {
9478 cb(err);
9479 } else if (err) {
9480 if (!this._writableState) {
9481 process.nextTick(emitErrorNT, this, err);
9482 } else if (!this._writableState.errorEmitted) {
9483 this._writableState.errorEmitted = true;
9484 process.nextTick(emitErrorNT, this, err);
9485 }
9486 }
9487
9488 return this;
9489 } // we set destroyed to true before firing error callbacks in order
9490 // to make it re-entrance safe in case destroy() is called within callbacks
9491
9492
9493 if (this._readableState) {
9494 this._readableState.destroyed = true;
9495 } // if this is a duplex stream mark the writable part as destroyed as well
9496
9497
9498 if (this._writableState) {
9499 this._writableState.destroyed = true;
9500 }
9501
9502 this._destroy(err || null, function (err) {
9503 if (!cb && err) {
9504 if (!_this._writableState) {
9505 process.nextTick(emitErrorAndCloseNT, _this, err);
9506 } else if (!_this._writableState.errorEmitted) {
9507 _this._writableState.errorEmitted = true;
9508 process.nextTick(emitErrorAndCloseNT, _this, err);
9509 } else {
9510 process.nextTick(emitCloseNT, _this);
9511 }
9512 } else if (cb) {
9513 process.nextTick(emitCloseNT, _this);
9514 cb(err);
9515 } else {
9516 process.nextTick(emitCloseNT, _this);
9517 }
9518 });
9519
9520 return this;
9521}
9522
9523function emitErrorAndCloseNT(self, err) {
9524 emitErrorNT(self, err);
9525 emitCloseNT(self);
9526}
9527
9528function emitCloseNT(self) {
9529 if (self._writableState && !self._writableState.emitClose) return;
9530 if (self._readableState && !self._readableState.emitClose) return;
9531 self.emit('close');
9532}
9533
9534function undestroy() {
9535 if (this._readableState) {
9536 this._readableState.destroyed = false;
9537 this._readableState.reading = false;
9538 this._readableState.ended = false;
9539 this._readableState.endEmitted = false;
9540 }
9541
9542 if (this._writableState) {
9543 this._writableState.destroyed = false;
9544 this._writableState.ended = false;
9545 this._writableState.ending = false;
9546 this._writableState.finalCalled = false;
9547 this._writableState.prefinished = false;
9548 this._writableState.finished = false;
9549 this._writableState.errorEmitted = false;
9550 }
9551}
9552
9553function emitErrorNT(self, err) {
9554 self.emit('error', err);
9555}
9556
9557function errorOrDestroy(stream, err) {
9558 // We have tests that rely on errors being emitted
9559 // in the same tick, so changing this is semver major.
9560 // For now when you opt-in to autoDestroy we allow
9561 // the error to be emitted nextTick. In a future
9562 // semver major update we should change the default to this.
9563 var rState = stream._readableState;
9564 var wState = stream._writableState;
9565 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
9566}
9567
9568module.exports = {
9569 destroy: destroy,
9570 undestroy: undestroy,
9571 errorOrDestroy: errorOrDestroy
9572};
9573}).call(this)}).call(this,_dereq_(67))
9574},{"67":67}],45:[function(_dereq_,module,exports){
9575// Ported from https://github.com/mafintosh/end-of-stream with
9576// permission from the author, Mathias Buus (@mafintosh).
9577'use strict';
9578
9579var ERR_STREAM_PREMATURE_CLOSE = _dereq_(36).codes.ERR_STREAM_PREMATURE_CLOSE;
9580
9581function once(callback) {
9582 var called = false;
9583 return function () {
9584 if (called) return;
9585 called = true;
9586
9587 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9588 args[_key] = arguments[_key];
9589 }
9590
9591 callback.apply(this, args);
9592 };
9593}
9594
9595function noop() {}
9596
9597function isRequest(stream) {
9598 return stream.setHeader && typeof stream.abort === 'function';
9599}
9600
9601function eos(stream, opts, callback) {
9602 if (typeof opts === 'function') return eos(stream, null, opts);
9603 if (!opts) opts = {};
9604 callback = once(callback || noop);
9605 var readable = opts.readable || opts.readable !== false && stream.readable;
9606 var writable = opts.writable || opts.writable !== false && stream.writable;
9607
9608 var onlegacyfinish = function onlegacyfinish() {
9609 if (!stream.writable) onfinish();
9610 };
9611
9612 var writableEnded = stream._writableState && stream._writableState.finished;
9613
9614 var onfinish = function onfinish() {
9615 writable = false;
9616 writableEnded = true;
9617 if (!readable) callback.call(stream);
9618 };
9619
9620 var readableEnded = stream._readableState && stream._readableState.endEmitted;
9621
9622 var onend = function onend() {
9623 readable = false;
9624 readableEnded = true;
9625 if (!writable) callback.call(stream);
9626 };
9627
9628 var onerror = function onerror(err) {
9629 callback.call(stream, err);
9630 };
9631
9632 var onclose = function onclose() {
9633 var err;
9634
9635 if (readable && !readableEnded) {
9636 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9637 return callback.call(stream, err);
9638 }
9639
9640 if (writable && !writableEnded) {
9641 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9642 return callback.call(stream, err);
9643 }
9644 };
9645
9646 var onrequest = function onrequest() {
9647 stream.req.on('finish', onfinish);
9648 };
9649
9650 if (isRequest(stream)) {
9651 stream.on('complete', onfinish);
9652 stream.on('abort', onclose);
9653 if (stream.req) onrequest();else stream.on('request', onrequest);
9654 } else if (writable && !stream._writableState) {
9655 // legacy streams
9656 stream.on('end', onlegacyfinish);
9657 stream.on('close', onlegacyfinish);
9658 }
9659
9660 stream.on('end', onend);
9661 stream.on('finish', onfinish);
9662 if (opts.error !== false) stream.on('error', onerror);
9663 stream.on('close', onclose);
9664 return function () {
9665 stream.removeListener('complete', onfinish);
9666 stream.removeListener('abort', onclose);
9667 stream.removeListener('request', onrequest);
9668 if (stream.req) stream.req.removeListener('finish', onfinish);
9669 stream.removeListener('end', onlegacyfinish);
9670 stream.removeListener('close', onlegacyfinish);
9671 stream.removeListener('finish', onfinish);
9672 stream.removeListener('end', onend);
9673 stream.removeListener('error', onerror);
9674 stream.removeListener('close', onclose);
9675 };
9676}
9677
9678module.exports = eos;
9679},{"36":36}],46:[function(_dereq_,module,exports){
9680module.exports = function () {
9681 throw new Error('Readable.from is not available in the browser')
9682};
9683
9684},{}],47:[function(_dereq_,module,exports){
9685// Ported from https://github.com/mafintosh/pump with
9686// permission from the author, Mathias Buus (@mafintosh).
9687'use strict';
9688
9689var eos;
9690
9691function once(callback) {
9692 var called = false;
9693 return function () {
9694 if (called) return;
9695 called = true;
9696 callback.apply(void 0, arguments);
9697 };
9698}
9699
9700var _require$codes = _dereq_(36).codes,
9701 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
9702 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
9703
9704function noop(err) {
9705 // Rethrow the error if it exists to avoid swallowing it
9706 if (err) throw err;
9707}
9708
9709function isRequest(stream) {
9710 return stream.setHeader && typeof stream.abort === 'function';
9711}
9712
9713function destroyer(stream, reading, writing, callback) {
9714 callback = once(callback);
9715 var closed = false;
9716 stream.on('close', function () {
9717 closed = true;
9718 });
9719 if (eos === undefined) eos = _dereq_(45);
9720 eos(stream, {
9721 readable: reading,
9722 writable: writing
9723 }, function (err) {
9724 if (err) return callback(err);
9725 closed = true;
9726 callback();
9727 });
9728 var destroyed = false;
9729 return function (err) {
9730 if (closed) return;
9731 if (destroyed) return;
9732 destroyed = true; // request.destroy just do .end - .abort is what we want
9733
9734 if (isRequest(stream)) return stream.abort();
9735 if (typeof stream.destroy === 'function') return stream.destroy();
9736 callback(err || new ERR_STREAM_DESTROYED('pipe'));
9737 };
9738}
9739
9740function call(fn) {
9741 fn();
9742}
9743
9744function pipe(from, to) {
9745 return from.pipe(to);
9746}
9747
9748function popCallback(streams) {
9749 if (!streams.length) return noop;
9750 if (typeof streams[streams.length - 1] !== 'function') return noop;
9751 return streams.pop();
9752}
9753
9754function pipeline() {
9755 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
9756 streams[_key] = arguments[_key];
9757 }
9758
9759 var callback = popCallback(streams);
9760 if (Array.isArray(streams[0])) streams = streams[0];
9761
9762 if (streams.length < 2) {
9763 throw new ERR_MISSING_ARGS('streams');
9764 }
9765
9766 var error;
9767 var destroys = streams.map(function (stream, i) {
9768 var reading = i < streams.length - 1;
9769 var writing = i > 0;
9770 return destroyer(stream, reading, writing, function (err) {
9771 if (!error) error = err;
9772 if (err) destroys.forEach(call);
9773 if (reading) return;
9774 destroys.forEach(call);
9775 callback(error);
9776 });
9777 });
9778 return streams.reduce(pipe);
9779}
9780
9781module.exports = pipeline;
9782},{"36":36,"45":45}],48:[function(_dereq_,module,exports){
9783'use strict';
9784
9785var ERR_INVALID_OPT_VALUE = _dereq_(36).codes.ERR_INVALID_OPT_VALUE;
9786
9787function highWaterMarkFrom(options, isDuplex, duplexKey) {
9788 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
9789}
9790
9791function getHighWaterMark(state, options, duplexKey, isDuplex) {
9792 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
9793
9794 if (hwm != null) {
9795 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
9796 var name = isDuplex ? duplexKey : 'highWaterMark';
9797 throw new ERR_INVALID_OPT_VALUE(name, hwm);
9798 }
9799
9800 return Math.floor(hwm);
9801 } // Default value
9802
9803
9804 return state.objectMode ? 16 : 16 * 1024;
9805}
9806
9807module.exports = {
9808 getHighWaterMark: getHighWaterMark
9809};
9810},{"36":36}],49:[function(_dereq_,module,exports){
9811module.exports = _dereq_(21).EventEmitter;
9812
9813},{"21":21}],50:[function(_dereq_,module,exports){
9814exports = module.exports = _dereq_(39);
9815exports.Stream = exports;
9816exports.Readable = exports;
9817exports.Writable = _dereq_(41);
9818exports.Duplex = _dereq_(37);
9819exports.Transform = _dereq_(40);
9820exports.PassThrough = _dereq_(38);
9821exports.finished = _dereq_(45);
9822exports.pipeline = _dereq_(47);
9823
9824},{"37":37,"38":38,"39":39,"40":40,"41":41,"45":45,"47":47}],51:[function(_dereq_,module,exports){
9825'use strict'
9826
9827// For (old) browser support
9828var xtend = _dereq_(134)
9829var assign = _dereq_(135)
9830
9831module.exports = function supports () {
9832 var manifest = xtend.apply(null, arguments)
9833
9834 return assign(manifest, {
9835 // Features of abstract-leveldown
9836 bufferKeys: manifest.bufferKeys || false,
9837 snapshots: manifest.snapshots || false,
9838 permanence: manifest.permanence || false,
9839 seek: manifest.seek || false,
9840 clear: manifest.clear || false,
9841
9842 // Features of abstract-leveldown that levelup doesn't have
9843 status: manifest.status || false,
9844
9845 // Features of disk-based implementations
9846 createIfMissing: manifest.createIfMissing || false,
9847 errorIfExists: manifest.errorIfExists || false,
9848
9849 // Features of level(up) that abstract-leveldown doesn't have yet
9850 deferredOpen: manifest.deferredOpen || false,
9851 openCallback: manifest.openCallback || false,
9852 promises: manifest.promises || false,
9853 streams: manifest.streams || false,
9854 encodings: manifest.encodings || false,
9855
9856 // Methods that are not part of abstract-leveldown or levelup
9857 additionalMethods: xtend(manifest.additionalMethods)
9858 })
9859}
9860
9861},{"134":134,"135":135}],52:[function(_dereq_,module,exports){
9862var WriteError = _dereq_(34).WriteError
9863var promisify = _dereq_(55)
9864var getCallback = _dereq_(53).getCallback
9865var getOptions = _dereq_(53).getOptions
9866
9867function Batch (levelup) {
9868 // TODO (next major): remove this._levelup alias
9869 this.db = this._levelup = levelup
9870 this.batch = levelup.db.batch()
9871 this.ops = []
9872 this.length = 0
9873}
9874
9875Batch.prototype.put = function (key, value) {
9876 try {
9877 this.batch.put(key, value)
9878 } catch (e) {
9879 throw new WriteError(e)
9880 }
9881
9882 this.ops.push({ type: 'put', key: key, value: value })
9883 this.length++
9884
9885 return this
9886}
9887
9888Batch.prototype.del = function (key) {
9889 try {
9890 this.batch.del(key)
9891 } catch (err) {
9892 throw new WriteError(err)
9893 }
9894
9895 this.ops.push({ type: 'del', key: key })
9896 this.length++
9897
9898 return this
9899}
9900
9901Batch.prototype.clear = function () {
9902 try {
9903 this.batch.clear()
9904 } catch (err) {
9905 throw new WriteError(err)
9906 }
9907
9908 this.ops = []
9909 this.length = 0
9910
9911 return this
9912}
9913
9914Batch.prototype.write = function (options, callback) {
9915 var levelup = this._levelup
9916 var ops = this.ops
9917 var promise
9918
9919 callback = getCallback(options, callback)
9920
9921 if (!callback) {
9922 callback = promisify()
9923 promise = callback.promise
9924 }
9925
9926 options = getOptions(options)
9927
9928 try {
9929 this.batch.write(options, function (err) {
9930 if (err) { return callback(new WriteError(err)) }
9931 levelup.emit('batch', ops)
9932 callback()
9933 })
9934 } catch (err) {
9935 throw new WriteError(err)
9936 }
9937
9938 return promise
9939}
9940
9941module.exports = Batch
9942
9943},{"34":34,"53":53,"55":55}],53:[function(_dereq_,module,exports){
9944exports.getCallback = function (options, callback) {
9945 return typeof options === 'function' ? options : callback
9946}
9947
9948exports.getOptions = function (options) {
9949 return typeof options === 'object' && options !== null ? options : {}
9950}
9951
9952},{}],54:[function(_dereq_,module,exports){
9953(function (process){(function (){
9954var EventEmitter = _dereq_(21).EventEmitter
9955var inherits = _dereq_(117).inherits
9956var extend = _dereq_(134)
9957var DeferredLevelDOWN = _dereq_(12)
9958var IteratorStream = _dereq_(35)
9959var Batch = _dereq_(52)
9960var errors = _dereq_(34)
9961var supports = _dereq_(51)
9962var assert = _dereq_(2)
9963var promisify = _dereq_(55)
9964var getCallback = _dereq_(53).getCallback
9965var getOptions = _dereq_(53).getOptions
9966
9967var WriteError = errors.WriteError
9968var ReadError = errors.ReadError
9969var NotFoundError = errors.NotFoundError
9970var OpenError = errors.OpenError
9971var InitializationError = errors.InitializationError
9972
9973// Possible AbstractLevelDOWN#status values:
9974// - 'new' - newly created, not opened or closed
9975// - 'opening' - waiting for the database to be opened, post open()
9976// - 'open' - successfully opened the database, available for use
9977// - 'closing' - waiting for the database to be closed, post close()
9978// - 'closed' - database has been successfully closed, should not be
9979// used except for another open() operation
9980
9981function LevelUP (db, options, callback) {
9982 if (!(this instanceof LevelUP)) {
9983 return new LevelUP(db, options, callback)
9984 }
9985
9986 var error
9987 var self = this
9988
9989 EventEmitter.call(this)
9990 this.setMaxListeners(Infinity)
9991
9992 if (typeof options === 'function') {
9993 callback = options
9994 options = {}
9995 }
9996
9997 options = options || {}
9998
9999 if (!db || typeof db !== 'object') {
10000 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
10001 if (typeof callback === 'function') {
10002 return process.nextTick(callback, error)
10003 }
10004 throw error
10005 }
10006
10007 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
10008
10009 this.options = getOptions(options)
10010 this._db = db
10011 this.db = new DeferredLevelDOWN(db)
10012 this.open(callback || function (err) {
10013 if (err) self.emit('error', err)
10014 })
10015
10016 // Create manifest based on deferred-leveldown's
10017 this.supports = supports(this.db.supports, {
10018 status: false,
10019 deferredOpen: true,
10020 openCallback: true,
10021 promises: true,
10022 streams: true
10023 })
10024
10025 // Experimental: enrich levelup interface
10026 Object.keys(this.supports.additionalMethods).forEach(function (method) {
10027 if (this[method] != null) return
10028
10029 // Don't do this.db[method].bind() because this.db is dynamic.
10030 this[method] = function () {
10031 return this.db[method].apply(this.db, arguments)
10032 }
10033 }, this)
10034}
10035
10036LevelUP.prototype.emit = EventEmitter.prototype.emit
10037LevelUP.prototype.once = EventEmitter.prototype.once
10038inherits(LevelUP, EventEmitter)
10039
10040LevelUP.prototype.open = function (opts, callback) {
10041 var self = this
10042 var promise
10043
10044 if (typeof opts === 'function') {
10045 callback = opts
10046 opts = null
10047 }
10048
10049 if (!callback) {
10050 callback = promisify()
10051 promise = callback.promise
10052 }
10053
10054 if (!opts) {
10055 opts = this.options
10056 }
10057
10058 if (this.isOpen()) {
10059 process.nextTick(callback, null, self)
10060 return promise
10061 }
10062
10063 if (this._isOpening()) {
10064 this.once('open', function () { callback(null, self) })
10065 return promise
10066 }
10067
10068 this.emit('opening')
10069
10070 this.db.open(opts, function (err) {
10071 if (err) {
10072 return callback(new OpenError(err))
10073 }
10074 self.db = self._db
10075 callback(null, self)
10076 self.emit('open')
10077 self.emit('ready')
10078 })
10079
10080 return promise
10081}
10082
10083LevelUP.prototype.close = function (callback) {
10084 var self = this
10085 var promise
10086
10087 if (!callback) {
10088 callback = promisify()
10089 promise = callback.promise
10090 }
10091
10092 if (this.isOpen()) {
10093 this.db.close(function () {
10094 self.emit('closed')
10095 callback.apply(null, arguments)
10096 })
10097 this.emit('closing')
10098 this.db = new DeferredLevelDOWN(this._db)
10099 } else if (this.isClosed()) {
10100 process.nextTick(callback)
10101 } else if (this.db.status === 'closing') {
10102 this.once('closed', callback)
10103 } else if (this._isOpening()) {
10104 this.once('open', function () {
10105 self.close(callback)
10106 })
10107 }
10108
10109 return promise
10110}
10111
10112LevelUP.prototype.isOpen = function () {
10113 return this.db.status === 'open'
10114}
10115
10116LevelUP.prototype._isOpening = function () {
10117 return this.db.status === 'opening'
10118}
10119
10120LevelUP.prototype.isClosed = function () {
10121 return (/^clos|new/).test(this.db.status)
10122}
10123
10124LevelUP.prototype.get = function (key, options, callback) {
10125 var promise
10126
10127 callback = getCallback(options, callback)
10128
10129 if (!callback) {
10130 callback = promisify()
10131 promise = callback.promise
10132 }
10133
10134 if (maybeError(this, callback)) { return promise }
10135
10136 options = getOptions(options)
10137
10138 this.db.get(key, options, function (err, value) {
10139 if (err) {
10140 if ((/notfound/i).test(err) || err.notFound) {
10141 err = new NotFoundError('Key not found in database [' + key + ']', err)
10142 } else {
10143 err = new ReadError(err)
10144 }
10145 return callback(err)
10146 }
10147 callback(null, value)
10148 })
10149
10150 return promise
10151}
10152
10153LevelUP.prototype.put = function (key, value, options, callback) {
10154 var self = this
10155 var promise
10156
10157 callback = getCallback(options, callback)
10158
10159 if (!callback) {
10160 callback = promisify()
10161 promise = callback.promise
10162 }
10163
10164 if (maybeError(this, callback)) { return promise }
10165
10166 options = getOptions(options)
10167
10168 this.db.put(key, value, options, function (err) {
10169 if (err) {
10170 return callback(new WriteError(err))
10171 }
10172 self.emit('put', key, value)
10173 callback()
10174 })
10175
10176 return promise
10177}
10178
10179LevelUP.prototype.del = function (key, options, callback) {
10180 var self = this
10181 var promise
10182
10183 callback = getCallback(options, callback)
10184
10185 if (!callback) {
10186 callback = promisify()
10187 promise = callback.promise
10188 }
10189
10190 if (maybeError(this, callback)) { return promise }
10191
10192 options = getOptions(options)
10193
10194 this.db.del(key, options, function (err) {
10195 if (err) {
10196 return callback(new WriteError(err))
10197 }
10198 self.emit('del', key)
10199 callback()
10200 })
10201
10202 return promise
10203}
10204
10205LevelUP.prototype.batch = function (arr, options, callback) {
10206 if (!arguments.length) {
10207 return new Batch(this)
10208 }
10209
10210 var self = this
10211 var promise
10212
10213 if (typeof arr === 'function') callback = arr
10214 else callback = getCallback(options, callback)
10215
10216 if (!callback) {
10217 callback = promisify()
10218 promise = callback.promise
10219 }
10220
10221 if (maybeError(this, callback)) { return promise }
10222
10223 options = getOptions(options)
10224
10225 this.db.batch(arr, options, function (err) {
10226 if (err) {
10227 return callback(new WriteError(err))
10228 }
10229 self.emit('batch', arr)
10230 callback()
10231 })
10232
10233 return promise
10234}
10235
10236LevelUP.prototype.iterator = function (options) {
10237 return this.db.iterator(options)
10238}
10239
10240LevelUP.prototype.clear = function (options, callback) {
10241 var self = this
10242 var promise
10243
10244 callback = getCallback(options, callback)
10245 options = getOptions(options)
10246
10247 if (!callback) {
10248 callback = promisify()
10249 promise = callback.promise
10250 }
10251
10252 if (maybeError(this, callback)) {
10253 return promise
10254 }
10255
10256 this.db.clear(options, function (err) {
10257 if (err) {
10258 return callback(new WriteError(err))
10259 }
10260 self.emit('clear', options)
10261 callback()
10262 })
10263
10264 return promise
10265}
10266
10267LevelUP.prototype.readStream =
10268LevelUP.prototype.createReadStream = function (options) {
10269 options = extend({ keys: true, values: true }, options)
10270 if (typeof options.limit !== 'number') { options.limit = -1 }
10271 return new IteratorStream(this.db.iterator(options), options)
10272}
10273
10274LevelUP.prototype.keyStream =
10275LevelUP.prototype.createKeyStream = function (options) {
10276 return this.createReadStream(extend(options, { keys: true, values: false }))
10277}
10278
10279LevelUP.prototype.valueStream =
10280LevelUP.prototype.createValueStream = function (options) {
10281 return this.createReadStream(extend(options, { keys: false, values: true }))
10282}
10283
10284LevelUP.prototype.toString = function () {
10285 return 'LevelUP'
10286}
10287
10288LevelUP.prototype.type = 'levelup'
10289
10290function maybeError (db, callback) {
10291 if (!db._isOpening() && !db.isOpen()) {
10292 process.nextTick(callback, new ReadError('Database is not open'))
10293 return true
10294 }
10295}
10296
10297LevelUP.errors = errors
10298module.exports = LevelUP.default = LevelUP
10299
10300}).call(this)}).call(this,_dereq_(67))
10301},{"117":117,"12":12,"134":134,"2":2,"21":21,"34":34,"35":35,"51":51,"52":52,"53":53,"55":55,"67":67}],55:[function(_dereq_,module,exports){
10302function promisify () {
10303 var callback
10304 var promise = new Promise(function (resolve, reject) {
10305 callback = function callback (err, value) {
10306 if (err) reject(err)
10307 else resolve(value)
10308 }
10309 })
10310 callback.promise = promise
10311 return callback
10312}
10313
10314module.exports = promisify
10315
10316},{}],56:[function(_dereq_,module,exports){
10317(function (Buffer){(function (){
10318
10319exports.compare = function (a, b) {
10320
10321 if(Buffer.isBuffer(a)) {
10322 var l = Math.min(a.length, b.length)
10323 for(var i = 0; i < l; i++) {
10324 var cmp = a[i] - b[i]
10325 if(cmp) return cmp
10326 }
10327 return a.length - b.length
10328 }
10329
10330 return a < b ? -1 : a > b ? 1 : 0
10331}
10332
10333// to be compatible with the current abstract-leveldown tests
10334// nullish or empty strings.
10335// I could use !!val but I want to permit numbers and booleans,
10336// if possible.
10337
10338function isDef (val) {
10339 return val !== undefined && val !== ''
10340}
10341
10342function has (range, name) {
10343 return Object.hasOwnProperty.call(range, name)
10344}
10345
10346function hasKey(range, name) {
10347 return Object.hasOwnProperty.call(range, name) && name
10348}
10349
10350var lowerBoundKey = exports.lowerBoundKey = function (range) {
10351 return (
10352 hasKey(range, 'gt')
10353 || hasKey(range, 'gte')
10354 || hasKey(range, 'min')
10355 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10356 || undefined
10357 )
10358}
10359
10360var lowerBound = exports.lowerBound = function (range, def) {
10361 var k = lowerBoundKey(range)
10362 return k ? range[k] : def
10363}
10364
10365var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10366 return has(range, 'gt') ? false : true
10367}
10368
10369var upperBoundInclusive = exports.upperBoundInclusive =
10370 function (range) {
10371 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10372 }
10373
10374var lowerBoundExclusive = exports.lowerBoundExclusive =
10375 function (range) {
10376 return !lowerBoundInclusive(range)
10377 }
10378
10379var upperBoundExclusive = exports.upperBoundExclusive =
10380 function (range) {
10381 return !upperBoundInclusive(range)
10382 }
10383
10384var upperBoundKey = exports.upperBoundKey = function (range) {
10385 return (
10386 hasKey(range, 'lt')
10387 || hasKey(range, 'lte')
10388 || hasKey(range, 'max')
10389 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10390 || undefined
10391 )
10392}
10393
10394var upperBound = exports.upperBound = function (range, def) {
10395 var k = upperBoundKey(range)
10396 return k ? range[k] : def
10397}
10398
10399exports.start = function (range, def) {
10400 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
10401}
10402exports.end = function (range, def) {
10403 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10404}
10405exports.startInclusive = function (range) {
10406 return (
10407 range.reverse
10408 ? upperBoundInclusive(range)
10409 : lowerBoundInclusive(range)
10410 )
10411}
10412exports.endInclusive = function (range) {
10413 return (
10414 range.reverse
10415 ? lowerBoundInclusive(range)
10416 : upperBoundInclusive(range)
10417 )
10418}
10419
10420function id (e) { return e }
10421
10422exports.toLtgt = function (range, _range, map, lower, upper) {
10423 _range = _range || {}
10424 map = map || id
10425 var defaults = arguments.length > 3
10426 var lb = exports.lowerBoundKey(range)
10427 var ub = exports.upperBoundKey(range)
10428 if(lb) {
10429 if(lb === 'gt') _range.gt = map(range.gt, false)
10430 else _range.gte = map(range[lb], false)
10431 }
10432 else if(defaults)
10433 _range.gte = map(lower, false)
10434
10435 if(ub) {
10436 if(ub === 'lt') _range.lt = map(range.lt, true)
10437 else _range.lte = map(range[ub], true)
10438 }
10439 else if(defaults)
10440 _range.lte = map(upper, true)
10441
10442 if(range.reverse != null)
10443 _range.reverse = !!range.reverse
10444
10445 //if range was used mutably
10446 //(in level-sublevel it's part of an options object
10447 //that has more properties on it.)
10448 if(has(_range, 'max')) delete _range.max
10449 if(has(_range, 'min')) delete _range.min
10450 if(has(_range, 'start')) delete _range.start
10451 if(has(_range, 'end')) delete _range.end
10452
10453 return _range
10454}
10455
10456exports.contains = function (range, key, compare) {
10457 compare = compare || exports.compare
10458
10459 var lb = lowerBound(range)
10460 if(isDef(lb)) {
10461 var cmp = compare(key, lb)
10462 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10463 return false
10464 }
10465
10466 var ub = upperBound(range)
10467 if(isDef(ub)) {
10468 var cmp = compare(key, ub)
10469 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10470 return false
10471 }
10472
10473 return true
10474}
10475
10476exports.filter = function (range, compare) {
10477 return function (key) {
10478 return exports.contains(range, key, compare)
10479 }
10480}
10481
10482
10483
10484}).call(this)}).call(this,{"isBuffer":_dereq_(31)})
10485},{"31":31}],57:[function(_dereq_,module,exports){
10486arguments[4][17][0].apply(exports,arguments)
10487},{"17":17,"24":24}],58:[function(_dereq_,module,exports){
10488var inherits = _dereq_(30)
10489var AbstractLevelDOWN = _dereq_(62).AbstractLevelDOWN
10490var AbstractIterator = _dereq_(62).AbstractIterator
10491var ltgt = _dereq_(56)
10492var createRBT = _dereq_(22)
10493var Buffer = _dereq_(64).Buffer
10494var globalStore = {}
10495
10496// In Node, use global.setImmediate. In the browser, use a consistent
10497// microtask library to give consistent microtask experience to all browsers
10498var setImmediate = _dereq_(57)
10499
10500function gt (value) {
10501 return ltgt.compare(value, this._end) > 0
10502}
10503
10504function gte (value) {
10505 return ltgt.compare(value, this._end) >= 0
10506}
10507
10508function lt (value) {
10509 return ltgt.compare(value, this._end) < 0
10510}
10511
10512function lte (value) {
10513 return ltgt.compare(value, this._end) <= 0
10514}
10515
10516function MemIterator (db, options) {
10517 AbstractIterator.call(this, db)
10518 this._limit = options.limit
10519
10520 if (this._limit === -1) this._limit = Infinity
10521
10522 var tree = db._store[db._location]
10523
10524 this.keyAsBuffer = options.keyAsBuffer !== false
10525 this.valueAsBuffer = options.valueAsBuffer !== false
10526 this._reverse = options.reverse
10527 this._options = options
10528 this._done = 0
10529
10530 if (!this._reverse) {
10531 this._incr = 'next'
10532 this._start = ltgt.lowerBound(options)
10533 this._end = ltgt.upperBound(options)
10534
10535 if (typeof this._start === 'undefined') {
10536 this._tree = tree.begin
10537 } else if (ltgt.lowerBoundInclusive(options)) {
10538 this._tree = tree.ge(this._start)
10539 } else {
10540 this._tree = tree.gt(this._start)
10541 }
10542
10543 if (this._end) {
10544 if (ltgt.upperBoundInclusive(options)) {
10545 this._test = lte
10546 } else {
10547 this._test = lt
10548 }
10549 }
10550 } else {
10551 this._incr = 'prev'
10552 this._start = ltgt.upperBound(options)
10553 this._end = ltgt.lowerBound(options)
10554
10555 if (typeof this._start === 'undefined') {
10556 this._tree = tree.end
10557 } else if (ltgt.upperBoundInclusive(options)) {
10558 this._tree = tree.le(this._start)
10559 } else {
10560 this._tree = tree.lt(this._start)
10561 }
10562
10563 if (this._end) {
10564 if (ltgt.lowerBoundInclusive(options)) {
10565 this._test = gte
10566 } else {
10567 this._test = gt
10568 }
10569 }
10570 }
10571}
10572
10573inherits(MemIterator, AbstractIterator)
10574
10575MemIterator.prototype._next = function (callback) {
10576 var key
10577 var value
10578
10579 if (this._done++ >= this._limit) return setImmediate(callback)
10580 if (!this._tree.valid) return setImmediate(callback)
10581
10582 key = this._tree.key
10583 value = this._tree.value
10584
10585 if (!this._test(key)) return setImmediate(callback)
10586
10587 if (this.keyAsBuffer) key = Buffer.from(key)
10588 if (this.valueAsBuffer) value = Buffer.from(value)
10589
10590 this._tree[this._incr]()
10591
10592 setImmediate(function callNext () {
10593 callback(null, key, value)
10594 })
10595}
10596
10597MemIterator.prototype._test = function () {
10598 return true
10599}
10600
10601function MemDOWN (location) {
10602 if (!(this instanceof MemDOWN)) return new MemDOWN(location)
10603
10604 AbstractLevelDOWN.call(this, typeof location === 'string' ? location : '')
10605
10606 this._location = this.location ? '$' + this.location : '_tree'
10607 this._store = this.location ? globalStore : this
10608 this._store[this._location] =
10609 this._store[this._location] || createRBT(ltgt.compare)
10610}
10611
10612MemDOWN.clearGlobalStore = function (strict) {
10613 if (strict) {
10614 Object.keys(globalStore).forEach(function (key) {
10615 delete globalStore[key]
10616 })
10617 } else {
10618 globalStore = {}
10619 }
10620}
10621
10622inherits(MemDOWN, AbstractLevelDOWN)
10623
10624MemDOWN.prototype._open = function (options, callback) {
10625 var self = this
10626 setImmediate(function callNext () {
10627 callback(null, self)
10628 })
10629}
10630
10631MemDOWN.prototype._put = function (key, value, options, callback) {
10632 if (typeof value === 'undefined' || value === null) value = ''
10633
10634 var iter = this._store[this._location].find(key)
10635
10636 if (iter.valid) {
10637 this._store[this._location] = iter.update(value)
10638 } else {
10639 this._store[this._location] = this._store[this._location].insert(key, value)
10640 }
10641
10642 setImmediate(callback)
10643}
10644
10645MemDOWN.prototype._get = function (key, options, callback) {
10646 var value = this._store[this._location].get(key)
10647
10648 if (typeof value === 'undefined') {
10649 // 'NotFound' error, consistent with LevelDOWN API
10650 return setImmediate(function callNext () {
10651 callback(new Error('NotFound'))
10652 })
10653 }
10654
10655 if (options.asBuffer !== false && !this._isBuffer(value)) {
10656 value = Buffer.from(String(value))
10657 }
10658
10659 setImmediate(function callNext () {
10660 callback(null, value)
10661 })
10662}
10663
10664MemDOWN.prototype._del = function (key, options, callback) {
10665 this._store[this._location] = this._store[this._location].remove(key)
10666 setImmediate(callback)
10667}
10668
10669MemDOWN.prototype._batch = function (array, options, callback) {
10670 var i = -1
10671 var key
10672 var value
10673 var iter
10674 var len = array.length
10675 var tree = this._store[this._location]
10676
10677 while (++i < len) {
10678 if (!array[i]) continue
10679
10680 key = this._isBuffer(array[i].key) ? array[i].key : String(array[i].key)
10681 iter = tree.find(key)
10682
10683 if (array[i].type === 'put') {
10684 value = this._isBuffer(array[i].value)
10685 ? array[i].value
10686 : String(array[i].value)
10687 tree = iter.valid ? iter.update(value) : tree.insert(key, value)
10688 } else {
10689 tree = iter.remove()
10690 }
10691 }
10692
10693 this._store[this._location] = tree
10694
10695 setImmediate(callback)
10696}
10697
10698MemDOWN.prototype._iterator = function (options) {
10699 return new MemIterator(this, options)
10700}
10701
10702MemDOWN.prototype._isBuffer = function (obj) {
10703 return Buffer.isBuffer(obj)
10704}
10705
10706MemDOWN.destroy = function (name, callback) {
10707 var key = '$' + name
10708
10709 if (key in globalStore) {
10710 delete globalStore[key]
10711 }
10712
10713 setImmediate(callback)
10714}
10715
10716module.exports = MemDOWN.default = MemDOWN
10717
10718},{"22":22,"30":30,"56":56,"57":57,"62":62,"64":64}],59:[function(_dereq_,module,exports){
10719(function (process){(function (){
10720/* Copyright (c) 2017 Rod Vagg, MIT License */
10721
10722function AbstractChainedBatch (db) {
10723 this._db = db
10724 this._operations = []
10725 this._written = false
10726}
10727
10728AbstractChainedBatch.prototype._serializeKey = function (key) {
10729 return this._db._serializeKey(key)
10730}
10731
10732AbstractChainedBatch.prototype._serializeValue = function (value) {
10733 return this._db._serializeValue(value)
10734}
10735
10736AbstractChainedBatch.prototype._checkWritten = function () {
10737 if (this._written)
10738 throw new Error('write() already called on this batch')
10739}
10740
10741AbstractChainedBatch.prototype.put = function (key, value) {
10742 this._checkWritten()
10743
10744 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10745 if (err)
10746 throw err
10747
10748 key = this._serializeKey(key)
10749 value = this._serializeValue(value)
10750
10751 if (typeof this._put == 'function' )
10752 this._put(key, value)
10753 else
10754 this._operations.push({ type: 'put', key: key, value: value })
10755
10756 return this
10757}
10758
10759AbstractChainedBatch.prototype.del = function (key) {
10760 this._checkWritten()
10761
10762 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10763 if (err) throw err
10764
10765 key = this._serializeKey(key)
10766
10767 if (typeof this._del == 'function' )
10768 this._del(key)
10769 else
10770 this._operations.push({ type: 'del', key: key })
10771
10772 return this
10773}
10774
10775AbstractChainedBatch.prototype.clear = function () {
10776 this._checkWritten()
10777
10778 this._operations = []
10779
10780 if (typeof this._clear == 'function' )
10781 this._clear()
10782
10783 return this
10784}
10785
10786AbstractChainedBatch.prototype.write = function (options, callback) {
10787 this._checkWritten()
10788
10789 if (typeof options == 'function')
10790 callback = options
10791 if (typeof callback != 'function')
10792 throw new Error('write() requires a callback argument')
10793 if (typeof options != 'object')
10794 options = {}
10795
10796 this._written = true
10797
10798 if (typeof this._write == 'function' )
10799 return this._write(callback)
10800
10801 if (typeof this._db._batch == 'function')
10802 return this._db._batch(this._operations, options, callback)
10803
10804 process.nextTick(callback)
10805}
10806
10807module.exports = AbstractChainedBatch
10808
10809}).call(this)}).call(this,_dereq_(67))
10810},{"67":67}],60:[function(_dereq_,module,exports){
10811(function (process){(function (){
10812/* Copyright (c) 2017 Rod Vagg, MIT License */
10813
10814function AbstractIterator (db) {
10815 this.db = db
10816 this._ended = false
10817 this._nexting = false
10818}
10819
10820AbstractIterator.prototype.next = function (callback) {
10821 var self = this
10822
10823 if (typeof callback != 'function')
10824 throw new Error('next() requires a callback argument')
10825
10826 if (self._ended)
10827 return callback(new Error('cannot call next() after end()'))
10828 if (self._nexting)
10829 return callback(new Error('cannot call next() before previous next() has completed'))
10830
10831 self._nexting = true
10832 if (typeof self._next == 'function') {
10833 return self._next(function () {
10834 self._nexting = false
10835 callback.apply(null, arguments)
10836 })
10837 }
10838
10839 process.nextTick(function () {
10840 self._nexting = false
10841 callback()
10842 })
10843}
10844
10845AbstractIterator.prototype.end = function (callback) {
10846 if (typeof callback != 'function')
10847 throw new Error('end() requires a callback argument')
10848
10849 if (this._ended)
10850 return callback(new Error('end() already called on iterator'))
10851
10852 this._ended = true
10853
10854 if (typeof this._end == 'function')
10855 return this._end(callback)
10856
10857 process.nextTick(callback)
10858}
10859
10860module.exports = AbstractIterator
10861
10862}).call(this)}).call(this,_dereq_(67))
10863},{"67":67}],61:[function(_dereq_,module,exports){
10864(function (Buffer,process){(function (){
10865/* Copyright (c) 2017 Rod Vagg, MIT License */
10866
10867var xtend = _dereq_(134)
10868 , AbstractIterator = _dereq_(60)
10869 , AbstractChainedBatch = _dereq_(59)
10870
10871function AbstractLevelDOWN (location) {
10872 if (!arguments.length || location === undefined)
10873 throw new Error('constructor requires at least a location argument')
10874
10875 if (typeof location != 'string')
10876 throw new Error('constructor requires a location string argument')
10877
10878 this.location = location
10879 this.status = 'new'
10880}
10881
10882AbstractLevelDOWN.prototype.open = function (options, callback) {
10883 var self = this
10884 , oldStatus = this.status
10885
10886 if (typeof options == 'function')
10887 callback = options
10888
10889 if (typeof callback != 'function')
10890 throw new Error('open() requires a callback argument')
10891
10892 if (typeof options != 'object')
10893 options = {}
10894
10895 options.createIfMissing = options.createIfMissing != false
10896 options.errorIfExists = !!options.errorIfExists
10897
10898 if (typeof this._open == 'function') {
10899 this.status = 'opening'
10900 this._open(options, function (err) {
10901 if (err) {
10902 self.status = oldStatus
10903 return callback(err)
10904 }
10905 self.status = 'open'
10906 callback()
10907 })
10908 } else {
10909 this.status = 'open'
10910 process.nextTick(callback)
10911 }
10912}
10913
10914AbstractLevelDOWN.prototype.close = function (callback) {
10915 var self = this
10916 , oldStatus = this.status
10917
10918 if (typeof callback != 'function')
10919 throw new Error('close() requires a callback argument')
10920
10921 if (typeof this._close == 'function') {
10922 this.status = 'closing'
10923 this._close(function (err) {
10924 if (err) {
10925 self.status = oldStatus
10926 return callback(err)
10927 }
10928 self.status = 'closed'
10929 callback()
10930 })
10931 } else {
10932 this.status = 'closed'
10933 process.nextTick(callback)
10934 }
10935}
10936
10937AbstractLevelDOWN.prototype.get = function (key, options, callback) {
10938 var err
10939
10940 if (typeof options == 'function')
10941 callback = options
10942
10943 if (typeof callback != 'function')
10944 throw new Error('get() requires a callback argument')
10945
10946 if (err = this._checkKey(key, 'key'))
10947 return callback(err)
10948
10949 key = this._serializeKey(key)
10950
10951 if (typeof options != 'object')
10952 options = {}
10953
10954 options.asBuffer = options.asBuffer != false
10955
10956 if (typeof this._get == 'function')
10957 return this._get(key, options, callback)
10958
10959 process.nextTick(function () { callback(new Error('NotFound')) })
10960}
10961
10962AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
10963 var err
10964
10965 if (typeof options == 'function')
10966 callback = options
10967
10968 if (typeof callback != 'function')
10969 throw new Error('put() requires a callback argument')
10970
10971 if (err = this._checkKey(key, 'key'))
10972 return callback(err)
10973
10974 key = this._serializeKey(key)
10975 value = this._serializeValue(value)
10976
10977 if (typeof options != 'object')
10978 options = {}
10979
10980 if (typeof this._put == 'function')
10981 return this._put(key, value, options, callback)
10982
10983 process.nextTick(callback)
10984}
10985
10986AbstractLevelDOWN.prototype.del = function (key, options, callback) {
10987 var err
10988
10989 if (typeof options == 'function')
10990 callback = options
10991
10992 if (typeof callback != 'function')
10993 throw new Error('del() requires a callback argument')
10994
10995 if (err = this._checkKey(key, 'key'))
10996 return callback(err)
10997
10998 key = this._serializeKey(key)
10999
11000 if (typeof options != 'object')
11001 options = {}
11002
11003 if (typeof this._del == 'function')
11004 return this._del(key, options, callback)
11005
11006 process.nextTick(callback)
11007}
11008
11009AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
11010 if (!arguments.length)
11011 return this._chainedBatch()
11012
11013 if (typeof options == 'function')
11014 callback = options
11015
11016 if (typeof array == 'function')
11017 callback = array
11018
11019 if (typeof callback != 'function')
11020 throw new Error('batch(array) requires a callback argument')
11021
11022 if (!Array.isArray(array))
11023 return callback(new Error('batch(array) requires an array argument'))
11024
11025 if (!options || typeof options != 'object')
11026 options = {}
11027
11028 var i = 0
11029 , l = array.length
11030 , e
11031 , err
11032
11033 for (; i < l; i++) {
11034 e = array[i]
11035 if (typeof e != 'object')
11036 continue
11037
11038 if (err = this._checkKey(e.type, 'type'))
11039 return callback(err)
11040
11041 if (err = this._checkKey(e.key, 'key'))
11042 return callback(err)
11043 }
11044
11045 if (typeof this._batch == 'function')
11046 return this._batch(array, options, callback)
11047
11048 process.nextTick(callback)
11049}
11050
11051//TODO: remove from here, not a necessary primitive
11052AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
11053 if ( start == null
11054 || end == null
11055 || typeof start == 'function'
11056 || typeof end == 'function') {
11057 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
11058 }
11059
11060 if (typeof callback != 'function')
11061 throw new Error('approximateSize() requires a callback argument')
11062
11063 start = this._serializeKey(start)
11064 end = this._serializeKey(end)
11065
11066 if (typeof this._approximateSize == 'function')
11067 return this._approximateSize(start, end, callback)
11068
11069 process.nextTick(function () {
11070 callback(null, 0)
11071 })
11072}
11073
11074AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
11075 var self = this
11076
11077 options = xtend(options)
11078
11079 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
11080 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
11081 delete options[o]
11082 })
11083
11084 options.reverse = !!options.reverse
11085 options.keys = options.keys != false
11086 options.values = options.values != false
11087 options.limit = 'limit' in options ? options.limit : -1
11088 options.keyAsBuffer = options.keyAsBuffer != false
11089 options.valueAsBuffer = options.valueAsBuffer != false
11090
11091 return options
11092}
11093
11094AbstractLevelDOWN.prototype.iterator = function (options) {
11095 if (typeof options != 'object')
11096 options = {}
11097
11098 options = this._setupIteratorOptions(options)
11099
11100 if (typeof this._iterator == 'function')
11101 return this._iterator(options)
11102
11103 return new AbstractIterator(this)
11104}
11105
11106AbstractLevelDOWN.prototype._chainedBatch = function () {
11107 return new AbstractChainedBatch(this)
11108}
11109
11110AbstractLevelDOWN.prototype._isBuffer = function (obj) {
11111 return Buffer.isBuffer(obj)
11112}
11113
11114AbstractLevelDOWN.prototype._serializeKey = function (key) {
11115 return this._isBuffer(key)
11116 ? key
11117 : String(key)
11118}
11119
11120AbstractLevelDOWN.prototype._serializeValue = function (value) {
11121 if (value == null) return ''
11122 return this._isBuffer(value) || process.browser ? value : String(value)
11123}
11124
11125AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
11126 if (obj === null || obj === undefined)
11127 return new Error(type + ' cannot be `null` or `undefined`')
11128
11129 if (this._isBuffer(obj) && obj.length === 0)
11130 return new Error(type + ' cannot be an empty Buffer')
11131 else if (String(obj) === '')
11132 return new Error(type + ' cannot be an empty String')
11133}
11134
11135module.exports = AbstractLevelDOWN
11136
11137}).call(this)}).call(this,{"isBuffer":_dereq_(31)},_dereq_(67))
11138},{"134":134,"31":31,"59":59,"60":60,"67":67}],62:[function(_dereq_,module,exports){
11139exports.AbstractLevelDOWN = _dereq_(61)
11140exports.AbstractIterator = _dereq_(60)
11141exports.AbstractChainedBatch = _dereq_(59)
11142exports.isLevelDOWN = _dereq_(63)
11143
11144},{"59":59,"60":60,"61":61,"63":63}],63:[function(_dereq_,module,exports){
11145var AbstractLevelDOWN = _dereq_(61)
11146
11147function isLevelDOWN (db) {
11148 if (!db || typeof db !== 'object')
11149 return false
11150 return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) {
11151 // TODO remove approximateSize check when method is gone
11152 return name[0] != '_' && name != 'approximateSize'
11153 }).every(function (name) {
11154 return typeof db[name] == 'function'
11155 })
11156}
11157
11158module.exports = isLevelDOWN
11159
11160},{"61":61}],64:[function(_dereq_,module,exports){
11161/* eslint-disable node/no-deprecated-api */
11162var buffer = _dereq_(9)
11163var Buffer = buffer.Buffer
11164
11165// alternative to using Object.keys for old browsers
11166function copyProps (src, dst) {
11167 for (var key in src) {
11168 dst[key] = src[key]
11169 }
11170}
11171if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
11172 module.exports = buffer
11173} else {
11174 // Copy properties from require('buffer')
11175 copyProps(buffer, exports)
11176 exports.Buffer = SafeBuffer
11177}
11178
11179function SafeBuffer (arg, encodingOrOffset, length) {
11180 return Buffer(arg, encodingOrOffset, length)
11181}
11182
11183// Copy static methods from Buffer
11184copyProps(Buffer, SafeBuffer)
11185
11186SafeBuffer.from = function (arg, encodingOrOffset, length) {
11187 if (typeof arg === 'number') {
11188 throw new TypeError('Argument must not be a number')
11189 }
11190 return Buffer(arg, encodingOrOffset, length)
11191}
11192
11193SafeBuffer.alloc = function (size, fill, encoding) {
11194 if (typeof size !== 'number') {
11195 throw new TypeError('Argument must be a number')
11196 }
11197 var buf = Buffer(size)
11198 if (fill !== undefined) {
11199 if (typeof encoding === 'string') {
11200 buf.fill(fill, encoding)
11201 } else {
11202 buf.fill(fill)
11203 }
11204 } else {
11205 buf.fill(0)
11206 }
11207 return buf
11208}
11209
11210SafeBuffer.allocUnsafe = function (size) {
11211 if (typeof size !== 'number') {
11212 throw new TypeError('Argument must be a number')
11213 }
11214 return Buffer(size)
11215}
11216
11217SafeBuffer.allocUnsafeSlow = function (size) {
11218 if (typeof size !== 'number') {
11219 throw new TypeError('Argument must be a number')
11220 }
11221 return buffer.SlowBuffer(size)
11222}
11223
11224},{"9":9}],65:[function(_dereq_,module,exports){
11225/*
11226object-assign
11227(c) Sindre Sorhus
11228@license MIT
11229*/
11230
11231'use strict';
11232/* eslint-disable no-unused-vars */
11233var getOwnPropertySymbols = Object.getOwnPropertySymbols;
11234var hasOwnProperty = Object.prototype.hasOwnProperty;
11235var propIsEnumerable = Object.prototype.propertyIsEnumerable;
11236
11237function toObject(val) {
11238 if (val === null || val === undefined) {
11239 throw new TypeError('Object.assign cannot be called with null or undefined');
11240 }
11241
11242 return Object(val);
11243}
11244
11245function shouldUseNative() {
11246 try {
11247 if (!Object.assign) {
11248 return false;
11249 }
11250
11251 // Detect buggy property enumeration order in older V8 versions.
11252
11253 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
11254 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
11255 test1[5] = 'de';
11256 if (Object.getOwnPropertyNames(test1)[0] === '5') {
11257 return false;
11258 }
11259
11260 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
11261 var test2 = {};
11262 for (var i = 0; i < 10; i++) {
11263 test2['_' + String.fromCharCode(i)] = i;
11264 }
11265 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
11266 return test2[n];
11267 });
11268 if (order2.join('') !== '0123456789') {
11269 return false;
11270 }
11271
11272 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
11273 var test3 = {};
11274 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
11275 test3[letter] = letter;
11276 });
11277 if (Object.keys(Object.assign({}, test3)).join('') !==
11278 'abcdefghijklmnopqrst') {
11279 return false;
11280 }
11281
11282 return true;
11283 } catch (err) {
11284 // We don't expect any of the above to throw, but better to be safe.
11285 return false;
11286 }
11287}
11288
11289module.exports = shouldUseNative() ? Object.assign : function (target, source) {
11290 var from;
11291 var to = toObject(target);
11292 var symbols;
11293
11294 for (var s = 1; s < arguments.length; s++) {
11295 from = Object(arguments[s]);
11296
11297 for (var key in from) {
11298 if (hasOwnProperty.call(from, key)) {
11299 to[key] = from[key];
11300 }
11301 }
11302
11303 if (getOwnPropertySymbols) {
11304 symbols = getOwnPropertySymbols(from);
11305 for (var i = 0; i < symbols.length; i++) {
11306 if (propIsEnumerable.call(from, symbols[i])) {
11307 to[symbols[i]] = from[symbols[i]];
11308 }
11309 }
11310 }
11311 }
11312
11313 return to;
11314};
11315
11316},{}],66:[function(_dereq_,module,exports){
11317(function (process){(function (){
11318'use strict';
11319
11320if (typeof process === 'undefined' ||
11321 !process.version ||
11322 process.version.indexOf('v0.') === 0 ||
11323 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
11324 module.exports = { nextTick: nextTick };
11325} else {
11326 module.exports = process
11327}
11328
11329function nextTick(fn, arg1, arg2, arg3) {
11330 if (typeof fn !== 'function') {
11331 throw new TypeError('"callback" argument must be a function');
11332 }
11333 var len = arguments.length;
11334 var args, i;
11335 switch (len) {
11336 case 0:
11337 case 1:
11338 return process.nextTick(fn);
11339 case 2:
11340 return process.nextTick(function afterTickOne() {
11341 fn.call(null, arg1);
11342 });
11343 case 3:
11344 return process.nextTick(function afterTickTwo() {
11345 fn.call(null, arg1, arg2);
11346 });
11347 case 4:
11348 return process.nextTick(function afterTickThree() {
11349 fn.call(null, arg1, arg2, arg3);
11350 });
11351 default:
11352 args = new Array(len - 1);
11353 i = 0;
11354 while (i < args.length) {
11355 args[i++] = arguments[i];
11356 }
11357 return process.nextTick(function afterTick() {
11358 fn.apply(null, args);
11359 });
11360 }
11361}
11362
11363
11364}).call(this)}).call(this,_dereq_(67))
11365},{"67":67}],67:[function(_dereq_,module,exports){
11366// shim for using process in browser
11367var process = module.exports = {};
11368
11369// cached from whatever global is present so that test runners that stub it
11370// don't break things. But we need to wrap it in a try catch in case it is
11371// wrapped in strict mode code which doesn't define any globals. It's inside a
11372// function because try/catches deoptimize in certain engines.
11373
11374var cachedSetTimeout;
11375var cachedClearTimeout;
11376
11377function defaultSetTimout() {
11378 throw new Error('setTimeout has not been defined');
11379}
11380function defaultClearTimeout () {
11381 throw new Error('clearTimeout has not been defined');
11382}
11383(function () {
11384 try {
11385 if (typeof setTimeout === 'function') {
11386 cachedSetTimeout = setTimeout;
11387 } else {
11388 cachedSetTimeout = defaultSetTimout;
11389 }
11390 } catch (e) {
11391 cachedSetTimeout = defaultSetTimout;
11392 }
11393 try {
11394 if (typeof clearTimeout === 'function') {
11395 cachedClearTimeout = clearTimeout;
11396 } else {
11397 cachedClearTimeout = defaultClearTimeout;
11398 }
11399 } catch (e) {
11400 cachedClearTimeout = defaultClearTimeout;
11401 }
11402} ())
11403function runTimeout(fun) {
11404 if (cachedSetTimeout === setTimeout) {
11405 //normal enviroments in sane situations
11406 return setTimeout(fun, 0);
11407 }
11408 // if setTimeout wasn't available but was latter defined
11409 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
11410 cachedSetTimeout = setTimeout;
11411 return setTimeout(fun, 0);
11412 }
11413 try {
11414 // when when somebody has screwed with setTimeout but no I.E. maddness
11415 return cachedSetTimeout(fun, 0);
11416 } catch(e){
11417 try {
11418 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11419 return cachedSetTimeout.call(null, fun, 0);
11420 } catch(e){
11421 // 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
11422 return cachedSetTimeout.call(this, fun, 0);
11423 }
11424 }
11425
11426
11427}
11428function runClearTimeout(marker) {
11429 if (cachedClearTimeout === clearTimeout) {
11430 //normal enviroments in sane situations
11431 return clearTimeout(marker);
11432 }
11433 // if clearTimeout wasn't available but was latter defined
11434 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
11435 cachedClearTimeout = clearTimeout;
11436 return clearTimeout(marker);
11437 }
11438 try {
11439 // when when somebody has screwed with setTimeout but no I.E. maddness
11440 return cachedClearTimeout(marker);
11441 } catch (e){
11442 try {
11443 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11444 return cachedClearTimeout.call(null, marker);
11445 } catch (e){
11446 // 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.
11447 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
11448 return cachedClearTimeout.call(this, marker);
11449 }
11450 }
11451
11452
11453
11454}
11455var queue = [];
11456var draining = false;
11457var currentQueue;
11458var queueIndex = -1;
11459
11460function cleanUpNextTick() {
11461 if (!draining || !currentQueue) {
11462 return;
11463 }
11464 draining = false;
11465 if (currentQueue.length) {
11466 queue = currentQueue.concat(queue);
11467 } else {
11468 queueIndex = -1;
11469 }
11470 if (queue.length) {
11471 drainQueue();
11472 }
11473}
11474
11475function drainQueue() {
11476 if (draining) {
11477 return;
11478 }
11479 var timeout = runTimeout(cleanUpNextTick);
11480 draining = true;
11481
11482 var len = queue.length;
11483 while(len) {
11484 currentQueue = queue;
11485 queue = [];
11486 while (++queueIndex < len) {
11487 if (currentQueue) {
11488 currentQueue[queueIndex].run();
11489 }
11490 }
11491 queueIndex = -1;
11492 len = queue.length;
11493 }
11494 currentQueue = null;
11495 draining = false;
11496 runClearTimeout(timeout);
11497}
11498
11499process.nextTick = function (fun) {
11500 var args = new Array(arguments.length - 1);
11501 if (arguments.length > 1) {
11502 for (var i = 1; i < arguments.length; i++) {
11503 args[i - 1] = arguments[i];
11504 }
11505 }
11506 queue.push(new Item(fun, args));
11507 if (queue.length === 1 && !draining) {
11508 runTimeout(drainQueue);
11509 }
11510};
11511
11512// v8 likes predictible objects
11513function Item(fun, array) {
11514 this.fun = fun;
11515 this.array = array;
11516}
11517Item.prototype.run = function () {
11518 this.fun.apply(null, this.array);
11519};
11520process.title = 'browser';
11521process.browser = true;
11522process.env = {};
11523process.argv = [];
11524process.version = ''; // empty string to avoid regexp issues
11525process.versions = {};
11526
11527function noop() {}
11528
11529process.on = noop;
11530process.addListener = noop;
11531process.once = noop;
11532process.off = noop;
11533process.removeListener = noop;
11534process.removeAllListeners = noop;
11535process.emit = noop;
11536process.prependListener = noop;
11537process.prependOnceListener = noop;
11538
11539process.listeners = function (name) { return [] }
11540
11541process.binding = function (name) {
11542 throw new Error('process.binding is not supported');
11543};
11544
11545process.cwd = function () { return '/' };
11546process.chdir = function (dir) {
11547 throw new Error('process.chdir is not supported');
11548};
11549process.umask = function() { return 0; };
11550
11551},{}],68:[function(_dereq_,module,exports){
11552/*!
11553 * prr
11554 * (c) 2013 Rod Vagg <rod@vagg.org>
11555 * https://github.com/rvagg/prr
11556 * License: MIT
11557 */
11558
11559(function (name, context, definition) {
11560 if (typeof module != 'undefined' && module.exports)
11561 module.exports = definition()
11562 else
11563 context[name] = definition()
11564})('prr', this, function() {
11565
11566 var setProperty = typeof Object.defineProperty == 'function'
11567 ? function (obj, key, options) {
11568 Object.defineProperty(obj, key, options)
11569 return obj
11570 }
11571 : function (obj, key, options) { // < es5
11572 obj[key] = options.value
11573 return obj
11574 }
11575
11576 , makeOptions = function (value, options) {
11577 var oo = typeof options == 'object'
11578 , os = !oo && typeof options == 'string'
11579 , op = function (p) {
11580 return oo
11581 ? !!options[p]
11582 : os
11583 ? options.indexOf(p[0]) > -1
11584 : false
11585 }
11586
11587 return {
11588 enumerable : op('enumerable')
11589 , configurable : op('configurable')
11590 , writable : op('writable')
11591 , value : value
11592 }
11593 }
11594
11595 , prr = function (obj, key, value, options) {
11596 var k
11597
11598 options = makeOptions(value, options)
11599
11600 if (typeof key == 'object') {
11601 for (k in key) {
11602 if (Object.hasOwnProperty.call(key, k)) {
11603 options.value = key[k]
11604 setProperty(obj, k, options)
11605 }
11606 }
11607 return obj
11608 }
11609
11610 return setProperty(obj, key, options)
11611 }
11612
11613 return prr
11614})
11615},{}],69:[function(_dereq_,module,exports){
11616(function (process){(function (){
11617// Copyright Joyent, Inc. and other Node contributors.
11618//
11619// Permission is hereby granted, free of charge, to any person obtaining a
11620// copy of this software and associated documentation files (the
11621// "Software"), to deal in the Software without restriction, including
11622// without limitation the rights to use, copy, modify, merge, publish,
11623// distribute, sublicense, and/or sell copies of the Software, and to permit
11624// persons to whom the Software is furnished to do so, subject to the
11625// following conditions:
11626//
11627// The above copyright notice and this permission notice shall be included
11628// in all copies or substantial portions of the Software.
11629//
11630// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11631// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11632// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11633// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11634// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11635// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11636// USE OR OTHER DEALINGS IN THE SOFTWARE.
11637
11638// a duplex stream is just a stream that is both readable and writable.
11639// Since JS doesn't have multiple prototypal inheritance, this class
11640// prototypally inherits from Readable, and then parasitically from
11641// Writable.
11642
11643module.exports = Duplex;
11644
11645/*<replacement>*/
11646var objectKeys = Object.keys || function (obj) {
11647 var keys = [];
11648 for (var key in obj) keys.push(key);
11649 return keys;
11650}
11651/*</replacement>*/
11652
11653
11654/*<replacement>*/
11655var util = _dereq_(10);
11656util.inherits = _dereq_(30);
11657/*</replacement>*/
11658
11659var Readable = _dereq_(71);
11660var Writable = _dereq_(73);
11661
11662util.inherits(Duplex, Readable);
11663
11664forEach(objectKeys(Writable.prototype), function(method) {
11665 if (!Duplex.prototype[method])
11666 Duplex.prototype[method] = Writable.prototype[method];
11667});
11668
11669function Duplex(options) {
11670 if (!(this instanceof Duplex))
11671 return new Duplex(options);
11672
11673 Readable.call(this, options);
11674 Writable.call(this, options);
11675
11676 if (options && options.readable === false)
11677 this.readable = false;
11678
11679 if (options && options.writable === false)
11680 this.writable = false;
11681
11682 this.allowHalfOpen = true;
11683 if (options && options.allowHalfOpen === false)
11684 this.allowHalfOpen = false;
11685
11686 this.once('end', onend);
11687}
11688
11689// the no-half-open enforcer
11690function onend() {
11691 // if we allow half-open state, or if the writable side ended,
11692 // then we're ok.
11693 if (this.allowHalfOpen || this._writableState.ended)
11694 return;
11695
11696 // no more data can be written.
11697 // But allow more writes to happen in this tick.
11698 process.nextTick(this.end.bind(this));
11699}
11700
11701function forEach (xs, f) {
11702 for (var i = 0, l = xs.length; i < l; i++) {
11703 f(xs[i], i);
11704 }
11705}
11706
11707}).call(this)}).call(this,_dereq_(67))
11708},{"10":10,"30":30,"67":67,"71":71,"73":73}],70:[function(_dereq_,module,exports){
11709// Copyright Joyent, Inc. and other Node contributors.
11710//
11711// Permission is hereby granted, free of charge, to any person obtaining a
11712// copy of this software and associated documentation files (the
11713// "Software"), to deal in the Software without restriction, including
11714// without limitation the rights to use, copy, modify, merge, publish,
11715// distribute, sublicense, and/or sell copies of the Software, and to permit
11716// persons to whom the Software is furnished to do so, subject to the
11717// following conditions:
11718//
11719// The above copyright notice and this permission notice shall be included
11720// in all copies or substantial portions of the Software.
11721//
11722// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11723// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11724// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11725// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11726// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11727// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11728// USE OR OTHER DEALINGS IN THE SOFTWARE.
11729
11730// a passthrough stream.
11731// basically just the most minimal sort of Transform stream.
11732// Every written chunk gets output as-is.
11733
11734module.exports = PassThrough;
11735
11736var Transform = _dereq_(72);
11737
11738/*<replacement>*/
11739var util = _dereq_(10);
11740util.inherits = _dereq_(30);
11741/*</replacement>*/
11742
11743util.inherits(PassThrough, Transform);
11744
11745function PassThrough(options) {
11746 if (!(this instanceof PassThrough))
11747 return new PassThrough(options);
11748
11749 Transform.call(this, options);
11750}
11751
11752PassThrough.prototype._transform = function(chunk, encoding, cb) {
11753 cb(null, chunk);
11754};
11755
11756},{"10":10,"30":30,"72":72}],71:[function(_dereq_,module,exports){
11757(function (process){(function (){
11758// Copyright Joyent, Inc. and other Node contributors.
11759//
11760// Permission is hereby granted, free of charge, to any person obtaining a
11761// copy of this software and associated documentation files (the
11762// "Software"), to deal in the Software without restriction, including
11763// without limitation the rights to use, copy, modify, merge, publish,
11764// distribute, sublicense, and/or sell copies of the Software, and to permit
11765// persons to whom the Software is furnished to do so, subject to the
11766// following conditions:
11767//
11768// The above copyright notice and this permission notice shall be included
11769// in all copies or substantial portions of the Software.
11770//
11771// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11772// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11773// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11774// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11775// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11776// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11777// USE OR OTHER DEALINGS IN THE SOFTWARE.
11778
11779module.exports = Readable;
11780
11781/*<replacement>*/
11782var isArray = _dereq_(74);
11783/*</replacement>*/
11784
11785
11786/*<replacement>*/
11787var Buffer = _dereq_(9).Buffer;
11788/*</replacement>*/
11789
11790Readable.ReadableState = ReadableState;
11791
11792var EE = _dereq_(21).EventEmitter;
11793
11794/*<replacement>*/
11795if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11796 return emitter.listeners(type).length;
11797};
11798/*</replacement>*/
11799
11800var Stream = _dereq_(79);
11801
11802/*<replacement>*/
11803var util = _dereq_(10);
11804util.inherits = _dereq_(30);
11805/*</replacement>*/
11806
11807var StringDecoder;
11808
11809
11810/*<replacement>*/
11811var debug = _dereq_(7);
11812if (debug && debug.debuglog) {
11813 debug = debug.debuglog('stream');
11814} else {
11815 debug = function () {};
11816}
11817/*</replacement>*/
11818
11819
11820util.inherits(Readable, Stream);
11821
11822function ReadableState(options, stream) {
11823 var Duplex = _dereq_(69);
11824
11825 options = options || {};
11826
11827 // the point at which it stops calling _read() to fill the buffer
11828 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11829 var hwm = options.highWaterMark;
11830 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
11831 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
11832
11833 // cast to ints.
11834 this.highWaterMark = ~~this.highWaterMark;
11835
11836 this.buffer = [];
11837 this.length = 0;
11838 this.pipes = null;
11839 this.pipesCount = 0;
11840 this.flowing = null;
11841 this.ended = false;
11842 this.endEmitted = false;
11843 this.reading = false;
11844
11845 // a flag to be able to tell if the onwrite cb is called immediately,
11846 // or on a later tick. We set this to true at first, because any
11847 // actions that shouldn't happen until "later" should generally also
11848 // not happen before the first write call.
11849 this.sync = true;
11850
11851 // whenever we return null, then we set a flag to say
11852 // that we're awaiting a 'readable' event emission.
11853 this.needReadable = false;
11854 this.emittedReadable = false;
11855 this.readableListening = false;
11856
11857
11858 // object stream flag. Used to make read(n) ignore n and to
11859 // make all the buffer merging and length checks go away
11860 this.objectMode = !!options.objectMode;
11861
11862 if (stream instanceof Duplex)
11863 this.objectMode = this.objectMode || !!options.readableObjectMode;
11864
11865 // Crypto is kind of old and crusty. Historically, its default string
11866 // encoding is 'binary' so we have to make this configurable.
11867 // Everything else in the universe uses 'utf8', though.
11868 this.defaultEncoding = options.defaultEncoding || 'utf8';
11869
11870 // when piping, we only care about 'readable' events that happen
11871 // after read()ing all the bytes and not getting any pushback.
11872 this.ranOut = false;
11873
11874 // the number of writers that are awaiting a drain event in .pipe()s
11875 this.awaitDrain = 0;
11876
11877 // if true, a maybeReadMore has been scheduled
11878 this.readingMore = false;
11879
11880 this.decoder = null;
11881 this.encoding = null;
11882 if (options.encoding) {
11883 if (!StringDecoder)
11884 StringDecoder = _dereq_(75).StringDecoder;
11885 this.decoder = new StringDecoder(options.encoding);
11886 this.encoding = options.encoding;
11887 }
11888}
11889
11890function Readable(options) {
11891 var Duplex = _dereq_(69);
11892
11893 if (!(this instanceof Readable))
11894 return new Readable(options);
11895
11896 this._readableState = new ReadableState(options, this);
11897
11898 // legacy
11899 this.readable = true;
11900
11901 Stream.call(this);
11902}
11903
11904// Manually shove something into the read() buffer.
11905// This returns true if the highWaterMark has not been hit yet,
11906// similar to how Writable.write() returns true if you should
11907// write() some more.
11908Readable.prototype.push = function(chunk, encoding) {
11909 var state = this._readableState;
11910
11911 if (util.isString(chunk) && !state.objectMode) {
11912 encoding = encoding || state.defaultEncoding;
11913 if (encoding !== state.encoding) {
11914 chunk = new Buffer(chunk, encoding);
11915 encoding = '';
11916 }
11917 }
11918
11919 return readableAddChunk(this, state, chunk, encoding, false);
11920};
11921
11922// Unshift should *always* be something directly out of read()
11923Readable.prototype.unshift = function(chunk) {
11924 var state = this._readableState;
11925 return readableAddChunk(this, state, chunk, '', true);
11926};
11927
11928function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11929 var er = chunkInvalid(state, chunk);
11930 if (er) {
11931 stream.emit('error', er);
11932 } else if (util.isNullOrUndefined(chunk)) {
11933 state.reading = false;
11934 if (!state.ended)
11935 onEofChunk(stream, state);
11936 } else if (state.objectMode || chunk && chunk.length > 0) {
11937 if (state.ended && !addToFront) {
11938 var e = new Error('stream.push() after EOF');
11939 stream.emit('error', e);
11940 } else if (state.endEmitted && addToFront) {
11941 var e = new Error('stream.unshift() after end event');
11942 stream.emit('error', e);
11943 } else {
11944 if (state.decoder && !addToFront && !encoding)
11945 chunk = state.decoder.write(chunk);
11946
11947 if (!addToFront)
11948 state.reading = false;
11949
11950 // if we want the data now, just emit it.
11951 if (state.flowing && state.length === 0 && !state.sync) {
11952 stream.emit('data', chunk);
11953 stream.read(0);
11954 } else {
11955 // update the buffer info.
11956 state.length += state.objectMode ? 1 : chunk.length;
11957 if (addToFront)
11958 state.buffer.unshift(chunk);
11959 else
11960 state.buffer.push(chunk);
11961
11962 if (state.needReadable)
11963 emitReadable(stream);
11964 }
11965
11966 maybeReadMore(stream, state);
11967 }
11968 } else if (!addToFront) {
11969 state.reading = false;
11970 }
11971
11972 return needMoreData(state);
11973}
11974
11975
11976
11977// if it's past the high water mark, we can push in some more.
11978// Also, if we have no data yet, we can stand some
11979// more bytes. This is to work around cases where hwm=0,
11980// such as the repl. Also, if the push() triggered a
11981// readable event, and the user called read(largeNumber) such that
11982// needReadable was set, then we ought to push more, so that another
11983// 'readable' event will be triggered.
11984function needMoreData(state) {
11985 return !state.ended &&
11986 (state.needReadable ||
11987 state.length < state.highWaterMark ||
11988 state.length === 0);
11989}
11990
11991// backwards compatibility.
11992Readable.prototype.setEncoding = function(enc) {
11993 if (!StringDecoder)
11994 StringDecoder = _dereq_(75).StringDecoder;
11995 this._readableState.decoder = new StringDecoder(enc);
11996 this._readableState.encoding = enc;
11997 return this;
11998};
11999
12000// Don't raise the hwm > 128MB
12001var MAX_HWM = 0x800000;
12002function roundUpToNextPowerOf2(n) {
12003 if (n >= MAX_HWM) {
12004 n = MAX_HWM;
12005 } else {
12006 // Get the next highest power of 2
12007 n--;
12008 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
12009 n++;
12010 }
12011 return n;
12012}
12013
12014function howMuchToRead(n, state) {
12015 if (state.length === 0 && state.ended)
12016 return 0;
12017
12018 if (state.objectMode)
12019 return n === 0 ? 0 : 1;
12020
12021 if (isNaN(n) || util.isNull(n)) {
12022 // only flow one buffer at a time
12023 if (state.flowing && state.buffer.length)
12024 return state.buffer[0].length;
12025 else
12026 return state.length;
12027 }
12028
12029 if (n <= 0)
12030 return 0;
12031
12032 // If we're asking for more than the target buffer level,
12033 // then raise the water mark. Bump up to the next highest
12034 // power of 2, to prevent increasing it excessively in tiny
12035 // amounts.
12036 if (n > state.highWaterMark)
12037 state.highWaterMark = roundUpToNextPowerOf2(n);
12038
12039 // don't have that much. return null, unless we've ended.
12040 if (n > state.length) {
12041 if (!state.ended) {
12042 state.needReadable = true;
12043 return 0;
12044 } else
12045 return state.length;
12046 }
12047
12048 return n;
12049}
12050
12051// you can override either this method, or the async _read(n) below.
12052Readable.prototype.read = function(n) {
12053 debug('read', n);
12054 var state = this._readableState;
12055 var nOrig = n;
12056
12057 if (!util.isNumber(n) || n > 0)
12058 state.emittedReadable = false;
12059
12060 // if we're doing read(0) to trigger a readable event, but we
12061 // already have a bunch of data in the buffer, then just trigger
12062 // the 'readable' event and move on.
12063 if (n === 0 &&
12064 state.needReadable &&
12065 (state.length >= state.highWaterMark || state.ended)) {
12066 debug('read: emitReadable', state.length, state.ended);
12067 if (state.length === 0 && state.ended)
12068 endReadable(this);
12069 else
12070 emitReadable(this);
12071 return null;
12072 }
12073
12074 n = howMuchToRead(n, state);
12075
12076 // if we've ended, and we're now clear, then finish it up.
12077 if (n === 0 && state.ended) {
12078 if (state.length === 0)
12079 endReadable(this);
12080 return null;
12081 }
12082
12083 // All the actual chunk generation logic needs to be
12084 // *below* the call to _read. The reason is that in certain
12085 // synthetic stream cases, such as passthrough streams, _read
12086 // may be a completely synchronous operation which may change
12087 // the state of the read buffer, providing enough data when
12088 // before there was *not* enough.
12089 //
12090 // So, the steps are:
12091 // 1. Figure out what the state of things will be after we do
12092 // a read from the buffer.
12093 //
12094 // 2. If that resulting state will trigger a _read, then call _read.
12095 // Note that this may be asynchronous, or synchronous. Yes, it is
12096 // deeply ugly to write APIs this way, but that still doesn't mean
12097 // that the Readable class should behave improperly, as streams are
12098 // designed to be sync/async agnostic.
12099 // Take note if the _read call is sync or async (ie, if the read call
12100 // has returned yet), so that we know whether or not it's safe to emit
12101 // 'readable' etc.
12102 //
12103 // 3. Actually pull the requested chunks out of the buffer and return.
12104
12105 // if we need a readable event, then we need to do some reading.
12106 var doRead = state.needReadable;
12107 debug('need readable', doRead);
12108
12109 // if we currently have less than the highWaterMark, then also read some
12110 if (state.length === 0 || state.length - n < state.highWaterMark) {
12111 doRead = true;
12112 debug('length less than watermark', doRead);
12113 }
12114
12115 // however, if we've ended, then there's no point, and if we're already
12116 // reading, then it's unnecessary.
12117 if (state.ended || state.reading) {
12118 doRead = false;
12119 debug('reading or ended', doRead);
12120 }
12121
12122 if (doRead) {
12123 debug('do read');
12124 state.reading = true;
12125 state.sync = true;
12126 // if the length is currently zero, then we *need* a readable event.
12127 if (state.length === 0)
12128 state.needReadable = true;
12129 // call internal read method
12130 this._read(state.highWaterMark);
12131 state.sync = false;
12132 }
12133
12134 // If _read pushed data synchronously, then `reading` will be false,
12135 // and we need to re-evaluate how much data we can return to the user.
12136 if (doRead && !state.reading)
12137 n = howMuchToRead(nOrig, state);
12138
12139 var ret;
12140 if (n > 0)
12141 ret = fromList(n, state);
12142 else
12143 ret = null;
12144
12145 if (util.isNull(ret)) {
12146 state.needReadable = true;
12147 n = 0;
12148 }
12149
12150 state.length -= n;
12151
12152 // If we have nothing in the buffer, then we want to know
12153 // as soon as we *do* get something into the buffer.
12154 if (state.length === 0 && !state.ended)
12155 state.needReadable = true;
12156
12157 // If we tried to read() past the EOF, then emit end on the next tick.
12158 if (nOrig !== n && state.ended && state.length === 0)
12159 endReadable(this);
12160
12161 if (!util.isNull(ret))
12162 this.emit('data', ret);
12163
12164 return ret;
12165};
12166
12167function chunkInvalid(state, chunk) {
12168 var er = null;
12169 if (!util.isBuffer(chunk) &&
12170 !util.isString(chunk) &&
12171 !util.isNullOrUndefined(chunk) &&
12172 !state.objectMode) {
12173 er = new TypeError('Invalid non-string/buffer chunk');
12174 }
12175 return er;
12176}
12177
12178
12179function onEofChunk(stream, state) {
12180 if (state.decoder && !state.ended) {
12181 var chunk = state.decoder.end();
12182 if (chunk && chunk.length) {
12183 state.buffer.push(chunk);
12184 state.length += state.objectMode ? 1 : chunk.length;
12185 }
12186 }
12187 state.ended = true;
12188
12189 // emit 'readable' now to make sure it gets picked up.
12190 emitReadable(stream);
12191}
12192
12193// Don't emit readable right away in sync mode, because this can trigger
12194// another read() call => stack overflow. This way, it might trigger
12195// a nextTick recursion warning, but that's not so bad.
12196function emitReadable(stream) {
12197 var state = stream._readableState;
12198 state.needReadable = false;
12199 if (!state.emittedReadable) {
12200 debug('emitReadable', state.flowing);
12201 state.emittedReadable = true;
12202 if (state.sync)
12203 process.nextTick(function() {
12204 emitReadable_(stream);
12205 });
12206 else
12207 emitReadable_(stream);
12208 }
12209}
12210
12211function emitReadable_(stream) {
12212 debug('emit readable');
12213 stream.emit('readable');
12214 flow(stream);
12215}
12216
12217
12218// at this point, the user has presumably seen the 'readable' event,
12219// and called read() to consume some data. that may have triggered
12220// in turn another _read(n) call, in which case reading = true if
12221// it's in progress.
12222// However, if we're not ended, or reading, and the length < hwm,
12223// then go ahead and try to read some more preemptively.
12224function maybeReadMore(stream, state) {
12225 if (!state.readingMore) {
12226 state.readingMore = true;
12227 process.nextTick(function() {
12228 maybeReadMore_(stream, state);
12229 });
12230 }
12231}
12232
12233function maybeReadMore_(stream, state) {
12234 var len = state.length;
12235 while (!state.reading && !state.flowing && !state.ended &&
12236 state.length < state.highWaterMark) {
12237 debug('maybeReadMore read 0');
12238 stream.read(0);
12239 if (len === state.length)
12240 // didn't get any data, stop spinning.
12241 break;
12242 else
12243 len = state.length;
12244 }
12245 state.readingMore = false;
12246}
12247
12248// abstract method. to be overridden in specific implementation classes.
12249// call cb(er, data) where data is <= n in length.
12250// for virtual (non-string, non-buffer) streams, "length" is somewhat
12251// arbitrary, and perhaps not very meaningful.
12252Readable.prototype._read = function(n) {
12253 this.emit('error', new Error('not implemented'));
12254};
12255
12256Readable.prototype.pipe = function(dest, pipeOpts) {
12257 var src = this;
12258 var state = this._readableState;
12259
12260 switch (state.pipesCount) {
12261 case 0:
12262 state.pipes = dest;
12263 break;
12264 case 1:
12265 state.pipes = [state.pipes, dest];
12266 break;
12267 default:
12268 state.pipes.push(dest);
12269 break;
12270 }
12271 state.pipesCount += 1;
12272 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
12273
12274 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
12275 dest !== process.stdout &&
12276 dest !== process.stderr;
12277
12278 var endFn = doEnd ? onend : cleanup;
12279 if (state.endEmitted)
12280 process.nextTick(endFn);
12281 else
12282 src.once('end', endFn);
12283
12284 dest.on('unpipe', onunpipe);
12285 function onunpipe(readable) {
12286 debug('onunpipe');
12287 if (readable === src) {
12288 cleanup();
12289 }
12290 }
12291
12292 function onend() {
12293 debug('onend');
12294 dest.end();
12295 }
12296
12297 // when the dest drains, it reduces the awaitDrain counter
12298 // on the source. This would be more elegant with a .once()
12299 // handler in flow(), but adding and removing repeatedly is
12300 // too slow.
12301 var ondrain = pipeOnDrain(src);
12302 dest.on('drain', ondrain);
12303
12304 function cleanup() {
12305 debug('cleanup');
12306 // cleanup event handlers once the pipe is broken
12307 dest.removeListener('close', onclose);
12308 dest.removeListener('finish', onfinish);
12309 dest.removeListener('drain', ondrain);
12310 dest.removeListener('error', onerror);
12311 dest.removeListener('unpipe', onunpipe);
12312 src.removeListener('end', onend);
12313 src.removeListener('end', cleanup);
12314 src.removeListener('data', ondata);
12315
12316 // if the reader is waiting for a drain event from this
12317 // specific writer, then it would cause it to never start
12318 // flowing again.
12319 // So, if this is awaiting a drain, then we just call it now.
12320 // If we don't know, then assume that we are waiting for one.
12321 if (state.awaitDrain &&
12322 (!dest._writableState || dest._writableState.needDrain))
12323 ondrain();
12324 }
12325
12326 src.on('data', ondata);
12327 function ondata(chunk) {
12328 debug('ondata');
12329 var ret = dest.write(chunk);
12330 if (false === ret) {
12331 debug('false write response, pause',
12332 src._readableState.awaitDrain);
12333 src._readableState.awaitDrain++;
12334 src.pause();
12335 }
12336 }
12337
12338 // if the dest has an error, then stop piping into it.
12339 // however, don't suppress the throwing behavior for this.
12340 function onerror(er) {
12341 debug('onerror', er);
12342 unpipe();
12343 dest.removeListener('error', onerror);
12344 if (EE.listenerCount(dest, 'error') === 0)
12345 dest.emit('error', er);
12346 }
12347 // This is a brutally ugly hack to make sure that our error handler
12348 // is attached before any userland ones. NEVER DO THIS.
12349 if (!dest._events || !dest._events.error)
12350 dest.on('error', onerror);
12351 else if (isArray(dest._events.error))
12352 dest._events.error.unshift(onerror);
12353 else
12354 dest._events.error = [onerror, dest._events.error];
12355
12356
12357
12358 // Both close and finish should trigger unpipe, but only once.
12359 function onclose() {
12360 dest.removeListener('finish', onfinish);
12361 unpipe();
12362 }
12363 dest.once('close', onclose);
12364 function onfinish() {
12365 debug('onfinish');
12366 dest.removeListener('close', onclose);
12367 unpipe();
12368 }
12369 dest.once('finish', onfinish);
12370
12371 function unpipe() {
12372 debug('unpipe');
12373 src.unpipe(dest);
12374 }
12375
12376 // tell the dest that it's being piped to
12377 dest.emit('pipe', src);
12378
12379 // start the flow if it hasn't been started already.
12380 if (!state.flowing) {
12381 debug('pipe resume');
12382 src.resume();
12383 }
12384
12385 return dest;
12386};
12387
12388function pipeOnDrain(src) {
12389 return function() {
12390 var state = src._readableState;
12391 debug('pipeOnDrain', state.awaitDrain);
12392 if (state.awaitDrain)
12393 state.awaitDrain--;
12394 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
12395 state.flowing = true;
12396 flow(src);
12397 }
12398 };
12399}
12400
12401
12402Readable.prototype.unpipe = function(dest) {
12403 var state = this._readableState;
12404
12405 // if we're not piping anywhere, then do nothing.
12406 if (state.pipesCount === 0)
12407 return this;
12408
12409 // just one destination. most common case.
12410 if (state.pipesCount === 1) {
12411 // passed in one, but it's not the right one.
12412 if (dest && dest !== state.pipes)
12413 return this;
12414
12415 if (!dest)
12416 dest = state.pipes;
12417
12418 // got a match.
12419 state.pipes = null;
12420 state.pipesCount = 0;
12421 state.flowing = false;
12422 if (dest)
12423 dest.emit('unpipe', this);
12424 return this;
12425 }
12426
12427 // slow case. multiple pipe destinations.
12428
12429 if (!dest) {
12430 // remove all.
12431 var dests = state.pipes;
12432 var len = state.pipesCount;
12433 state.pipes = null;
12434 state.pipesCount = 0;
12435 state.flowing = false;
12436
12437 for (var i = 0; i < len; i++)
12438 dests[i].emit('unpipe', this);
12439 return this;
12440 }
12441
12442 // try to find the right one.
12443 var i = indexOf(state.pipes, dest);
12444 if (i === -1)
12445 return this;
12446
12447 state.pipes.splice(i, 1);
12448 state.pipesCount -= 1;
12449 if (state.pipesCount === 1)
12450 state.pipes = state.pipes[0];
12451
12452 dest.emit('unpipe', this);
12453
12454 return this;
12455};
12456
12457// set up data events if they are asked for
12458// Ensure readable listeners eventually get something
12459Readable.prototype.on = function(ev, fn) {
12460 var res = Stream.prototype.on.call(this, ev, fn);
12461
12462 // If listening to data, and it has not explicitly been paused,
12463 // then call resume to start the flow of data on the next tick.
12464 if (ev === 'data' && false !== this._readableState.flowing) {
12465 this.resume();
12466 }
12467
12468 if (ev === 'readable' && this.readable) {
12469 var state = this._readableState;
12470 if (!state.readableListening) {
12471 state.readableListening = true;
12472 state.emittedReadable = false;
12473 state.needReadable = true;
12474 if (!state.reading) {
12475 var self = this;
12476 process.nextTick(function() {
12477 debug('readable nexttick read 0');
12478 self.read(0);
12479 });
12480 } else if (state.length) {
12481 emitReadable(this, state);
12482 }
12483 }
12484 }
12485
12486 return res;
12487};
12488Readable.prototype.addListener = Readable.prototype.on;
12489
12490// pause() and resume() are remnants of the legacy readable stream API
12491// If the user uses them, then switch into old mode.
12492Readable.prototype.resume = function() {
12493 var state = this._readableState;
12494 if (!state.flowing) {
12495 debug('resume');
12496 state.flowing = true;
12497 if (!state.reading) {
12498 debug('resume read 0');
12499 this.read(0);
12500 }
12501 resume(this, state);
12502 }
12503 return this;
12504};
12505
12506function resume(stream, state) {
12507 if (!state.resumeScheduled) {
12508 state.resumeScheduled = true;
12509 process.nextTick(function() {
12510 resume_(stream, state);
12511 });
12512 }
12513}
12514
12515function resume_(stream, state) {
12516 state.resumeScheduled = false;
12517 stream.emit('resume');
12518 flow(stream);
12519 if (state.flowing && !state.reading)
12520 stream.read(0);
12521}
12522
12523Readable.prototype.pause = function() {
12524 debug('call pause flowing=%j', this._readableState.flowing);
12525 if (false !== this._readableState.flowing) {
12526 debug('pause');
12527 this._readableState.flowing = false;
12528 this.emit('pause');
12529 }
12530 return this;
12531};
12532
12533function flow(stream) {
12534 var state = stream._readableState;
12535 debug('flow', state.flowing);
12536 if (state.flowing) {
12537 do {
12538 var chunk = stream.read();
12539 } while (null !== chunk && state.flowing);
12540 }
12541}
12542
12543// wrap an old-style stream as the async data source.
12544// This is *not* part of the readable stream interface.
12545// It is an ugly unfortunate mess of history.
12546Readable.prototype.wrap = function(stream) {
12547 var state = this._readableState;
12548 var paused = false;
12549
12550 var self = this;
12551 stream.on('end', function() {
12552 debug('wrapped end');
12553 if (state.decoder && !state.ended) {
12554 var chunk = state.decoder.end();
12555 if (chunk && chunk.length)
12556 self.push(chunk);
12557 }
12558
12559 self.push(null);
12560 });
12561
12562 stream.on('data', function(chunk) {
12563 debug('wrapped data');
12564 if (state.decoder)
12565 chunk = state.decoder.write(chunk);
12566 if (!chunk || !state.objectMode && !chunk.length)
12567 return;
12568
12569 var ret = self.push(chunk);
12570 if (!ret) {
12571 paused = true;
12572 stream.pause();
12573 }
12574 });
12575
12576 // proxy all the other methods.
12577 // important when wrapping filters and duplexes.
12578 for (var i in stream) {
12579 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
12580 this[i] = function(method) { return function() {
12581 return stream[method].apply(stream, arguments);
12582 }}(i);
12583 }
12584 }
12585
12586 // proxy certain important events.
12587 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
12588 forEach(events, function(ev) {
12589 stream.on(ev, self.emit.bind(self, ev));
12590 });
12591
12592 // when we try to consume some more bytes, simply unpause the
12593 // underlying stream.
12594 self._read = function(n) {
12595 debug('wrapped _read', n);
12596 if (paused) {
12597 paused = false;
12598 stream.resume();
12599 }
12600 };
12601
12602 return self;
12603};
12604
12605
12606
12607// exposed for testing purposes only.
12608Readable._fromList = fromList;
12609
12610// Pluck off n bytes from an array of buffers.
12611// Length is the combined lengths of all the buffers in the list.
12612function fromList(n, state) {
12613 var list = state.buffer;
12614 var length = state.length;
12615 var stringMode = !!state.decoder;
12616 var objectMode = !!state.objectMode;
12617 var ret;
12618
12619 // nothing in the list, definitely empty.
12620 if (list.length === 0)
12621 return null;
12622
12623 if (length === 0)
12624 ret = null;
12625 else if (objectMode)
12626 ret = list.shift();
12627 else if (!n || n >= length) {
12628 // read it all, truncate the array.
12629 if (stringMode)
12630 ret = list.join('');
12631 else
12632 ret = Buffer.concat(list, length);
12633 list.length = 0;
12634 } else {
12635 // read just some of it.
12636 if (n < list[0].length) {
12637 // just take a part of the first list item.
12638 // slice is the same for buffers and strings.
12639 var buf = list[0];
12640 ret = buf.slice(0, n);
12641 list[0] = buf.slice(n);
12642 } else if (n === list[0].length) {
12643 // first list is a perfect match
12644 ret = list.shift();
12645 } else {
12646 // complex case.
12647 // we have enough to cover it, but it spans past the first buffer.
12648 if (stringMode)
12649 ret = '';
12650 else
12651 ret = new Buffer(n);
12652
12653 var c = 0;
12654 for (var i = 0, l = list.length; i < l && c < n; i++) {
12655 var buf = list[0];
12656 var cpy = Math.min(n - c, buf.length);
12657
12658 if (stringMode)
12659 ret += buf.slice(0, cpy);
12660 else
12661 buf.copy(ret, c, 0, cpy);
12662
12663 if (cpy < buf.length)
12664 list[0] = buf.slice(cpy);
12665 else
12666 list.shift();
12667
12668 c += cpy;
12669 }
12670 }
12671 }
12672
12673 return ret;
12674}
12675
12676function endReadable(stream) {
12677 var state = stream._readableState;
12678
12679 // If we get here before consuming all the bytes, then that is a
12680 // bug in node. Should never happen.
12681 if (state.length > 0)
12682 throw new Error('endReadable called on non-empty stream');
12683
12684 if (!state.endEmitted) {
12685 state.ended = true;
12686 process.nextTick(function() {
12687 // Check that we didn't get one last unshift.
12688 if (!state.endEmitted && state.length === 0) {
12689 state.endEmitted = true;
12690 stream.readable = false;
12691 stream.emit('end');
12692 }
12693 });
12694 }
12695}
12696
12697function forEach (xs, f) {
12698 for (var i = 0, l = xs.length; i < l; i++) {
12699 f(xs[i], i);
12700 }
12701}
12702
12703function indexOf (xs, x) {
12704 for (var i = 0, l = xs.length; i < l; i++) {
12705 if (xs[i] === x) return i;
12706 }
12707 return -1;
12708}
12709
12710}).call(this)}).call(this,_dereq_(67))
12711},{"10":10,"21":21,"30":30,"67":67,"69":69,"7":7,"74":74,"75":75,"79":79,"9":9}],72:[function(_dereq_,module,exports){
12712// Copyright Joyent, Inc. and other Node contributors.
12713//
12714// Permission is hereby granted, free of charge, to any person obtaining a
12715// copy of this software and associated documentation files (the
12716// "Software"), to deal in the Software without restriction, including
12717// without limitation the rights to use, copy, modify, merge, publish,
12718// distribute, sublicense, and/or sell copies of the Software, and to permit
12719// persons to whom the Software is furnished to do so, subject to the
12720// following conditions:
12721//
12722// The above copyright notice and this permission notice shall be included
12723// in all copies or substantial portions of the Software.
12724//
12725// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12726// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12727// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12728// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12729// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12730// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12731// USE OR OTHER DEALINGS IN THE SOFTWARE.
12732
12733
12734// a transform stream is a readable/writable stream where you do
12735// something with the data. Sometimes it's called a "filter",
12736// but that's not a great name for it, since that implies a thing where
12737// some bits pass through, and others are simply ignored. (That would
12738// be a valid example of a transform, of course.)
12739//
12740// While the output is causally related to the input, it's not a
12741// necessarily symmetric or synchronous transformation. For example,
12742// a zlib stream might take multiple plain-text writes(), and then
12743// emit a single compressed chunk some time in the future.
12744//
12745// Here's how this works:
12746//
12747// The Transform stream has all the aspects of the readable and writable
12748// stream classes. When you write(chunk), that calls _write(chunk,cb)
12749// internally, and returns false if there's a lot of pending writes
12750// buffered up. When you call read(), that calls _read(n) until
12751// there's enough pending readable data buffered up.
12752//
12753// In a transform stream, the written data is placed in a buffer. When
12754// _read(n) is called, it transforms the queued up data, calling the
12755// buffered _write cb's as it consumes chunks. If consuming a single
12756// written chunk would result in multiple output chunks, then the first
12757// outputted bit calls the readcb, and subsequent chunks just go into
12758// the read buffer, and will cause it to emit 'readable' if necessary.
12759//
12760// This way, back-pressure is actually determined by the reading side,
12761// since _read has to be called to start processing a new chunk. However,
12762// a pathological inflate type of transform can cause excessive buffering
12763// here. For example, imagine a stream where every byte of input is
12764// interpreted as an integer from 0-255, and then results in that many
12765// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12766// 1kb of data being output. In this case, you could write a very small
12767// amount of input, and end up with a very large amount of output. In
12768// such a pathological inflating mechanism, there'd be no way to tell
12769// the system to stop doing the transform. A single 4MB write could
12770// cause the system to run out of memory.
12771//
12772// However, even in such a pathological case, only a single written chunk
12773// would be consumed, and then the rest would wait (un-transformed) until
12774// the results of the previous transformed chunk were consumed.
12775
12776module.exports = Transform;
12777
12778var Duplex = _dereq_(69);
12779
12780/*<replacement>*/
12781var util = _dereq_(10);
12782util.inherits = _dereq_(30);
12783/*</replacement>*/
12784
12785util.inherits(Transform, Duplex);
12786
12787
12788function TransformState(options, stream) {
12789 this.afterTransform = function(er, data) {
12790 return afterTransform(stream, er, data);
12791 };
12792
12793 this.needTransform = false;
12794 this.transforming = false;
12795 this.writecb = null;
12796 this.writechunk = null;
12797}
12798
12799function afterTransform(stream, er, data) {
12800 var ts = stream._transformState;
12801 ts.transforming = false;
12802
12803 var cb = ts.writecb;
12804
12805 if (!cb)
12806 return stream.emit('error', new Error('no writecb in Transform class'));
12807
12808 ts.writechunk = null;
12809 ts.writecb = null;
12810
12811 if (!util.isNullOrUndefined(data))
12812 stream.push(data);
12813
12814 if (cb)
12815 cb(er);
12816
12817 var rs = stream._readableState;
12818 rs.reading = false;
12819 if (rs.needReadable || rs.length < rs.highWaterMark) {
12820 stream._read(rs.highWaterMark);
12821 }
12822}
12823
12824
12825function Transform(options) {
12826 if (!(this instanceof Transform))
12827 return new Transform(options);
12828
12829 Duplex.call(this, options);
12830
12831 this._transformState = new TransformState(options, this);
12832
12833 // when the writable side finishes, then flush out anything remaining.
12834 var stream = this;
12835
12836 // start out asking for a readable event once data is transformed.
12837 this._readableState.needReadable = true;
12838
12839 // we have implemented the _read method, and done the other things
12840 // that Readable wants before the first _read call, so unset the
12841 // sync guard flag.
12842 this._readableState.sync = false;
12843
12844 this.once('prefinish', function() {
12845 if (util.isFunction(this._flush))
12846 this._flush(function(er) {
12847 done(stream, er);
12848 });
12849 else
12850 done(stream);
12851 });
12852}
12853
12854Transform.prototype.push = function(chunk, encoding) {
12855 this._transformState.needTransform = false;
12856 return Duplex.prototype.push.call(this, chunk, encoding);
12857};
12858
12859// This is the part where you do stuff!
12860// override this function in implementation classes.
12861// 'chunk' is an input chunk.
12862//
12863// Call `push(newChunk)` to pass along transformed output
12864// to the readable side. You may call 'push' zero or more times.
12865//
12866// Call `cb(err)` when you are done with this chunk. If you pass
12867// an error, then that'll put the hurt on the whole operation. If you
12868// never call cb(), then you'll never get another chunk.
12869Transform.prototype._transform = function(chunk, encoding, cb) {
12870 throw new Error('not implemented');
12871};
12872
12873Transform.prototype._write = function(chunk, encoding, cb) {
12874 var ts = this._transformState;
12875 ts.writecb = cb;
12876 ts.writechunk = chunk;
12877 ts.writeencoding = encoding;
12878 if (!ts.transforming) {
12879 var rs = this._readableState;
12880 if (ts.needTransform ||
12881 rs.needReadable ||
12882 rs.length < rs.highWaterMark)
12883 this._read(rs.highWaterMark);
12884 }
12885};
12886
12887// Doesn't matter what the args are here.
12888// _transform does all the work.
12889// That we got here means that the readable side wants more data.
12890Transform.prototype._read = function(n) {
12891 var ts = this._transformState;
12892
12893 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
12894 ts.transforming = true;
12895 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12896 } else {
12897 // mark that we need a transform, so that any data that comes in
12898 // will get processed, now that we've asked for it.
12899 ts.needTransform = true;
12900 }
12901};
12902
12903
12904function done(stream, er) {
12905 if (er)
12906 return stream.emit('error', er);
12907
12908 // if there's nothing in the write buffer, then that means
12909 // that nothing more will ever be provided
12910 var ws = stream._writableState;
12911 var ts = stream._transformState;
12912
12913 if (ws.length)
12914 throw new Error('calling transform done when ws.length != 0');
12915
12916 if (ts.transforming)
12917 throw new Error('calling transform done when still transforming');
12918
12919 return stream.push(null);
12920}
12921
12922},{"10":10,"30":30,"69":69}],73:[function(_dereq_,module,exports){
12923(function (process){(function (){
12924// Copyright Joyent, Inc. and other Node contributors.
12925//
12926// Permission is hereby granted, free of charge, to any person obtaining a
12927// copy of this software and associated documentation files (the
12928// "Software"), to deal in the Software without restriction, including
12929// without limitation the rights to use, copy, modify, merge, publish,
12930// distribute, sublicense, and/or sell copies of the Software, and to permit
12931// persons to whom the Software is furnished to do so, subject to the
12932// following conditions:
12933//
12934// The above copyright notice and this permission notice shall be included
12935// in all copies or substantial portions of the Software.
12936//
12937// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12938// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12939// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12940// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12941// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12942// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12943// USE OR OTHER DEALINGS IN THE SOFTWARE.
12944
12945// A bit simpler than readable streams.
12946// Implement an async ._write(chunk, cb), and it'll handle all
12947// the drain event emission and buffering.
12948
12949module.exports = Writable;
12950
12951/*<replacement>*/
12952var Buffer = _dereq_(9).Buffer;
12953/*</replacement>*/
12954
12955Writable.WritableState = WritableState;
12956
12957
12958/*<replacement>*/
12959var util = _dereq_(10);
12960util.inherits = _dereq_(30);
12961/*</replacement>*/
12962
12963var Stream = _dereq_(79);
12964
12965util.inherits(Writable, Stream);
12966
12967function WriteReq(chunk, encoding, cb) {
12968 this.chunk = chunk;
12969 this.encoding = encoding;
12970 this.callback = cb;
12971}
12972
12973function WritableState(options, stream) {
12974 var Duplex = _dereq_(69);
12975
12976 options = options || {};
12977
12978 // the point at which write() starts returning false
12979 // Note: 0 is a valid value, means that we always return false if
12980 // the entire buffer is not flushed immediately on write()
12981 var hwm = options.highWaterMark;
12982 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
12983 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
12984
12985 // object stream flag to indicate whether or not this stream
12986 // contains buffers or objects.
12987 this.objectMode = !!options.objectMode;
12988
12989 if (stream instanceof Duplex)
12990 this.objectMode = this.objectMode || !!options.writableObjectMode;
12991
12992 // cast to ints.
12993 this.highWaterMark = ~~this.highWaterMark;
12994
12995 this.needDrain = false;
12996 // at the start of calling end()
12997 this.ending = false;
12998 // when end() has been called, and returned
12999 this.ended = false;
13000 // when 'finish' is emitted
13001 this.finished = false;
13002
13003 // should we decode strings into buffers before passing to _write?
13004 // this is here so that some node-core streams can optimize string
13005 // handling at a lower level.
13006 var noDecode = options.decodeStrings === false;
13007 this.decodeStrings = !noDecode;
13008
13009 // Crypto is kind of old and crusty. Historically, its default string
13010 // encoding is 'binary' so we have to make this configurable.
13011 // Everything else in the universe uses 'utf8', though.
13012 this.defaultEncoding = options.defaultEncoding || 'utf8';
13013
13014 // not an actual buffer we keep track of, but a measurement
13015 // of how much we're waiting to get pushed to some underlying
13016 // socket or file.
13017 this.length = 0;
13018
13019 // a flag to see when we're in the middle of a write.
13020 this.writing = false;
13021
13022 // when true all writes will be buffered until .uncork() call
13023 this.corked = 0;
13024
13025 // a flag to be able to tell if the onwrite cb is called immediately,
13026 // or on a later tick. We set this to true at first, because any
13027 // actions that shouldn't happen until "later" should generally also
13028 // not happen before the first write call.
13029 this.sync = true;
13030
13031 // a flag to know if we're processing previously buffered items, which
13032 // may call the _write() callback in the same tick, so that we don't
13033 // end up in an overlapped onwrite situation.
13034 this.bufferProcessing = false;
13035
13036 // the callback that's passed to _write(chunk,cb)
13037 this.onwrite = function(er) {
13038 onwrite(stream, er);
13039 };
13040
13041 // the callback that the user supplies to write(chunk,encoding,cb)
13042 this.writecb = null;
13043
13044 // the amount that is being written when _write is called.
13045 this.writelen = 0;
13046
13047 this.buffer = [];
13048
13049 // number of pending user-supplied write callbacks
13050 // this must be 0 before 'finish' can be emitted
13051 this.pendingcb = 0;
13052
13053 // emit prefinish if the only thing we're waiting for is _write cbs
13054 // This is relevant for synchronous Transform streams
13055 this.prefinished = false;
13056
13057 // True if the error was already emitted and should not be thrown again
13058 this.errorEmitted = false;
13059}
13060
13061function Writable(options) {
13062 var Duplex = _dereq_(69);
13063
13064 // Writable ctor is applied to Duplexes, though they're not
13065 // instanceof Writable, they're instanceof Readable.
13066 if (!(this instanceof Writable) && !(this instanceof Duplex))
13067 return new Writable(options);
13068
13069 this._writableState = new WritableState(options, this);
13070
13071 // legacy.
13072 this.writable = true;
13073
13074 Stream.call(this);
13075}
13076
13077// Otherwise people can pipe Writable streams, which is just wrong.
13078Writable.prototype.pipe = function() {
13079 this.emit('error', new Error('Cannot pipe. Not readable.'));
13080};
13081
13082
13083function writeAfterEnd(stream, state, cb) {
13084 var er = new Error('write after end');
13085 // TODO: defer error events consistently everywhere, not just the cb
13086 stream.emit('error', er);
13087 process.nextTick(function() {
13088 cb(er);
13089 });
13090}
13091
13092// If we get something that is not a buffer, string, null, or undefined,
13093// and we're not in objectMode, then that's an error.
13094// Otherwise stream chunks are all considered to be of length=1, and the
13095// watermarks determine how many objects to keep in the buffer, rather than
13096// how many bytes or characters.
13097function validChunk(stream, state, chunk, cb) {
13098 var valid = true;
13099 if (!util.isBuffer(chunk) &&
13100 !util.isString(chunk) &&
13101 !util.isNullOrUndefined(chunk) &&
13102 !state.objectMode) {
13103 var er = new TypeError('Invalid non-string/buffer chunk');
13104 stream.emit('error', er);
13105 process.nextTick(function() {
13106 cb(er);
13107 });
13108 valid = false;
13109 }
13110 return valid;
13111}
13112
13113Writable.prototype.write = function(chunk, encoding, cb) {
13114 var state = this._writableState;
13115 var ret = false;
13116
13117 if (util.isFunction(encoding)) {
13118 cb = encoding;
13119 encoding = null;
13120 }
13121
13122 if (util.isBuffer(chunk))
13123 encoding = 'buffer';
13124 else if (!encoding)
13125 encoding = state.defaultEncoding;
13126
13127 if (!util.isFunction(cb))
13128 cb = function() {};
13129
13130 if (state.ended)
13131 writeAfterEnd(this, state, cb);
13132 else if (validChunk(this, state, chunk, cb)) {
13133 state.pendingcb++;
13134 ret = writeOrBuffer(this, state, chunk, encoding, cb);
13135 }
13136
13137 return ret;
13138};
13139
13140Writable.prototype.cork = function() {
13141 var state = this._writableState;
13142
13143 state.corked++;
13144};
13145
13146Writable.prototype.uncork = function() {
13147 var state = this._writableState;
13148
13149 if (state.corked) {
13150 state.corked--;
13151
13152 if (!state.writing &&
13153 !state.corked &&
13154 !state.finished &&
13155 !state.bufferProcessing &&
13156 state.buffer.length)
13157 clearBuffer(this, state);
13158 }
13159};
13160
13161function decodeChunk(state, chunk, encoding) {
13162 if (!state.objectMode &&
13163 state.decodeStrings !== false &&
13164 util.isString(chunk)) {
13165 chunk = new Buffer(chunk, encoding);
13166 }
13167 return chunk;
13168}
13169
13170// if we're already writing something, then just put this
13171// in the queue, and wait our turn. Otherwise, call _write
13172// If we return false, then we need a drain event, so set that flag.
13173function writeOrBuffer(stream, state, chunk, encoding, cb) {
13174 chunk = decodeChunk(state, chunk, encoding);
13175 if (util.isBuffer(chunk))
13176 encoding = 'buffer';
13177 var len = state.objectMode ? 1 : chunk.length;
13178
13179 state.length += len;
13180
13181 var ret = state.length < state.highWaterMark;
13182 // we must ensure that previous needDrain will not be reset to false.
13183 if (!ret)
13184 state.needDrain = true;
13185
13186 if (state.writing || state.corked)
13187 state.buffer.push(new WriteReq(chunk, encoding, cb));
13188 else
13189 doWrite(stream, state, false, len, chunk, encoding, cb);
13190
13191 return ret;
13192}
13193
13194function doWrite(stream, state, writev, len, chunk, encoding, cb) {
13195 state.writelen = len;
13196 state.writecb = cb;
13197 state.writing = true;
13198 state.sync = true;
13199 if (writev)
13200 stream._writev(chunk, state.onwrite);
13201 else
13202 stream._write(chunk, encoding, state.onwrite);
13203 state.sync = false;
13204}
13205
13206function onwriteError(stream, state, sync, er, cb) {
13207 if (sync)
13208 process.nextTick(function() {
13209 state.pendingcb--;
13210 cb(er);
13211 });
13212 else {
13213 state.pendingcb--;
13214 cb(er);
13215 }
13216
13217 stream._writableState.errorEmitted = true;
13218 stream.emit('error', er);
13219}
13220
13221function onwriteStateUpdate(state) {
13222 state.writing = false;
13223 state.writecb = null;
13224 state.length -= state.writelen;
13225 state.writelen = 0;
13226}
13227
13228function onwrite(stream, er) {
13229 var state = stream._writableState;
13230 var sync = state.sync;
13231 var cb = state.writecb;
13232
13233 onwriteStateUpdate(state);
13234
13235 if (er)
13236 onwriteError(stream, state, sync, er, cb);
13237 else {
13238 // Check if we're actually ready to finish, but don't emit yet
13239 var finished = needFinish(stream, state);
13240
13241 if (!finished &&
13242 !state.corked &&
13243 !state.bufferProcessing &&
13244 state.buffer.length) {
13245 clearBuffer(stream, state);
13246 }
13247
13248 if (sync) {
13249 process.nextTick(function() {
13250 afterWrite(stream, state, finished, cb);
13251 });
13252 } else {
13253 afterWrite(stream, state, finished, cb);
13254 }
13255 }
13256}
13257
13258function afterWrite(stream, state, finished, cb) {
13259 if (!finished)
13260 onwriteDrain(stream, state);
13261 state.pendingcb--;
13262 cb();
13263 finishMaybe(stream, state);
13264}
13265
13266// Must force callback to be called on nextTick, so that we don't
13267// emit 'drain' before the write() consumer gets the 'false' return
13268// value, and has a chance to attach a 'drain' listener.
13269function onwriteDrain(stream, state) {
13270 if (state.length === 0 && state.needDrain) {
13271 state.needDrain = false;
13272 stream.emit('drain');
13273 }
13274}
13275
13276
13277// if there's something in the buffer waiting, then process it
13278function clearBuffer(stream, state) {
13279 state.bufferProcessing = true;
13280
13281 if (stream._writev && state.buffer.length > 1) {
13282 // Fast case, write everything using _writev()
13283 var cbs = [];
13284 for (var c = 0; c < state.buffer.length; c++)
13285 cbs.push(state.buffer[c].callback);
13286
13287 // count the one we are adding, as well.
13288 // TODO(isaacs) clean this up
13289 state.pendingcb++;
13290 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
13291 for (var i = 0; i < cbs.length; i++) {
13292 state.pendingcb--;
13293 cbs[i](err);
13294 }
13295 });
13296
13297 // Clear buffer
13298 state.buffer = [];
13299 } else {
13300 // Slow case, write chunks one-by-one
13301 for (var c = 0; c < state.buffer.length; c++) {
13302 var entry = state.buffer[c];
13303 var chunk = entry.chunk;
13304 var encoding = entry.encoding;
13305 var cb = entry.callback;
13306 var len = state.objectMode ? 1 : chunk.length;
13307
13308 doWrite(stream, state, false, len, chunk, encoding, cb);
13309
13310 // if we didn't call the onwrite immediately, then
13311 // it means that we need to wait until it does.
13312 // also, that means that the chunk and cb are currently
13313 // being processed, so move the buffer counter past them.
13314 if (state.writing) {
13315 c++;
13316 break;
13317 }
13318 }
13319
13320 if (c < state.buffer.length)
13321 state.buffer = state.buffer.slice(c);
13322 else
13323 state.buffer.length = 0;
13324 }
13325
13326 state.bufferProcessing = false;
13327}
13328
13329Writable.prototype._write = function(chunk, encoding, cb) {
13330 cb(new Error('not implemented'));
13331
13332};
13333
13334Writable.prototype._writev = null;
13335
13336Writable.prototype.end = function(chunk, encoding, cb) {
13337 var state = this._writableState;
13338
13339 if (util.isFunction(chunk)) {
13340 cb = chunk;
13341 chunk = null;
13342 encoding = null;
13343 } else if (util.isFunction(encoding)) {
13344 cb = encoding;
13345 encoding = null;
13346 }
13347
13348 if (!util.isNullOrUndefined(chunk))
13349 this.write(chunk, encoding);
13350
13351 // .end() fully uncorks
13352 if (state.corked) {
13353 state.corked = 1;
13354 this.uncork();
13355 }
13356
13357 // ignore unnecessary end() calls.
13358 if (!state.ending && !state.finished)
13359 endWritable(this, state, cb);
13360};
13361
13362
13363function needFinish(stream, state) {
13364 return (state.ending &&
13365 state.length === 0 &&
13366 !state.finished &&
13367 !state.writing);
13368}
13369
13370function prefinish(stream, state) {
13371 if (!state.prefinished) {
13372 state.prefinished = true;
13373 stream.emit('prefinish');
13374 }
13375}
13376
13377function finishMaybe(stream, state) {
13378 var need = needFinish(stream, state);
13379 if (need) {
13380 if (state.pendingcb === 0) {
13381 prefinish(stream, state);
13382 state.finished = true;
13383 stream.emit('finish');
13384 } else
13385 prefinish(stream, state);
13386 }
13387 return need;
13388}
13389
13390function endWritable(stream, state, cb) {
13391 state.ending = true;
13392 finishMaybe(stream, state);
13393 if (cb) {
13394 if (state.finished)
13395 process.nextTick(cb);
13396 else
13397 stream.once('finish', cb);
13398 }
13399 state.ended = true;
13400}
13401
13402}).call(this)}).call(this,_dereq_(67))
13403},{"10":10,"30":30,"67":67,"69":69,"79":79,"9":9}],74:[function(_dereq_,module,exports){
13404module.exports = Array.isArray || function (arr) {
13405 return Object.prototype.toString.call(arr) == '[object Array]';
13406};
13407
13408},{}],75:[function(_dereq_,module,exports){
13409// Copyright Joyent, Inc. and other Node contributors.
13410//
13411// Permission is hereby granted, free of charge, to any person obtaining a
13412// copy of this software and associated documentation files (the
13413// "Software"), to deal in the Software without restriction, including
13414// without limitation the rights to use, copy, modify, merge, publish,
13415// distribute, sublicense, and/or sell copies of the Software, and to permit
13416// persons to whom the Software is furnished to do so, subject to the
13417// following conditions:
13418//
13419// The above copyright notice and this permission notice shall be included
13420// in all copies or substantial portions of the Software.
13421//
13422// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13423// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13424// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13425// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13426// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13427// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13428// USE OR OTHER DEALINGS IN THE SOFTWARE.
13429
13430var Buffer = _dereq_(9).Buffer;
13431
13432var isBufferEncoding = Buffer.isEncoding
13433 || function(encoding) {
13434 switch (encoding && encoding.toLowerCase()) {
13435 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;
13436 default: return false;
13437 }
13438 }
13439
13440
13441function assertEncoding(encoding) {
13442 if (encoding && !isBufferEncoding(encoding)) {
13443 throw new Error('Unknown encoding: ' + encoding);
13444 }
13445}
13446
13447// StringDecoder provides an interface for efficiently splitting a series of
13448// buffers into a series of JS strings without breaking apart multi-byte
13449// characters. CESU-8 is handled as part of the UTF-8 encoding.
13450//
13451// @TODO Handling all encodings inside a single object makes it very difficult
13452// to reason about this code, so it should be split up in the future.
13453// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
13454// points as used by CESU-8.
13455var StringDecoder = exports.StringDecoder = function(encoding) {
13456 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
13457 assertEncoding(encoding);
13458 switch (this.encoding) {
13459 case 'utf8':
13460 // CESU-8 represents each of Surrogate Pair by 3-bytes
13461 this.surrogateSize = 3;
13462 break;
13463 case 'ucs2':
13464 case 'utf16le':
13465 // UTF-16 represents each of Surrogate Pair by 2-bytes
13466 this.surrogateSize = 2;
13467 this.detectIncompleteChar = utf16DetectIncompleteChar;
13468 break;
13469 case 'base64':
13470 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
13471 this.surrogateSize = 3;
13472 this.detectIncompleteChar = base64DetectIncompleteChar;
13473 break;
13474 default:
13475 this.write = passThroughWrite;
13476 return;
13477 }
13478
13479 // Enough space to store all bytes of a single character. UTF-8 needs 4
13480 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
13481 this.charBuffer = new Buffer(6);
13482 // Number of bytes received for the current incomplete multi-byte character.
13483 this.charReceived = 0;
13484 // Number of bytes expected for the current incomplete multi-byte character.
13485 this.charLength = 0;
13486};
13487
13488
13489// write decodes the given buffer and returns it as JS string that is
13490// guaranteed to not contain any partial multi-byte characters. Any partial
13491// character found at the end of the buffer is buffered up, and will be
13492// returned when calling write again with the remaining bytes.
13493//
13494// Note: Converting a Buffer containing an orphan surrogate to a String
13495// currently works, but converting a String to a Buffer (via `new Buffer`, or
13496// Buffer#write) will replace incomplete surrogates with the unicode
13497// replacement character. See https://codereview.chromium.org/121173009/ .
13498StringDecoder.prototype.write = function(buffer) {
13499 var charStr = '';
13500 // if our last write ended with an incomplete multibyte character
13501 while (this.charLength) {
13502 // determine how many remaining bytes this buffer has to offer for this char
13503 var available = (buffer.length >= this.charLength - this.charReceived) ?
13504 this.charLength - this.charReceived :
13505 buffer.length;
13506
13507 // add the new bytes to the char buffer
13508 buffer.copy(this.charBuffer, this.charReceived, 0, available);
13509 this.charReceived += available;
13510
13511 if (this.charReceived < this.charLength) {
13512 // still not enough chars in this buffer? wait for more ...
13513 return '';
13514 }
13515
13516 // remove bytes belonging to the current character from the buffer
13517 buffer = buffer.slice(available, buffer.length);
13518
13519 // get the character that was split
13520 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
13521
13522 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13523 var charCode = charStr.charCodeAt(charStr.length - 1);
13524 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13525 this.charLength += this.surrogateSize;
13526 charStr = '';
13527 continue;
13528 }
13529 this.charReceived = this.charLength = 0;
13530
13531 // if there are no more bytes in this buffer, just emit our char
13532 if (buffer.length === 0) {
13533 return charStr;
13534 }
13535 break;
13536 }
13537
13538 // determine and set charLength / charReceived
13539 this.detectIncompleteChar(buffer);
13540
13541 var end = buffer.length;
13542 if (this.charLength) {
13543 // buffer the incomplete character bytes we got
13544 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
13545 end -= this.charReceived;
13546 }
13547
13548 charStr += buffer.toString(this.encoding, 0, end);
13549
13550 var end = charStr.length - 1;
13551 var charCode = charStr.charCodeAt(end);
13552 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13553 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13554 var size = this.surrogateSize;
13555 this.charLength += size;
13556 this.charReceived += size;
13557 this.charBuffer.copy(this.charBuffer, size, 0, size);
13558 buffer.copy(this.charBuffer, 0, 0, size);
13559 return charStr.substring(0, end);
13560 }
13561
13562 // or just emit the charStr
13563 return charStr;
13564};
13565
13566// detectIncompleteChar determines if there is an incomplete UTF-8 character at
13567// the end of the given buffer. If so, it sets this.charLength to the byte
13568// length that character, and sets this.charReceived to the number of bytes
13569// that are available for this character.
13570StringDecoder.prototype.detectIncompleteChar = function(buffer) {
13571 // determine how many bytes we have to check at the end of this buffer
13572 var i = (buffer.length >= 3) ? 3 : buffer.length;
13573
13574 // Figure out if one of the last i bytes of our buffer announces an
13575 // incomplete char.
13576 for (; i > 0; i--) {
13577 var c = buffer[buffer.length - i];
13578
13579 // See http://en.wikipedia.org/wiki/UTF-8#Description
13580
13581 // 110XXXXX
13582 if (i == 1 && c >> 5 == 0x06) {
13583 this.charLength = 2;
13584 break;
13585 }
13586
13587 // 1110XXXX
13588 if (i <= 2 && c >> 4 == 0x0E) {
13589 this.charLength = 3;
13590 break;
13591 }
13592
13593 // 11110XXX
13594 if (i <= 3 && c >> 3 == 0x1E) {
13595 this.charLength = 4;
13596 break;
13597 }
13598 }
13599 this.charReceived = i;
13600};
13601
13602StringDecoder.prototype.end = function(buffer) {
13603 var res = '';
13604 if (buffer && buffer.length)
13605 res = this.write(buffer);
13606
13607 if (this.charReceived) {
13608 var cr = this.charReceived;
13609 var buf = this.charBuffer;
13610 var enc = this.encoding;
13611 res += buf.slice(0, cr).toString(enc);
13612 }
13613
13614 return res;
13615};
13616
13617function passThroughWrite(buffer) {
13618 return buffer.toString(this.encoding);
13619}
13620
13621function utf16DetectIncompleteChar(buffer) {
13622 this.charReceived = buffer.length % 2;
13623 this.charLength = this.charReceived ? 2 : 0;
13624}
13625
13626function base64DetectIncompleteChar(buffer) {
13627 this.charReceived = buffer.length % 3;
13628 this.charLength = this.charReceived ? 3 : 0;
13629}
13630
13631},{"9":9}],76:[function(_dereq_,module,exports){
13632(function (process){(function (){
13633exports = module.exports = _dereq_(71);
13634exports.Stream = _dereq_(79);
13635exports.Readable = exports;
13636exports.Writable = _dereq_(73);
13637exports.Duplex = _dereq_(69);
13638exports.Transform = _dereq_(72);
13639exports.PassThrough = _dereq_(70);
13640if (!process.browser && process.env.READABLE_STREAM === 'disable') {
13641 module.exports = _dereq_(79);
13642}
13643
13644}).call(this)}).call(this,_dereq_(67))
13645},{"67":67,"69":69,"70":70,"71":71,"72":72,"73":73,"79":79}],77:[function(_dereq_,module,exports){
13646/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
13647/* eslint-disable node/no-deprecated-api */
13648var buffer = _dereq_(9)
13649var Buffer = buffer.Buffer
13650
13651// alternative to using Object.keys for old browsers
13652function copyProps (src, dst) {
13653 for (var key in src) {
13654 dst[key] = src[key]
13655 }
13656}
13657if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13658 module.exports = buffer
13659} else {
13660 // Copy properties from require('buffer')
13661 copyProps(buffer, exports)
13662 exports.Buffer = SafeBuffer
13663}
13664
13665function SafeBuffer (arg, encodingOrOffset, length) {
13666 return Buffer(arg, encodingOrOffset, length)
13667}
13668
13669SafeBuffer.prototype = Object.create(Buffer.prototype)
13670
13671// Copy static methods from Buffer
13672copyProps(Buffer, SafeBuffer)
13673
13674SafeBuffer.from = function (arg, encodingOrOffset, length) {
13675 if (typeof arg === 'number') {
13676 throw new TypeError('Argument must not be a number')
13677 }
13678 return Buffer(arg, encodingOrOffset, length)
13679}
13680
13681SafeBuffer.alloc = function (size, fill, encoding) {
13682 if (typeof size !== 'number') {
13683 throw new TypeError('Argument must be a number')
13684 }
13685 var buf = Buffer(size)
13686 if (fill !== undefined) {
13687 if (typeof encoding === 'string') {
13688 buf.fill(fill, encoding)
13689 } else {
13690 buf.fill(fill)
13691 }
13692 } else {
13693 buf.fill(0)
13694 }
13695 return buf
13696}
13697
13698SafeBuffer.allocUnsafe = function (size) {
13699 if (typeof size !== 'number') {
13700 throw new TypeError('Argument must be a number')
13701 }
13702 return Buffer(size)
13703}
13704
13705SafeBuffer.allocUnsafeSlow = function (size) {
13706 if (typeof size !== 'number') {
13707 throw new TypeError('Argument must be a number')
13708 }
13709 return buffer.SlowBuffer(size)
13710}
13711
13712},{"9":9}],78:[function(_dereq_,module,exports){
13713(function (factory) {
13714 if (typeof exports === 'object') {
13715 // Node/CommonJS
13716 module.exports = factory();
13717 } else if (typeof define === 'function' && define.amd) {
13718 // AMD
13719 define(factory);
13720 } else {
13721 // Browser globals (with support for web workers)
13722 var glob;
13723
13724 try {
13725 glob = window;
13726 } catch (e) {
13727 glob = self;
13728 }
13729
13730 glob.SparkMD5 = factory();
13731 }
13732}(function (undefined) {
13733
13734 'use strict';
13735
13736 /*
13737 * Fastest md5 implementation around (JKM md5).
13738 * Credits: Joseph Myers
13739 *
13740 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
13741 * @see http://jsperf.com/md5-shootout/7
13742 */
13743
13744 /* this function is much faster,
13745 so if possible we use it. Some IEs
13746 are the only ones I know of that
13747 need the idiotic second function,
13748 generated by an if clause. */
13749 var add32 = function (a, b) {
13750 return (a + b) & 0xFFFFFFFF;
13751 },
13752 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
13753
13754
13755 function cmn(q, a, b, x, s, t) {
13756 a = add32(add32(a, q), add32(x, t));
13757 return add32((a << s) | (a >>> (32 - s)), b);
13758 }
13759
13760 function md5cycle(x, k) {
13761 var a = x[0],
13762 b = x[1],
13763 c = x[2],
13764 d = x[3];
13765
13766 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
13767 a = (a << 7 | a >>> 25) + b | 0;
13768 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
13769 d = (d << 12 | d >>> 20) + a | 0;
13770 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
13771 c = (c << 17 | c >>> 15) + d | 0;
13772 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
13773 b = (b << 22 | b >>> 10) + c | 0;
13774 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
13775 a = (a << 7 | a >>> 25) + b | 0;
13776 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
13777 d = (d << 12 | d >>> 20) + a | 0;
13778 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
13779 c = (c << 17 | c >>> 15) + d | 0;
13780 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
13781 b = (b << 22 | b >>> 10) + c | 0;
13782 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
13783 a = (a << 7 | a >>> 25) + b | 0;
13784 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
13785 d = (d << 12 | d >>> 20) + a | 0;
13786 c += (d & a | ~d & b) + k[10] - 42063 | 0;
13787 c = (c << 17 | c >>> 15) + d | 0;
13788 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
13789 b = (b << 22 | b >>> 10) + c | 0;
13790 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
13791 a = (a << 7 | a >>> 25) + b | 0;
13792 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
13793 d = (d << 12 | d >>> 20) + a | 0;
13794 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
13795 c = (c << 17 | c >>> 15) + d | 0;
13796 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
13797 b = (b << 22 | b >>> 10) + c | 0;
13798
13799 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
13800 a = (a << 5 | a >>> 27) + b | 0;
13801 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
13802 d = (d << 9 | d >>> 23) + a | 0;
13803 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
13804 c = (c << 14 | c >>> 18) + d | 0;
13805 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
13806 b = (b << 20 | b >>> 12) + c | 0;
13807 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
13808 a = (a << 5 | a >>> 27) + b | 0;
13809 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
13810 d = (d << 9 | d >>> 23) + a | 0;
13811 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
13812 c = (c << 14 | c >>> 18) + d | 0;
13813 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
13814 b = (b << 20 | b >>> 12) + c | 0;
13815 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
13816 a = (a << 5 | a >>> 27) + b | 0;
13817 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
13818 d = (d << 9 | d >>> 23) + a | 0;
13819 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
13820 c = (c << 14 | c >>> 18) + d | 0;
13821 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
13822 b = (b << 20 | b >>> 12) + c | 0;
13823 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
13824 a = (a << 5 | a >>> 27) + b | 0;
13825 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
13826 d = (d << 9 | d >>> 23) + a | 0;
13827 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
13828 c = (c << 14 | c >>> 18) + d | 0;
13829 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
13830 b = (b << 20 | b >>> 12) + c | 0;
13831
13832 a += (b ^ c ^ d) + k[5] - 378558 | 0;
13833 a = (a << 4 | a >>> 28) + b | 0;
13834 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
13835 d = (d << 11 | d >>> 21) + a | 0;
13836 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
13837 c = (c << 16 | c >>> 16) + d | 0;
13838 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
13839 b = (b << 23 | b >>> 9) + c | 0;
13840 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
13841 a = (a << 4 | a >>> 28) + b | 0;
13842 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
13843 d = (d << 11 | d >>> 21) + a | 0;
13844 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
13845 c = (c << 16 | c >>> 16) + d | 0;
13846 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
13847 b = (b << 23 | b >>> 9) + c | 0;
13848 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
13849 a = (a << 4 | a >>> 28) + b | 0;
13850 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
13851 d = (d << 11 | d >>> 21) + a | 0;
13852 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
13853 c = (c << 16 | c >>> 16) + d | 0;
13854 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
13855 b = (b << 23 | b >>> 9) + c | 0;
13856 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
13857 a = (a << 4 | a >>> 28) + b | 0;
13858 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
13859 d = (d << 11 | d >>> 21) + a | 0;
13860 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
13861 c = (c << 16 | c >>> 16) + d | 0;
13862 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
13863 b = (b << 23 | b >>> 9) + c | 0;
13864
13865 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
13866 a = (a << 6 | a >>> 26) + b | 0;
13867 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
13868 d = (d << 10 | d >>> 22) + a | 0;
13869 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
13870 c = (c << 15 | c >>> 17) + d | 0;
13871 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
13872 b = (b << 21 |b >>> 11) + c | 0;
13873 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
13874 a = (a << 6 | a >>> 26) + b | 0;
13875 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
13876 d = (d << 10 | d >>> 22) + a | 0;
13877 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
13878 c = (c << 15 | c >>> 17) + d | 0;
13879 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
13880 b = (b << 21 |b >>> 11) + c | 0;
13881 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
13882 a = (a << 6 | a >>> 26) + b | 0;
13883 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
13884 d = (d << 10 | d >>> 22) + a | 0;
13885 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
13886 c = (c << 15 | c >>> 17) + d | 0;
13887 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
13888 b = (b << 21 |b >>> 11) + c | 0;
13889 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
13890 a = (a << 6 | a >>> 26) + b | 0;
13891 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
13892 d = (d << 10 | d >>> 22) + a | 0;
13893 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
13894 c = (c << 15 | c >>> 17) + d | 0;
13895 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
13896 b = (b << 21 | b >>> 11) + c | 0;
13897
13898 x[0] = a + x[0] | 0;
13899 x[1] = b + x[1] | 0;
13900 x[2] = c + x[2] | 0;
13901 x[3] = d + x[3] | 0;
13902 }
13903
13904 function md5blk(s) {
13905 var md5blks = [],
13906 i; /* Andy King said do it this way. */
13907
13908 for (i = 0; i < 64; i += 4) {
13909 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
13910 }
13911 return md5blks;
13912 }
13913
13914 function md5blk_array(a) {
13915 var md5blks = [],
13916 i; /* Andy King said do it this way. */
13917
13918 for (i = 0; i < 64; i += 4) {
13919 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13920 }
13921 return md5blks;
13922 }
13923
13924 function md51(s) {
13925 var n = s.length,
13926 state = [1732584193, -271733879, -1732584194, 271733878],
13927 i,
13928 length,
13929 tail,
13930 tmp,
13931 lo,
13932 hi;
13933
13934 for (i = 64; i <= n; i += 64) {
13935 md5cycle(state, md5blk(s.substring(i - 64, i)));
13936 }
13937 s = s.substring(i - 64);
13938 length = s.length;
13939 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13940 for (i = 0; i < length; i += 1) {
13941 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13942 }
13943 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13944 if (i > 55) {
13945 md5cycle(state, tail);
13946 for (i = 0; i < 16; i += 1) {
13947 tail[i] = 0;
13948 }
13949 }
13950
13951 // Beware that the final length might not fit in 32 bits so we take care of that
13952 tmp = n * 8;
13953 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13954 lo = parseInt(tmp[2], 16);
13955 hi = parseInt(tmp[1], 16) || 0;
13956
13957 tail[14] = lo;
13958 tail[15] = hi;
13959
13960 md5cycle(state, tail);
13961 return state;
13962 }
13963
13964 function md51_array(a) {
13965 var n = a.length,
13966 state = [1732584193, -271733879, -1732584194, 271733878],
13967 i,
13968 length,
13969 tail,
13970 tmp,
13971 lo,
13972 hi;
13973
13974 for (i = 64; i <= n; i += 64) {
13975 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13976 }
13977
13978 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13979 // containing the last element of the parent array if the sub array specified starts
13980 // beyond the length of the parent array - weird.
13981 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13982 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13983
13984 length = a.length;
13985 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13986 for (i = 0; i < length; i += 1) {
13987 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13988 }
13989
13990 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13991 if (i > 55) {
13992 md5cycle(state, tail);
13993 for (i = 0; i < 16; i += 1) {
13994 tail[i] = 0;
13995 }
13996 }
13997
13998 // Beware that the final length might not fit in 32 bits so we take care of that
13999 tmp = n * 8;
14000 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
14001 lo = parseInt(tmp[2], 16);
14002 hi = parseInt(tmp[1], 16) || 0;
14003
14004 tail[14] = lo;
14005 tail[15] = hi;
14006
14007 md5cycle(state, tail);
14008
14009 return state;
14010 }
14011
14012 function rhex(n) {
14013 var s = '',
14014 j;
14015 for (j = 0; j < 4; j += 1) {
14016 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
14017 }
14018 return s;
14019 }
14020
14021 function hex(x) {
14022 var i;
14023 for (i = 0; i < x.length; i += 1) {
14024 x[i] = rhex(x[i]);
14025 }
14026 return x.join('');
14027 }
14028
14029 // In some cases the fast add32 function cannot be used..
14030 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
14031 add32 = function (x, y) {
14032 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
14033 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
14034 return (msw << 16) | (lsw & 0xFFFF);
14035 };
14036 }
14037
14038 // ---------------------------------------------------
14039
14040 /**
14041 * ArrayBuffer slice polyfill.
14042 *
14043 * @see https://github.com/ttaubert/node-arraybuffer-slice
14044 */
14045
14046 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
14047 (function () {
14048 function clamp(val, length) {
14049 val = (val | 0) || 0;
14050
14051 if (val < 0) {
14052 return Math.max(val + length, 0);
14053 }
14054
14055 return Math.min(val, length);
14056 }
14057
14058 ArrayBuffer.prototype.slice = function (from, to) {
14059 var length = this.byteLength,
14060 begin = clamp(from, length),
14061 end = length,
14062 num,
14063 target,
14064 targetArray,
14065 sourceArray;
14066
14067 if (to !== undefined) {
14068 end = clamp(to, length);
14069 }
14070
14071 if (begin > end) {
14072 return new ArrayBuffer(0);
14073 }
14074
14075 num = end - begin;
14076 target = new ArrayBuffer(num);
14077 targetArray = new Uint8Array(target);
14078
14079 sourceArray = new Uint8Array(this, begin, num);
14080 targetArray.set(sourceArray);
14081
14082 return target;
14083 };
14084 })();
14085 }
14086
14087 // ---------------------------------------------------
14088
14089 /**
14090 * Helpers.
14091 */
14092
14093 function toUtf8(str) {
14094 if (/[\u0080-\uFFFF]/.test(str)) {
14095 str = unescape(encodeURIComponent(str));
14096 }
14097
14098 return str;
14099 }
14100
14101 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
14102 var length = str.length,
14103 buff = new ArrayBuffer(length),
14104 arr = new Uint8Array(buff),
14105 i;
14106
14107 for (i = 0; i < length; i += 1) {
14108 arr[i] = str.charCodeAt(i);
14109 }
14110
14111 return returnUInt8Array ? arr : buff;
14112 }
14113
14114 function arrayBuffer2Utf8Str(buff) {
14115 return String.fromCharCode.apply(null, new Uint8Array(buff));
14116 }
14117
14118 function concatenateArrayBuffers(first, second, returnUInt8Array) {
14119 var result = new Uint8Array(first.byteLength + second.byteLength);
14120
14121 result.set(new Uint8Array(first));
14122 result.set(new Uint8Array(second), first.byteLength);
14123
14124 return returnUInt8Array ? result : result.buffer;
14125 }
14126
14127 function hexToBinaryString(hex) {
14128 var bytes = [],
14129 length = hex.length,
14130 x;
14131
14132 for (x = 0; x < length - 1; x += 2) {
14133 bytes.push(parseInt(hex.substr(x, 2), 16));
14134 }
14135
14136 return String.fromCharCode.apply(String, bytes);
14137 }
14138
14139 // ---------------------------------------------------
14140
14141 /**
14142 * SparkMD5 OOP implementation.
14143 *
14144 * Use this class to perform an incremental md5, otherwise use the
14145 * static methods instead.
14146 */
14147
14148 function SparkMD5() {
14149 // call reset to init the instance
14150 this.reset();
14151 }
14152
14153 /**
14154 * Appends a string.
14155 * A conversion will be applied if an utf8 string is detected.
14156 *
14157 * @param {String} str The string to be appended
14158 *
14159 * @return {SparkMD5} The instance itself
14160 */
14161 SparkMD5.prototype.append = function (str) {
14162 // Converts the string to utf8 bytes if necessary
14163 // Then append as binary
14164 this.appendBinary(toUtf8(str));
14165
14166 return this;
14167 };
14168
14169 /**
14170 * Appends a binary string.
14171 *
14172 * @param {String} contents The binary string to be appended
14173 *
14174 * @return {SparkMD5} The instance itself
14175 */
14176 SparkMD5.prototype.appendBinary = function (contents) {
14177 this._buff += contents;
14178 this._length += contents.length;
14179
14180 var length = this._buff.length,
14181 i;
14182
14183 for (i = 64; i <= length; i += 64) {
14184 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
14185 }
14186
14187 this._buff = this._buff.substring(i - 64);
14188
14189 return this;
14190 };
14191
14192 /**
14193 * Finishes the incremental computation, reseting the internal state and
14194 * returning the result.
14195 *
14196 * @param {Boolean} raw True to get the raw string, false to get the hex string
14197 *
14198 * @return {String} The result
14199 */
14200 SparkMD5.prototype.end = function (raw) {
14201 var buff = this._buff,
14202 length = buff.length,
14203 i,
14204 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14205 ret;
14206
14207 for (i = 0; i < length; i += 1) {
14208 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
14209 }
14210
14211 this._finish(tail, length);
14212 ret = hex(this._hash);
14213
14214 if (raw) {
14215 ret = hexToBinaryString(ret);
14216 }
14217
14218 this.reset();
14219
14220 return ret;
14221 };
14222
14223 /**
14224 * Resets the internal state of the computation.
14225 *
14226 * @return {SparkMD5} The instance itself
14227 */
14228 SparkMD5.prototype.reset = function () {
14229 this._buff = '';
14230 this._length = 0;
14231 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14232
14233 return this;
14234 };
14235
14236 /**
14237 * Gets the internal state of the computation.
14238 *
14239 * @return {Object} The state
14240 */
14241 SparkMD5.prototype.getState = function () {
14242 return {
14243 buff: this._buff,
14244 length: this._length,
14245 hash: this._hash.slice()
14246 };
14247 };
14248
14249 /**
14250 * Gets the internal state of the computation.
14251 *
14252 * @param {Object} state The state
14253 *
14254 * @return {SparkMD5} The instance itself
14255 */
14256 SparkMD5.prototype.setState = function (state) {
14257 this._buff = state.buff;
14258 this._length = state.length;
14259 this._hash = state.hash;
14260
14261 return this;
14262 };
14263
14264 /**
14265 * Releases memory used by the incremental buffer and other additional
14266 * resources. If you plan to use the instance again, use reset instead.
14267 */
14268 SparkMD5.prototype.destroy = function () {
14269 delete this._hash;
14270 delete this._buff;
14271 delete this._length;
14272 };
14273
14274 /**
14275 * Finish the final calculation based on the tail.
14276 *
14277 * @param {Array} tail The tail (will be modified)
14278 * @param {Number} length The length of the remaining buffer
14279 */
14280 SparkMD5.prototype._finish = function (tail, length) {
14281 var i = length,
14282 tmp,
14283 lo,
14284 hi;
14285
14286 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
14287 if (i > 55) {
14288 md5cycle(this._hash, tail);
14289 for (i = 0; i < 16; i += 1) {
14290 tail[i] = 0;
14291 }
14292 }
14293
14294 // Do the final computation based on the tail and length
14295 // Beware that the final length may not fit in 32 bits so we take care of that
14296 tmp = this._length * 8;
14297 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
14298 lo = parseInt(tmp[2], 16);
14299 hi = parseInt(tmp[1], 16) || 0;
14300
14301 tail[14] = lo;
14302 tail[15] = hi;
14303 md5cycle(this._hash, tail);
14304 };
14305
14306 /**
14307 * Performs the md5 hash on a string.
14308 * A conversion will be applied if utf8 string is detected.
14309 *
14310 * @param {String} str The string
14311 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
14312 *
14313 * @return {String} The result
14314 */
14315 SparkMD5.hash = function (str, raw) {
14316 // Converts the string to utf8 bytes if necessary
14317 // Then compute it using the binary function
14318 return SparkMD5.hashBinary(toUtf8(str), raw);
14319 };
14320
14321 /**
14322 * Performs the md5 hash on a binary string.
14323 *
14324 * @param {String} content The binary string
14325 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
14326 *
14327 * @return {String} The result
14328 */
14329 SparkMD5.hashBinary = function (content, raw) {
14330 var hash = md51(content),
14331 ret = hex(hash);
14332
14333 return raw ? hexToBinaryString(ret) : ret;
14334 };
14335
14336 // ---------------------------------------------------
14337
14338 /**
14339 * SparkMD5 OOP implementation for array buffers.
14340 *
14341 * Use this class to perform an incremental md5 ONLY for array buffers.
14342 */
14343 SparkMD5.ArrayBuffer = function () {
14344 // call reset to init the instance
14345 this.reset();
14346 };
14347
14348 /**
14349 * Appends an array buffer.
14350 *
14351 * @param {ArrayBuffer} arr The array to be appended
14352 *
14353 * @return {SparkMD5.ArrayBuffer} The instance itself
14354 */
14355 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
14356 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
14357 length = buff.length,
14358 i;
14359
14360 this._length += arr.byteLength;
14361
14362 for (i = 64; i <= length; i += 64) {
14363 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
14364 }
14365
14366 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
14367
14368 return this;
14369 };
14370
14371 /**
14372 * Finishes the incremental computation, reseting the internal state and
14373 * returning the result.
14374 *
14375 * @param {Boolean} raw True to get the raw string, false to get the hex string
14376 *
14377 * @return {String} The result
14378 */
14379 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
14380 var buff = this._buff,
14381 length = buff.length,
14382 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14383 i,
14384 ret;
14385
14386 for (i = 0; i < length; i += 1) {
14387 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
14388 }
14389
14390 this._finish(tail, length);
14391 ret = hex(this._hash);
14392
14393 if (raw) {
14394 ret = hexToBinaryString(ret);
14395 }
14396
14397 this.reset();
14398
14399 return ret;
14400 };
14401
14402 /**
14403 * Resets the internal state of the computation.
14404 *
14405 * @return {SparkMD5.ArrayBuffer} The instance itself
14406 */
14407 SparkMD5.ArrayBuffer.prototype.reset = function () {
14408 this._buff = new Uint8Array(0);
14409 this._length = 0;
14410 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14411
14412 return this;
14413 };
14414
14415 /**
14416 * Gets the internal state of the computation.
14417 *
14418 * @return {Object} The state
14419 */
14420 SparkMD5.ArrayBuffer.prototype.getState = function () {
14421 var state = SparkMD5.prototype.getState.call(this);
14422
14423 // Convert buffer to a string
14424 state.buff = arrayBuffer2Utf8Str(state.buff);
14425
14426 return state;
14427 };
14428
14429 /**
14430 * Gets the internal state of the computation.
14431 *
14432 * @param {Object} state The state
14433 *
14434 * @return {SparkMD5.ArrayBuffer} The instance itself
14435 */
14436 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
14437 // Convert string to buffer
14438 state.buff = utf8Str2ArrayBuffer(state.buff, true);
14439
14440 return SparkMD5.prototype.setState.call(this, state);
14441 };
14442
14443 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
14444
14445 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
14446
14447 /**
14448 * Performs the md5 hash on an array buffer.
14449 *
14450 * @param {ArrayBuffer} arr The array buffer
14451 * @param {Boolean} [raw] True to get the raw string, false to get the hex one
14452 *
14453 * @return {String} The result
14454 */
14455 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
14456 var hash = md51_array(new Uint8Array(arr)),
14457 ret = hex(hash);
14458
14459 return raw ? hexToBinaryString(ret) : ret;
14460 };
14461
14462 return SparkMD5;
14463}));
14464
14465},{}],79:[function(_dereq_,module,exports){
14466// Copyright Joyent, Inc. and other Node contributors.
14467//
14468// Permission is hereby granted, free of charge, to any person obtaining a
14469// copy of this software and associated documentation files (the
14470// "Software"), to deal in the Software without restriction, including
14471// without limitation the rights to use, copy, modify, merge, publish,
14472// distribute, sublicense, and/or sell copies of the Software, and to permit
14473// persons to whom the Software is furnished to do so, subject to the
14474// following conditions:
14475//
14476// The above copyright notice and this permission notice shall be included
14477// in all copies or substantial portions of the Software.
14478//
14479// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14480// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14481// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14482// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14483// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14484// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14485// USE OR OTHER DEALINGS IN THE SOFTWARE.
14486
14487module.exports = Stream;
14488
14489var EE = _dereq_(21).EventEmitter;
14490var inherits = _dereq_(30);
14491
14492inherits(Stream, EE);
14493Stream.Readable = _dereq_(91);
14494Stream.Writable = _dereq_(93);
14495Stream.Duplex = _dereq_(81);
14496Stream.Transform = _dereq_(92);
14497Stream.PassThrough = _dereq_(90);
14498
14499// Backwards-compat with node 0.4.x
14500Stream.Stream = Stream;
14501
14502
14503
14504// old-style streams. Note that the pipe method (the only relevant
14505// part of this class) is overridden in the Readable class.
14506
14507function Stream() {
14508 EE.call(this);
14509}
14510
14511Stream.prototype.pipe = function(dest, options) {
14512 var source = this;
14513
14514 function ondata(chunk) {
14515 if (dest.writable) {
14516 if (false === dest.write(chunk) && source.pause) {
14517 source.pause();
14518 }
14519 }
14520 }
14521
14522 source.on('data', ondata);
14523
14524 function ondrain() {
14525 if (source.readable && source.resume) {
14526 source.resume();
14527 }
14528 }
14529
14530 dest.on('drain', ondrain);
14531
14532 // If the 'end' option is not supplied, dest.end() will be called when
14533 // source gets the 'end' or 'close' events. Only dest.end() once.
14534 if (!dest._isStdio && (!options || options.end !== false)) {
14535 source.on('end', onend);
14536 source.on('close', onclose);
14537 }
14538
14539 var didOnEnd = false;
14540 function onend() {
14541 if (didOnEnd) return;
14542 didOnEnd = true;
14543
14544 dest.end();
14545 }
14546
14547
14548 function onclose() {
14549 if (didOnEnd) return;
14550 didOnEnd = true;
14551
14552 if (typeof dest.destroy === 'function') dest.destroy();
14553 }
14554
14555 // don't leave dangling pipes when there are errors.
14556 function onerror(er) {
14557 cleanup();
14558 if (EE.listenerCount(this, 'error') === 0) {
14559 throw er; // Unhandled stream error in pipe.
14560 }
14561 }
14562
14563 source.on('error', onerror);
14564 dest.on('error', onerror);
14565
14566 // remove all the event listeners that were added.
14567 function cleanup() {
14568 source.removeListener('data', ondata);
14569 dest.removeListener('drain', ondrain);
14570
14571 source.removeListener('end', onend);
14572 source.removeListener('close', onclose);
14573
14574 source.removeListener('error', onerror);
14575 dest.removeListener('error', onerror);
14576
14577 source.removeListener('end', cleanup);
14578 source.removeListener('close', cleanup);
14579
14580 dest.removeListener('close', cleanup);
14581 }
14582
14583 source.on('end', cleanup);
14584 source.on('close', cleanup);
14585
14586 dest.on('close', cleanup);
14587
14588 dest.emit('pipe', source);
14589
14590 // Allow for unix-like usage: A.pipe(B).pipe(C)
14591 return dest;
14592};
14593
14594},{"21":21,"30":30,"81":81,"90":90,"91":91,"92":92,"93":93}],80:[function(_dereq_,module,exports){
14595var toString = {}.toString;
14596
14597module.exports = Array.isArray || function (arr) {
14598 return toString.call(arr) == '[object Array]';
14599};
14600
14601},{}],81:[function(_dereq_,module,exports){
14602module.exports = _dereq_(82);
14603
14604},{"82":82}],82:[function(_dereq_,module,exports){
14605// Copyright Joyent, Inc. and other Node contributors.
14606//
14607// Permission is hereby granted, free of charge, to any person obtaining a
14608// copy of this software and associated documentation files (the
14609// "Software"), to deal in the Software without restriction, including
14610// without limitation the rights to use, copy, modify, merge, publish,
14611// distribute, sublicense, and/or sell copies of the Software, and to permit
14612// persons to whom the Software is furnished to do so, subject to the
14613// following conditions:
14614//
14615// The above copyright notice and this permission notice shall be included
14616// in all copies or substantial portions of the Software.
14617//
14618// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14619// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14620// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14621// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14622// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14623// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14624// USE OR OTHER DEALINGS IN THE SOFTWARE.
14625
14626// a duplex stream is just a stream that is both readable and writable.
14627// Since JS doesn't have multiple prototypal inheritance, this class
14628// prototypally inherits from Readable, and then parasitically from
14629// Writable.
14630
14631'use strict';
14632
14633/*<replacement>*/
14634
14635var pna = _dereq_(66);
14636/*</replacement>*/
14637
14638/*<replacement>*/
14639var objectKeys = Object.keys || function (obj) {
14640 var keys = [];
14641 for (var key in obj) {
14642 keys.push(key);
14643 }return keys;
14644};
14645/*</replacement>*/
14646
14647module.exports = Duplex;
14648
14649/*<replacement>*/
14650var util = Object.create(_dereq_(10));
14651util.inherits = _dereq_(30);
14652/*</replacement>*/
14653
14654var Readable = _dereq_(84);
14655var Writable = _dereq_(86);
14656
14657util.inherits(Duplex, Readable);
14658
14659{
14660 // avoid scope creep, the keys array can then be collected
14661 var keys = objectKeys(Writable.prototype);
14662 for (var v = 0; v < keys.length; v++) {
14663 var method = keys[v];
14664 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
14665 }
14666}
14667
14668function Duplex(options) {
14669 if (!(this instanceof Duplex)) return new Duplex(options);
14670
14671 Readable.call(this, options);
14672 Writable.call(this, options);
14673
14674 if (options && options.readable === false) this.readable = false;
14675
14676 if (options && options.writable === false) this.writable = false;
14677
14678 this.allowHalfOpen = true;
14679 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
14680
14681 this.once('end', onend);
14682}
14683
14684Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
14685 // making it explicit this property is not enumerable
14686 // because otherwise some prototype manipulation in
14687 // userland will fail
14688 enumerable: false,
14689 get: function () {
14690 return this._writableState.highWaterMark;
14691 }
14692});
14693
14694// the no-half-open enforcer
14695function onend() {
14696 // if we allow half-open state, or if the writable side ended,
14697 // then we're ok.
14698 if (this.allowHalfOpen || this._writableState.ended) return;
14699
14700 // no more data can be written.
14701 // But allow more writes to happen in this tick.
14702 pna.nextTick(onEndNT, this);
14703}
14704
14705function onEndNT(self) {
14706 self.end();
14707}
14708
14709Object.defineProperty(Duplex.prototype, 'destroyed', {
14710 get: function () {
14711 if (this._readableState === undefined || this._writableState === undefined) {
14712 return false;
14713 }
14714 return this._readableState.destroyed && this._writableState.destroyed;
14715 },
14716 set: function (value) {
14717 // we ignore the value if the stream
14718 // has not been initialized yet
14719 if (this._readableState === undefined || this._writableState === undefined) {
14720 return;
14721 }
14722
14723 // backward compatibility, the user is explicitly
14724 // managing destroyed
14725 this._readableState.destroyed = value;
14726 this._writableState.destroyed = value;
14727 }
14728});
14729
14730Duplex.prototype._destroy = function (err, cb) {
14731 this.push(null);
14732 this.end();
14733
14734 pna.nextTick(cb, err);
14735};
14736},{"10":10,"30":30,"66":66,"84":84,"86":86}],83:[function(_dereq_,module,exports){
14737// Copyright Joyent, Inc. and other Node contributors.
14738//
14739// Permission is hereby granted, free of charge, to any person obtaining a
14740// copy of this software and associated documentation files (the
14741// "Software"), to deal in the Software without restriction, including
14742// without limitation the rights to use, copy, modify, merge, publish,
14743// distribute, sublicense, and/or sell copies of the Software, and to permit
14744// persons to whom the Software is furnished to do so, subject to the
14745// following conditions:
14746//
14747// The above copyright notice and this permission notice shall be included
14748// in all copies or substantial portions of the Software.
14749//
14750// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14751// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14752// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14753// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14754// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14755// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14756// USE OR OTHER DEALINGS IN THE SOFTWARE.
14757
14758// a passthrough stream.
14759// basically just the most minimal sort of Transform stream.
14760// Every written chunk gets output as-is.
14761
14762'use strict';
14763
14764module.exports = PassThrough;
14765
14766var Transform = _dereq_(85);
14767
14768/*<replacement>*/
14769var util = Object.create(_dereq_(10));
14770util.inherits = _dereq_(30);
14771/*</replacement>*/
14772
14773util.inherits(PassThrough, Transform);
14774
14775function PassThrough(options) {
14776 if (!(this instanceof PassThrough)) return new PassThrough(options);
14777
14778 Transform.call(this, options);
14779}
14780
14781PassThrough.prototype._transform = function (chunk, encoding, cb) {
14782 cb(null, chunk);
14783};
14784},{"10":10,"30":30,"85":85}],84:[function(_dereq_,module,exports){
14785(function (process,global){(function (){
14786// Copyright Joyent, Inc. and other Node contributors.
14787//
14788// Permission is hereby granted, free of charge, to any person obtaining a
14789// copy of this software and associated documentation files (the
14790// "Software"), to deal in the Software without restriction, including
14791// without limitation the rights to use, copy, modify, merge, publish,
14792// distribute, sublicense, and/or sell copies of the Software, and to permit
14793// persons to whom the Software is furnished to do so, subject to the
14794// following conditions:
14795//
14796// The above copyright notice and this permission notice shall be included
14797// in all copies or substantial portions of the Software.
14798//
14799// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14800// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14801// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14802// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14803// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14804// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14805// USE OR OTHER DEALINGS IN THE SOFTWARE.
14806
14807'use strict';
14808
14809/*<replacement>*/
14810
14811var pna = _dereq_(66);
14812/*</replacement>*/
14813
14814module.exports = Readable;
14815
14816/*<replacement>*/
14817var isArray = _dereq_(80);
14818/*</replacement>*/
14819
14820/*<replacement>*/
14821var Duplex;
14822/*</replacement>*/
14823
14824Readable.ReadableState = ReadableState;
14825
14826/*<replacement>*/
14827var EE = _dereq_(21).EventEmitter;
14828
14829var EElistenerCount = function (emitter, type) {
14830 return emitter.listeners(type).length;
14831};
14832/*</replacement>*/
14833
14834/*<replacement>*/
14835var Stream = _dereq_(89);
14836/*</replacement>*/
14837
14838/*<replacement>*/
14839
14840var Buffer = _dereq_(94).Buffer;
14841var OurUint8Array = global.Uint8Array || function () {};
14842function _uint8ArrayToBuffer(chunk) {
14843 return Buffer.from(chunk);
14844}
14845function _isUint8Array(obj) {
14846 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14847}
14848
14849/*</replacement>*/
14850
14851/*<replacement>*/
14852var util = Object.create(_dereq_(10));
14853util.inherits = _dereq_(30);
14854/*</replacement>*/
14855
14856/*<replacement>*/
14857var debugUtil = _dereq_(7);
14858var debug = void 0;
14859if (debugUtil && debugUtil.debuglog) {
14860 debug = debugUtil.debuglog('stream');
14861} else {
14862 debug = function () {};
14863}
14864/*</replacement>*/
14865
14866var BufferList = _dereq_(87);
14867var destroyImpl = _dereq_(88);
14868var StringDecoder;
14869
14870util.inherits(Readable, Stream);
14871
14872var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14873
14874function prependListener(emitter, event, fn) {
14875 // Sadly this is not cacheable as some libraries bundle their own
14876 // event emitter implementation with them.
14877 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
14878
14879 // This is a hack to make sure that our error handler is attached before any
14880 // userland ones. NEVER DO THIS. This is here only because this code needs
14881 // to continue to work with older versions of Node.js that do not include
14882 // the prependListener() method. The goal is to eventually remove this hack.
14883 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]];
14884}
14885
14886function ReadableState(options, stream) {
14887 Duplex = Duplex || _dereq_(82);
14888
14889 options = options || {};
14890
14891 // Duplex streams are both readable and writable, but share
14892 // the same options object.
14893 // However, some cases require setting options to different
14894 // values for the readable and the writable sides of the duplex stream.
14895 // These options can be provided separately as readableXXX and writableXXX.
14896 var isDuplex = stream instanceof Duplex;
14897
14898 // object stream flag. Used to make read(n) ignore n and to
14899 // make all the buffer merging and length checks go away
14900 this.objectMode = !!options.objectMode;
14901
14902 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
14903
14904 // the point at which it stops calling _read() to fill the buffer
14905 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14906 var hwm = options.highWaterMark;
14907 var readableHwm = options.readableHighWaterMark;
14908 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14909
14910 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
14911
14912 // cast to ints.
14913 this.highWaterMark = Math.floor(this.highWaterMark);
14914
14915 // A linked list is used to store data chunks instead of an array because the
14916 // linked list can remove elements from the beginning faster than
14917 // array.shift()
14918 this.buffer = new BufferList();
14919 this.length = 0;
14920 this.pipes = null;
14921 this.pipesCount = 0;
14922 this.flowing = null;
14923 this.ended = false;
14924 this.endEmitted = false;
14925 this.reading = false;
14926
14927 // a flag to be able to tell if the event 'readable'/'data' is emitted
14928 // immediately, or on a later tick. We set this to true at first, because
14929 // any actions that shouldn't happen until "later" should generally also
14930 // not happen before the first read call.
14931 this.sync = true;
14932
14933 // whenever we return null, then we set a flag to say
14934 // that we're awaiting a 'readable' event emission.
14935 this.needReadable = false;
14936 this.emittedReadable = false;
14937 this.readableListening = false;
14938 this.resumeScheduled = false;
14939
14940 // has it been destroyed
14941 this.destroyed = false;
14942
14943 // Crypto is kind of old and crusty. Historically, its default string
14944 // encoding is 'binary' so we have to make this configurable.
14945 // Everything else in the universe uses 'utf8', though.
14946 this.defaultEncoding = options.defaultEncoding || 'utf8';
14947
14948 // the number of writers that are awaiting a drain event in .pipe()s
14949 this.awaitDrain = 0;
14950
14951 // if true, a maybeReadMore has been scheduled
14952 this.readingMore = false;
14953
14954 this.decoder = null;
14955 this.encoding = null;
14956 if (options.encoding) {
14957 if (!StringDecoder) StringDecoder = _dereq_(95).StringDecoder;
14958 this.decoder = new StringDecoder(options.encoding);
14959 this.encoding = options.encoding;
14960 }
14961}
14962
14963function Readable(options) {
14964 Duplex = Duplex || _dereq_(82);
14965
14966 if (!(this instanceof Readable)) return new Readable(options);
14967
14968 this._readableState = new ReadableState(options, this);
14969
14970 // legacy
14971 this.readable = true;
14972
14973 if (options) {
14974 if (typeof options.read === 'function') this._read = options.read;
14975
14976 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14977 }
14978
14979 Stream.call(this);
14980}
14981
14982Object.defineProperty(Readable.prototype, 'destroyed', {
14983 get: function () {
14984 if (this._readableState === undefined) {
14985 return false;
14986 }
14987 return this._readableState.destroyed;
14988 },
14989 set: function (value) {
14990 // we ignore the value if the stream
14991 // has not been initialized yet
14992 if (!this._readableState) {
14993 return;
14994 }
14995
14996 // backward compatibility, the user is explicitly
14997 // managing destroyed
14998 this._readableState.destroyed = value;
14999 }
15000});
15001
15002Readable.prototype.destroy = destroyImpl.destroy;
15003Readable.prototype._undestroy = destroyImpl.undestroy;
15004Readable.prototype._destroy = function (err, cb) {
15005 this.push(null);
15006 cb(err);
15007};
15008
15009// Manually shove something into the read() buffer.
15010// This returns true if the highWaterMark has not been hit yet,
15011// similar to how Writable.write() returns true if you should
15012// write() some more.
15013Readable.prototype.push = function (chunk, encoding) {
15014 var state = this._readableState;
15015 var skipChunkCheck;
15016
15017 if (!state.objectMode) {
15018 if (typeof chunk === 'string') {
15019 encoding = encoding || state.defaultEncoding;
15020 if (encoding !== state.encoding) {
15021 chunk = Buffer.from(chunk, encoding);
15022 encoding = '';
15023 }
15024 skipChunkCheck = true;
15025 }
15026 } else {
15027 skipChunkCheck = true;
15028 }
15029
15030 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
15031};
15032
15033// Unshift should *always* be something directly out of read()
15034Readable.prototype.unshift = function (chunk) {
15035 return readableAddChunk(this, chunk, null, true, false);
15036};
15037
15038function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
15039 var state = stream._readableState;
15040 if (chunk === null) {
15041 state.reading = false;
15042 onEofChunk(stream, state);
15043 } else {
15044 var er;
15045 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
15046 if (er) {
15047 stream.emit('error', er);
15048 } else if (state.objectMode || chunk && chunk.length > 0) {
15049 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
15050 chunk = _uint8ArrayToBuffer(chunk);
15051 }
15052
15053 if (addToFront) {
15054 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
15055 } else if (state.ended) {
15056 stream.emit('error', new Error('stream.push() after EOF'));
15057 } else {
15058 state.reading = false;
15059 if (state.decoder && !encoding) {
15060 chunk = state.decoder.write(chunk);
15061 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
15062 } else {
15063 addChunk(stream, state, chunk, false);
15064 }
15065 }
15066 } else if (!addToFront) {
15067 state.reading = false;
15068 }
15069 }
15070
15071 return needMoreData(state);
15072}
15073
15074function addChunk(stream, state, chunk, addToFront) {
15075 if (state.flowing && state.length === 0 && !state.sync) {
15076 stream.emit('data', chunk);
15077 stream.read(0);
15078 } else {
15079 // update the buffer info.
15080 state.length += state.objectMode ? 1 : chunk.length;
15081 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
15082
15083 if (state.needReadable) emitReadable(stream);
15084 }
15085 maybeReadMore(stream, state);
15086}
15087
15088function chunkInvalid(state, chunk) {
15089 var er;
15090 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15091 er = new TypeError('Invalid non-string/buffer chunk');
15092 }
15093 return er;
15094}
15095
15096// if it's past the high water mark, we can push in some more.
15097// Also, if we have no data yet, we can stand some
15098// more bytes. This is to work around cases where hwm=0,
15099// such as the repl. Also, if the push() triggered a
15100// readable event, and the user called read(largeNumber) such that
15101// needReadable was set, then we ought to push more, so that another
15102// 'readable' event will be triggered.
15103function needMoreData(state) {
15104 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
15105}
15106
15107Readable.prototype.isPaused = function () {
15108 return this._readableState.flowing === false;
15109};
15110
15111// backwards compatibility.
15112Readable.prototype.setEncoding = function (enc) {
15113 if (!StringDecoder) StringDecoder = _dereq_(95).StringDecoder;
15114 this._readableState.decoder = new StringDecoder(enc);
15115 this._readableState.encoding = enc;
15116 return this;
15117};
15118
15119// Don't raise the hwm > 8MB
15120var MAX_HWM = 0x800000;
15121function computeNewHighWaterMark(n) {
15122 if (n >= MAX_HWM) {
15123 n = MAX_HWM;
15124 } else {
15125 // Get the next highest power of 2 to prevent increasing hwm excessively in
15126 // tiny amounts
15127 n--;
15128 n |= n >>> 1;
15129 n |= n >>> 2;
15130 n |= n >>> 4;
15131 n |= n >>> 8;
15132 n |= n >>> 16;
15133 n++;
15134 }
15135 return n;
15136}
15137
15138// This function is designed to be inlinable, so please take care when making
15139// changes to the function body.
15140function howMuchToRead(n, state) {
15141 if (n <= 0 || state.length === 0 && state.ended) return 0;
15142 if (state.objectMode) return 1;
15143 if (n !== n) {
15144 // Only flow one buffer at a time
15145 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
15146 }
15147 // If we're asking for more than the current hwm, then raise the hwm.
15148 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
15149 if (n <= state.length) return n;
15150 // Don't have enough
15151 if (!state.ended) {
15152 state.needReadable = true;
15153 return 0;
15154 }
15155 return state.length;
15156}
15157
15158// you can override either this method, or the async _read(n) below.
15159Readable.prototype.read = function (n) {
15160 debug('read', n);
15161 n = parseInt(n, 10);
15162 var state = this._readableState;
15163 var nOrig = n;
15164
15165 if (n !== 0) state.emittedReadable = false;
15166
15167 // if we're doing read(0) to trigger a readable event, but we
15168 // already have a bunch of data in the buffer, then just trigger
15169 // the 'readable' event and move on.
15170 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
15171 debug('read: emitReadable', state.length, state.ended);
15172 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
15173 return null;
15174 }
15175
15176 n = howMuchToRead(n, state);
15177
15178 // if we've ended, and we're now clear, then finish it up.
15179 if (n === 0 && state.ended) {
15180 if (state.length === 0) endReadable(this);
15181 return null;
15182 }
15183
15184 // All the actual chunk generation logic needs to be
15185 // *below* the call to _read. The reason is that in certain
15186 // synthetic stream cases, such as passthrough streams, _read
15187 // may be a completely synchronous operation which may change
15188 // the state of the read buffer, providing enough data when
15189 // before there was *not* enough.
15190 //
15191 // So, the steps are:
15192 // 1. Figure out what the state of things will be after we do
15193 // a read from the buffer.
15194 //
15195 // 2. If that resulting state will trigger a _read, then call _read.
15196 // Note that this may be asynchronous, or synchronous. Yes, it is
15197 // deeply ugly to write APIs this way, but that still doesn't mean
15198 // that the Readable class should behave improperly, as streams are
15199 // designed to be sync/async agnostic.
15200 // Take note if the _read call is sync or async (ie, if the read call
15201 // has returned yet), so that we know whether or not it's safe to emit
15202 // 'readable' etc.
15203 //
15204 // 3. Actually pull the requested chunks out of the buffer and return.
15205
15206 // if we need a readable event, then we need to do some reading.
15207 var doRead = state.needReadable;
15208 debug('need readable', doRead);
15209
15210 // if we currently have less than the highWaterMark, then also read some
15211 if (state.length === 0 || state.length - n < state.highWaterMark) {
15212 doRead = true;
15213 debug('length less than watermark', doRead);
15214 }
15215
15216 // however, if we've ended, then there's no point, and if we're already
15217 // reading, then it's unnecessary.
15218 if (state.ended || state.reading) {
15219 doRead = false;
15220 debug('reading or ended', doRead);
15221 } else if (doRead) {
15222 debug('do read');
15223 state.reading = true;
15224 state.sync = true;
15225 // if the length is currently zero, then we *need* a readable event.
15226 if (state.length === 0) state.needReadable = true;
15227 // call internal read method
15228 this._read(state.highWaterMark);
15229 state.sync = false;
15230 // If _read pushed data synchronously, then `reading` will be false,
15231 // and we need to re-evaluate how much data we can return to the user.
15232 if (!state.reading) n = howMuchToRead(nOrig, state);
15233 }
15234
15235 var ret;
15236 if (n > 0) ret = fromList(n, state);else ret = null;
15237
15238 if (ret === null) {
15239 state.needReadable = true;
15240 n = 0;
15241 } else {
15242 state.length -= n;
15243 }
15244
15245 if (state.length === 0) {
15246 // If we have nothing in the buffer, then we want to know
15247 // as soon as we *do* get something into the buffer.
15248 if (!state.ended) state.needReadable = true;
15249
15250 // If we tried to read() past the EOF, then emit end on the next tick.
15251 if (nOrig !== n && state.ended) endReadable(this);
15252 }
15253
15254 if (ret !== null) this.emit('data', ret);
15255
15256 return ret;
15257};
15258
15259function onEofChunk(stream, state) {
15260 if (state.ended) return;
15261 if (state.decoder) {
15262 var chunk = state.decoder.end();
15263 if (chunk && chunk.length) {
15264 state.buffer.push(chunk);
15265 state.length += state.objectMode ? 1 : chunk.length;
15266 }
15267 }
15268 state.ended = true;
15269
15270 // emit 'readable' now to make sure it gets picked up.
15271 emitReadable(stream);
15272}
15273
15274// Don't emit readable right away in sync mode, because this can trigger
15275// another read() call => stack overflow. This way, it might trigger
15276// a nextTick recursion warning, but that's not so bad.
15277function emitReadable(stream) {
15278 var state = stream._readableState;
15279 state.needReadable = false;
15280 if (!state.emittedReadable) {
15281 debug('emitReadable', state.flowing);
15282 state.emittedReadable = true;
15283 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
15284 }
15285}
15286
15287function emitReadable_(stream) {
15288 debug('emit readable');
15289 stream.emit('readable');
15290 flow(stream);
15291}
15292
15293// at this point, the user has presumably seen the 'readable' event,
15294// and called read() to consume some data. that may have triggered
15295// in turn another _read(n) call, in which case reading = true if
15296// it's in progress.
15297// However, if we're not ended, or reading, and the length < hwm,
15298// then go ahead and try to read some more preemptively.
15299function maybeReadMore(stream, state) {
15300 if (!state.readingMore) {
15301 state.readingMore = true;
15302 pna.nextTick(maybeReadMore_, stream, state);
15303 }
15304}
15305
15306function maybeReadMore_(stream, state) {
15307 var len = state.length;
15308 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
15309 debug('maybeReadMore read 0');
15310 stream.read(0);
15311 if (len === state.length)
15312 // didn't get any data, stop spinning.
15313 break;else len = state.length;
15314 }
15315 state.readingMore = false;
15316}
15317
15318// abstract method. to be overridden in specific implementation classes.
15319// call cb(er, data) where data is <= n in length.
15320// for virtual (non-string, non-buffer) streams, "length" is somewhat
15321// arbitrary, and perhaps not very meaningful.
15322Readable.prototype._read = function (n) {
15323 this.emit('error', new Error('_read() is not implemented'));
15324};
15325
15326Readable.prototype.pipe = function (dest, pipeOpts) {
15327 var src = this;
15328 var state = this._readableState;
15329
15330 switch (state.pipesCount) {
15331 case 0:
15332 state.pipes = dest;
15333 break;
15334 case 1:
15335 state.pipes = [state.pipes, dest];
15336 break;
15337 default:
15338 state.pipes.push(dest);
15339 break;
15340 }
15341 state.pipesCount += 1;
15342 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
15343
15344 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
15345
15346 var endFn = doEnd ? onend : unpipe;
15347 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
15348
15349 dest.on('unpipe', onunpipe);
15350 function onunpipe(readable, unpipeInfo) {
15351 debug('onunpipe');
15352 if (readable === src) {
15353 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
15354 unpipeInfo.hasUnpiped = true;
15355 cleanup();
15356 }
15357 }
15358 }
15359
15360 function onend() {
15361 debug('onend');
15362 dest.end();
15363 }
15364
15365 // when the dest drains, it reduces the awaitDrain counter
15366 // on the source. This would be more elegant with a .once()
15367 // handler in flow(), but adding and removing repeatedly is
15368 // too slow.
15369 var ondrain = pipeOnDrain(src);
15370 dest.on('drain', ondrain);
15371
15372 var cleanedUp = false;
15373 function cleanup() {
15374 debug('cleanup');
15375 // cleanup event handlers once the pipe is broken
15376 dest.removeListener('close', onclose);
15377 dest.removeListener('finish', onfinish);
15378 dest.removeListener('drain', ondrain);
15379 dest.removeListener('error', onerror);
15380 dest.removeListener('unpipe', onunpipe);
15381 src.removeListener('end', onend);
15382 src.removeListener('end', unpipe);
15383 src.removeListener('data', ondata);
15384
15385 cleanedUp = true;
15386
15387 // if the reader is waiting for a drain event from this
15388 // specific writer, then it would cause it to never start
15389 // flowing again.
15390 // So, if this is awaiting a drain, then we just call it now.
15391 // If we don't know, then assume that we are waiting for one.
15392 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
15393 }
15394
15395 // If the user pushes more data while we're writing to dest then we'll end up
15396 // in ondata again. However, we only want to increase awaitDrain once because
15397 // dest will only emit one 'drain' event for the multiple writes.
15398 // => Introduce a guard on increasing awaitDrain.
15399 var increasedAwaitDrain = false;
15400 src.on('data', ondata);
15401 function ondata(chunk) {
15402 debug('ondata');
15403 increasedAwaitDrain = false;
15404 var ret = dest.write(chunk);
15405 if (false === ret && !increasedAwaitDrain) {
15406 // If the user unpiped during `dest.write()`, it is possible
15407 // to get stuck in a permanently paused state if that write
15408 // also returned false.
15409 // => Check whether `dest` is still a piping destination.
15410 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
15411 debug('false write response, pause', src._readableState.awaitDrain);
15412 src._readableState.awaitDrain++;
15413 increasedAwaitDrain = true;
15414 }
15415 src.pause();
15416 }
15417 }
15418
15419 // if the dest has an error, then stop piping into it.
15420 // however, don't suppress the throwing behavior for this.
15421 function onerror(er) {
15422 debug('onerror', er);
15423 unpipe();
15424 dest.removeListener('error', onerror);
15425 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
15426 }
15427
15428 // Make sure our error handler is attached before userland ones.
15429 prependListener(dest, 'error', onerror);
15430
15431 // Both close and finish should trigger unpipe, but only once.
15432 function onclose() {
15433 dest.removeListener('finish', onfinish);
15434 unpipe();
15435 }
15436 dest.once('close', onclose);
15437 function onfinish() {
15438 debug('onfinish');
15439 dest.removeListener('close', onclose);
15440 unpipe();
15441 }
15442 dest.once('finish', onfinish);
15443
15444 function unpipe() {
15445 debug('unpipe');
15446 src.unpipe(dest);
15447 }
15448
15449 // tell the dest that it's being piped to
15450 dest.emit('pipe', src);
15451
15452 // start the flow if it hasn't been started already.
15453 if (!state.flowing) {
15454 debug('pipe resume');
15455 src.resume();
15456 }
15457
15458 return dest;
15459};
15460
15461function pipeOnDrain(src) {
15462 return function () {
15463 var state = src._readableState;
15464 debug('pipeOnDrain', state.awaitDrain);
15465 if (state.awaitDrain) state.awaitDrain--;
15466 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
15467 state.flowing = true;
15468 flow(src);
15469 }
15470 };
15471}
15472
15473Readable.prototype.unpipe = function (dest) {
15474 var state = this._readableState;
15475 var unpipeInfo = { hasUnpiped: false };
15476
15477 // if we're not piping anywhere, then do nothing.
15478 if (state.pipesCount === 0) return this;
15479
15480 // just one destination. most common case.
15481 if (state.pipesCount === 1) {
15482 // passed in one, but it's not the right one.
15483 if (dest && dest !== state.pipes) return this;
15484
15485 if (!dest) dest = state.pipes;
15486
15487 // got a match.
15488 state.pipes = null;
15489 state.pipesCount = 0;
15490 state.flowing = false;
15491 if (dest) dest.emit('unpipe', this, unpipeInfo);
15492 return this;
15493 }
15494
15495 // slow case. multiple pipe destinations.
15496
15497 if (!dest) {
15498 // remove all.
15499 var dests = state.pipes;
15500 var len = state.pipesCount;
15501 state.pipes = null;
15502 state.pipesCount = 0;
15503 state.flowing = false;
15504
15505 for (var i = 0; i < len; i++) {
15506 dests[i].emit('unpipe', this, unpipeInfo);
15507 }return this;
15508 }
15509
15510 // try to find the right one.
15511 var index = indexOf(state.pipes, dest);
15512 if (index === -1) return this;
15513
15514 state.pipes.splice(index, 1);
15515 state.pipesCount -= 1;
15516 if (state.pipesCount === 1) state.pipes = state.pipes[0];
15517
15518 dest.emit('unpipe', this, unpipeInfo);
15519
15520 return this;
15521};
15522
15523// set up data events if they are asked for
15524// Ensure readable listeners eventually get something
15525Readable.prototype.on = function (ev, fn) {
15526 var res = Stream.prototype.on.call(this, ev, fn);
15527
15528 if (ev === 'data') {
15529 // Start flowing on next tick if stream isn't explicitly paused
15530 if (this._readableState.flowing !== false) this.resume();
15531 } else if (ev === 'readable') {
15532 var state = this._readableState;
15533 if (!state.endEmitted && !state.readableListening) {
15534 state.readableListening = state.needReadable = true;
15535 state.emittedReadable = false;
15536 if (!state.reading) {
15537 pna.nextTick(nReadingNextTick, this);
15538 } else if (state.length) {
15539 emitReadable(this);
15540 }
15541 }
15542 }
15543
15544 return res;
15545};
15546Readable.prototype.addListener = Readable.prototype.on;
15547
15548function nReadingNextTick(self) {
15549 debug('readable nexttick read 0');
15550 self.read(0);
15551}
15552
15553// pause() and resume() are remnants of the legacy readable stream API
15554// If the user uses them, then switch into old mode.
15555Readable.prototype.resume = function () {
15556 var state = this._readableState;
15557 if (!state.flowing) {
15558 debug('resume');
15559 state.flowing = true;
15560 resume(this, state);
15561 }
15562 return this;
15563};
15564
15565function resume(stream, state) {
15566 if (!state.resumeScheduled) {
15567 state.resumeScheduled = true;
15568 pna.nextTick(resume_, stream, state);
15569 }
15570}
15571
15572function resume_(stream, state) {
15573 if (!state.reading) {
15574 debug('resume read 0');
15575 stream.read(0);
15576 }
15577
15578 state.resumeScheduled = false;
15579 state.awaitDrain = 0;
15580 stream.emit('resume');
15581 flow(stream);
15582 if (state.flowing && !state.reading) stream.read(0);
15583}
15584
15585Readable.prototype.pause = function () {
15586 debug('call pause flowing=%j', this._readableState.flowing);
15587 if (false !== this._readableState.flowing) {
15588 debug('pause');
15589 this._readableState.flowing = false;
15590 this.emit('pause');
15591 }
15592 return this;
15593};
15594
15595function flow(stream) {
15596 var state = stream._readableState;
15597 debug('flow', state.flowing);
15598 while (state.flowing && stream.read() !== null) {}
15599}
15600
15601// wrap an old-style stream as the async data source.
15602// This is *not* part of the readable stream interface.
15603// It is an ugly unfortunate mess of history.
15604Readable.prototype.wrap = function (stream) {
15605 var _this = this;
15606
15607 var state = this._readableState;
15608 var paused = false;
15609
15610 stream.on('end', function () {
15611 debug('wrapped end');
15612 if (state.decoder && !state.ended) {
15613 var chunk = state.decoder.end();
15614 if (chunk && chunk.length) _this.push(chunk);
15615 }
15616
15617 _this.push(null);
15618 });
15619
15620 stream.on('data', function (chunk) {
15621 debug('wrapped data');
15622 if (state.decoder) chunk = state.decoder.write(chunk);
15623
15624 // don't skip over falsy values in objectMode
15625 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
15626
15627 var ret = _this.push(chunk);
15628 if (!ret) {
15629 paused = true;
15630 stream.pause();
15631 }
15632 });
15633
15634 // proxy all the other methods.
15635 // important when wrapping filters and duplexes.
15636 for (var i in stream) {
15637 if (this[i] === undefined && typeof stream[i] === 'function') {
15638 this[i] = function (method) {
15639 return function () {
15640 return stream[method].apply(stream, arguments);
15641 };
15642 }(i);
15643 }
15644 }
15645
15646 // proxy certain important events.
15647 for (var n = 0; n < kProxyEvents.length; n++) {
15648 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
15649 }
15650
15651 // when we try to consume some more bytes, simply unpause the
15652 // underlying stream.
15653 this._read = function (n) {
15654 debug('wrapped _read', n);
15655 if (paused) {
15656 paused = false;
15657 stream.resume();
15658 }
15659 };
15660
15661 return this;
15662};
15663
15664Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
15665 // making it explicit this property is not enumerable
15666 // because otherwise some prototype manipulation in
15667 // userland will fail
15668 enumerable: false,
15669 get: function () {
15670 return this._readableState.highWaterMark;
15671 }
15672});
15673
15674// exposed for testing purposes only.
15675Readable._fromList = fromList;
15676
15677// Pluck off n bytes from an array of buffers.
15678// Length is the combined lengths of all the buffers in the list.
15679// This function is designed to be inlinable, so please take care when making
15680// changes to the function body.
15681function fromList(n, state) {
15682 // nothing buffered
15683 if (state.length === 0) return null;
15684
15685 var ret;
15686 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
15687 // read it all, truncate the list
15688 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);
15689 state.buffer.clear();
15690 } else {
15691 // read part of list
15692 ret = fromListPartial(n, state.buffer, state.decoder);
15693 }
15694
15695 return ret;
15696}
15697
15698// Extracts only enough buffered data to satisfy the amount requested.
15699// This function is designed to be inlinable, so please take care when making
15700// changes to the function body.
15701function fromListPartial(n, list, hasStrings) {
15702 var ret;
15703 if (n < list.head.data.length) {
15704 // slice is the same for buffers and strings
15705 ret = list.head.data.slice(0, n);
15706 list.head.data = list.head.data.slice(n);
15707 } else if (n === list.head.data.length) {
15708 // first chunk is a perfect match
15709 ret = list.shift();
15710 } else {
15711 // result spans more than one buffer
15712 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
15713 }
15714 return ret;
15715}
15716
15717// Copies a specified amount of characters from the list of buffered data
15718// chunks.
15719// This function is designed to be inlinable, so please take care when making
15720// changes to the function body.
15721function copyFromBufferString(n, list) {
15722 var p = list.head;
15723 var c = 1;
15724 var ret = p.data;
15725 n -= ret.length;
15726 while (p = p.next) {
15727 var str = p.data;
15728 var nb = n > str.length ? str.length : n;
15729 if (nb === str.length) ret += str;else ret += str.slice(0, n);
15730 n -= nb;
15731 if (n === 0) {
15732 if (nb === str.length) {
15733 ++c;
15734 if (p.next) list.head = p.next;else list.head = list.tail = null;
15735 } else {
15736 list.head = p;
15737 p.data = str.slice(nb);
15738 }
15739 break;
15740 }
15741 ++c;
15742 }
15743 list.length -= c;
15744 return ret;
15745}
15746
15747// Copies a specified amount of bytes from the list of buffered data chunks.
15748// This function is designed to be inlinable, so please take care when making
15749// changes to the function body.
15750function copyFromBuffer(n, list) {
15751 var ret = Buffer.allocUnsafe(n);
15752 var p = list.head;
15753 var c = 1;
15754 p.data.copy(ret);
15755 n -= p.data.length;
15756 while (p = p.next) {
15757 var buf = p.data;
15758 var nb = n > buf.length ? buf.length : n;
15759 buf.copy(ret, ret.length - n, 0, nb);
15760 n -= nb;
15761 if (n === 0) {
15762 if (nb === buf.length) {
15763 ++c;
15764 if (p.next) list.head = p.next;else list.head = list.tail = null;
15765 } else {
15766 list.head = p;
15767 p.data = buf.slice(nb);
15768 }
15769 break;
15770 }
15771 ++c;
15772 }
15773 list.length -= c;
15774 return ret;
15775}
15776
15777function endReadable(stream) {
15778 var state = stream._readableState;
15779
15780 // If we get here before consuming all the bytes, then that is a
15781 // bug in node. Should never happen.
15782 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
15783
15784 if (!state.endEmitted) {
15785 state.ended = true;
15786 pna.nextTick(endReadableNT, state, stream);
15787 }
15788}
15789
15790function endReadableNT(state, stream) {
15791 // Check that we didn't get one last unshift.
15792 if (!state.endEmitted && state.length === 0) {
15793 state.endEmitted = true;
15794 stream.readable = false;
15795 stream.emit('end');
15796 }
15797}
15798
15799function indexOf(xs, x) {
15800 for (var i = 0, l = xs.length; i < l; i++) {
15801 if (xs[i] === x) return i;
15802 }
15803 return -1;
15804}
15805}).call(this)}).call(this,_dereq_(67),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15806},{"10":10,"21":21,"30":30,"66":66,"67":67,"7":7,"80":80,"82":82,"87":87,"88":88,"89":89,"94":94,"95":95}],85:[function(_dereq_,module,exports){
15807// Copyright Joyent, Inc. and other Node contributors.
15808//
15809// Permission is hereby granted, free of charge, to any person obtaining a
15810// copy of this software and associated documentation files (the
15811// "Software"), to deal in the Software without restriction, including
15812// without limitation the rights to use, copy, modify, merge, publish,
15813// distribute, sublicense, and/or sell copies of the Software, and to permit
15814// persons to whom the Software is furnished to do so, subject to the
15815// following conditions:
15816//
15817// The above copyright notice and this permission notice shall be included
15818// in all copies or substantial portions of the Software.
15819//
15820// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15821// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15822// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15823// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15824// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15825// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15826// USE OR OTHER DEALINGS IN THE SOFTWARE.
15827
15828// a transform stream is a readable/writable stream where you do
15829// something with the data. Sometimes it's called a "filter",
15830// but that's not a great name for it, since that implies a thing where
15831// some bits pass through, and others are simply ignored. (That would
15832// be a valid example of a transform, of course.)
15833//
15834// While the output is causally related to the input, it's not a
15835// necessarily symmetric or synchronous transformation. For example,
15836// a zlib stream might take multiple plain-text writes(), and then
15837// emit a single compressed chunk some time in the future.
15838//
15839// Here's how this works:
15840//
15841// The Transform stream has all the aspects of the readable and writable
15842// stream classes. When you write(chunk), that calls _write(chunk,cb)
15843// internally, and returns false if there's a lot of pending writes
15844// buffered up. When you call read(), that calls _read(n) until
15845// there's enough pending readable data buffered up.
15846//
15847// In a transform stream, the written data is placed in a buffer. When
15848// _read(n) is called, it transforms the queued up data, calling the
15849// buffered _write cb's as it consumes chunks. If consuming a single
15850// written chunk would result in multiple output chunks, then the first
15851// outputted bit calls the readcb, and subsequent chunks just go into
15852// the read buffer, and will cause it to emit 'readable' if necessary.
15853//
15854// This way, back-pressure is actually determined by the reading side,
15855// since _read has to be called to start processing a new chunk. However,
15856// a pathological inflate type of transform can cause excessive buffering
15857// here. For example, imagine a stream where every byte of input is
15858// interpreted as an integer from 0-255, and then results in that many
15859// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
15860// 1kb of data being output. In this case, you could write a very small
15861// amount of input, and end up with a very large amount of output. In
15862// such a pathological inflating mechanism, there'd be no way to tell
15863// the system to stop doing the transform. A single 4MB write could
15864// cause the system to run out of memory.
15865//
15866// However, even in such a pathological case, only a single written chunk
15867// would be consumed, and then the rest would wait (un-transformed) until
15868// the results of the previous transformed chunk were consumed.
15869
15870'use strict';
15871
15872module.exports = Transform;
15873
15874var Duplex = _dereq_(82);
15875
15876/*<replacement>*/
15877var util = Object.create(_dereq_(10));
15878util.inherits = _dereq_(30);
15879/*</replacement>*/
15880
15881util.inherits(Transform, Duplex);
15882
15883function afterTransform(er, data) {
15884 var ts = this._transformState;
15885 ts.transforming = false;
15886
15887 var cb = ts.writecb;
15888
15889 if (!cb) {
15890 return this.emit('error', new Error('write callback called multiple times'));
15891 }
15892
15893 ts.writechunk = null;
15894 ts.writecb = null;
15895
15896 if (data != null) // single equals check for both `null` and `undefined`
15897 this.push(data);
15898
15899 cb(er);
15900
15901 var rs = this._readableState;
15902 rs.reading = false;
15903 if (rs.needReadable || rs.length < rs.highWaterMark) {
15904 this._read(rs.highWaterMark);
15905 }
15906}
15907
15908function Transform(options) {
15909 if (!(this instanceof Transform)) return new Transform(options);
15910
15911 Duplex.call(this, options);
15912
15913 this._transformState = {
15914 afterTransform: afterTransform.bind(this),
15915 needTransform: false,
15916 transforming: false,
15917 writecb: null,
15918 writechunk: null,
15919 writeencoding: null
15920 };
15921
15922 // start out asking for a readable event once data is transformed.
15923 this._readableState.needReadable = true;
15924
15925 // we have implemented the _read method, and done the other things
15926 // that Readable wants before the first _read call, so unset the
15927 // sync guard flag.
15928 this._readableState.sync = false;
15929
15930 if (options) {
15931 if (typeof options.transform === 'function') this._transform = options.transform;
15932
15933 if (typeof options.flush === 'function') this._flush = options.flush;
15934 }
15935
15936 // When the writable side finishes, then flush out anything remaining.
15937 this.on('prefinish', prefinish);
15938}
15939
15940function prefinish() {
15941 var _this = this;
15942
15943 if (typeof this._flush === 'function') {
15944 this._flush(function (er, data) {
15945 done(_this, er, data);
15946 });
15947 } else {
15948 done(this, null, null);
15949 }
15950}
15951
15952Transform.prototype.push = function (chunk, encoding) {
15953 this._transformState.needTransform = false;
15954 return Duplex.prototype.push.call(this, chunk, encoding);
15955};
15956
15957// This is the part where you do stuff!
15958// override this function in implementation classes.
15959// 'chunk' is an input chunk.
15960//
15961// Call `push(newChunk)` to pass along transformed output
15962// to the readable side. You may call 'push' zero or more times.
15963//
15964// Call `cb(err)` when you are done with this chunk. If you pass
15965// an error, then that'll put the hurt on the whole operation. If you
15966// never call cb(), then you'll never get another chunk.
15967Transform.prototype._transform = function (chunk, encoding, cb) {
15968 throw new Error('_transform() is not implemented');
15969};
15970
15971Transform.prototype._write = function (chunk, encoding, cb) {
15972 var ts = this._transformState;
15973 ts.writecb = cb;
15974 ts.writechunk = chunk;
15975 ts.writeencoding = encoding;
15976 if (!ts.transforming) {
15977 var rs = this._readableState;
15978 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15979 }
15980};
15981
15982// Doesn't matter what the args are here.
15983// _transform does all the work.
15984// That we got here means that the readable side wants more data.
15985Transform.prototype._read = function (n) {
15986 var ts = this._transformState;
15987
15988 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15989 ts.transforming = true;
15990 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15991 } else {
15992 // mark that we need a transform, so that any data that comes in
15993 // will get processed, now that we've asked for it.
15994 ts.needTransform = true;
15995 }
15996};
15997
15998Transform.prototype._destroy = function (err, cb) {
15999 var _this2 = this;
16000
16001 Duplex.prototype._destroy.call(this, err, function (err2) {
16002 cb(err2);
16003 _this2.emit('close');
16004 });
16005};
16006
16007function done(stream, er, data) {
16008 if (er) return stream.emit('error', er);
16009
16010 if (data != null) // single equals check for both `null` and `undefined`
16011 stream.push(data);
16012
16013 // if there's nothing in the write buffer, then that means
16014 // that nothing more will ever be provided
16015 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
16016
16017 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
16018
16019 return stream.push(null);
16020}
16021},{"10":10,"30":30,"82":82}],86:[function(_dereq_,module,exports){
16022(function (process,global,setImmediate){(function (){
16023// Copyright Joyent, Inc. and other Node contributors.
16024//
16025// Permission is hereby granted, free of charge, to any person obtaining a
16026// copy of this software and associated documentation files (the
16027// "Software"), to deal in the Software without restriction, including
16028// without limitation the rights to use, copy, modify, merge, publish,
16029// distribute, sublicense, and/or sell copies of the Software, and to permit
16030// persons to whom the Software is furnished to do so, subject to the
16031// following conditions:
16032//
16033// The above copyright notice and this permission notice shall be included
16034// in all copies or substantial portions of the Software.
16035//
16036// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16037// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16038// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16039// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16040// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16041// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16042// USE OR OTHER DEALINGS IN THE SOFTWARE.
16043
16044// A bit simpler than readable streams.
16045// Implement an async ._write(chunk, encoding, cb), and it'll handle all
16046// the drain event emission and buffering.
16047
16048'use strict';
16049
16050/*<replacement>*/
16051
16052var pna = _dereq_(66);
16053/*</replacement>*/
16054
16055module.exports = Writable;
16056
16057/* <replacement> */
16058function WriteReq(chunk, encoding, cb) {
16059 this.chunk = chunk;
16060 this.encoding = encoding;
16061 this.callback = cb;
16062 this.next = null;
16063}
16064
16065// It seems a linked list but it is not
16066// there will be only 2 of these for each stream
16067function CorkedRequest(state) {
16068 var _this = this;
16069
16070 this.next = null;
16071 this.entry = null;
16072 this.finish = function () {
16073 onCorkedFinish(_this, state);
16074 };
16075}
16076/* </replacement> */
16077
16078/*<replacement>*/
16079var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
16080/*</replacement>*/
16081
16082/*<replacement>*/
16083var Duplex;
16084/*</replacement>*/
16085
16086Writable.WritableState = WritableState;
16087
16088/*<replacement>*/
16089var util = Object.create(_dereq_(10));
16090util.inherits = _dereq_(30);
16091/*</replacement>*/
16092
16093/*<replacement>*/
16094var internalUtil = {
16095 deprecate: _dereq_(114)
16096};
16097/*</replacement>*/
16098
16099/*<replacement>*/
16100var Stream = _dereq_(89);
16101/*</replacement>*/
16102
16103/*<replacement>*/
16104
16105var Buffer = _dereq_(94).Buffer;
16106var OurUint8Array = global.Uint8Array || function () {};
16107function _uint8ArrayToBuffer(chunk) {
16108 return Buffer.from(chunk);
16109}
16110function _isUint8Array(obj) {
16111 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
16112}
16113
16114/*</replacement>*/
16115
16116var destroyImpl = _dereq_(88);
16117
16118util.inherits(Writable, Stream);
16119
16120function nop() {}
16121
16122function WritableState(options, stream) {
16123 Duplex = Duplex || _dereq_(82);
16124
16125 options = options || {};
16126
16127 // Duplex streams are both readable and writable, but share
16128 // the same options object.
16129 // However, some cases require setting options to different
16130 // values for the readable and the writable sides of the duplex stream.
16131 // These options can be provided separately as readableXXX and writableXXX.
16132 var isDuplex = stream instanceof Duplex;
16133
16134 // object stream flag to indicate whether or not this stream
16135 // contains buffers or objects.
16136 this.objectMode = !!options.objectMode;
16137
16138 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
16139
16140 // the point at which write() starts returning false
16141 // Note: 0 is a valid value, means that we always return false if
16142 // the entire buffer is not flushed immediately on write()
16143 var hwm = options.highWaterMark;
16144 var writableHwm = options.writableHighWaterMark;
16145 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
16146
16147 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
16148
16149 // cast to ints.
16150 this.highWaterMark = Math.floor(this.highWaterMark);
16151
16152 // if _final has been called
16153 this.finalCalled = false;
16154
16155 // drain event flag.
16156 this.needDrain = false;
16157 // at the start of calling end()
16158 this.ending = false;
16159 // when end() has been called, and returned
16160 this.ended = false;
16161 // when 'finish' is emitted
16162 this.finished = false;
16163
16164 // has it been destroyed
16165 this.destroyed = false;
16166
16167 // should we decode strings into buffers before passing to _write?
16168 // this is here so that some node-core streams can optimize string
16169 // handling at a lower level.
16170 var noDecode = options.decodeStrings === false;
16171 this.decodeStrings = !noDecode;
16172
16173 // Crypto is kind of old and crusty. Historically, its default string
16174 // encoding is 'binary' so we have to make this configurable.
16175 // Everything else in the universe uses 'utf8', though.
16176 this.defaultEncoding = options.defaultEncoding || 'utf8';
16177
16178 // not an actual buffer we keep track of, but a measurement
16179 // of how much we're waiting to get pushed to some underlying
16180 // socket or file.
16181 this.length = 0;
16182
16183 // a flag to see when we're in the middle of a write.
16184 this.writing = false;
16185
16186 // when true all writes will be buffered until .uncork() call
16187 this.corked = 0;
16188
16189 // a flag to be able to tell if the onwrite cb is called immediately,
16190 // or on a later tick. We set this to true at first, because any
16191 // actions that shouldn't happen until "later" should generally also
16192 // not happen before the first write call.
16193 this.sync = true;
16194
16195 // a flag to know if we're processing previously buffered items, which
16196 // may call the _write() callback in the same tick, so that we don't
16197 // end up in an overlapped onwrite situation.
16198 this.bufferProcessing = false;
16199
16200 // the callback that's passed to _write(chunk,cb)
16201 this.onwrite = function (er) {
16202 onwrite(stream, er);
16203 };
16204
16205 // the callback that the user supplies to write(chunk,encoding,cb)
16206 this.writecb = null;
16207
16208 // the amount that is being written when _write is called.
16209 this.writelen = 0;
16210
16211 this.bufferedRequest = null;
16212 this.lastBufferedRequest = null;
16213
16214 // number of pending user-supplied write callbacks
16215 // this must be 0 before 'finish' can be emitted
16216 this.pendingcb = 0;
16217
16218 // emit prefinish if the only thing we're waiting for is _write cbs
16219 // This is relevant for synchronous Transform streams
16220 this.prefinished = false;
16221
16222 // True if the error was already emitted and should not be thrown again
16223 this.errorEmitted = false;
16224
16225 // count buffered requests
16226 this.bufferedRequestCount = 0;
16227
16228 // allocate the first CorkedRequest, there is always
16229 // one allocated and free to use, and we maintain at most two
16230 this.corkedRequestsFree = new CorkedRequest(this);
16231}
16232
16233WritableState.prototype.getBuffer = function getBuffer() {
16234 var current = this.bufferedRequest;
16235 var out = [];
16236 while (current) {
16237 out.push(current);
16238 current = current.next;
16239 }
16240 return out;
16241};
16242
16243(function () {
16244 try {
16245 Object.defineProperty(WritableState.prototype, 'buffer', {
16246 get: internalUtil.deprecate(function () {
16247 return this.getBuffer();
16248 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
16249 });
16250 } catch (_) {}
16251})();
16252
16253// Test _writableState for inheritance to account for Duplex streams,
16254// whose prototype chain only points to Readable.
16255var realHasInstance;
16256if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
16257 realHasInstance = Function.prototype[Symbol.hasInstance];
16258 Object.defineProperty(Writable, Symbol.hasInstance, {
16259 value: function (object) {
16260 if (realHasInstance.call(this, object)) return true;
16261 if (this !== Writable) return false;
16262
16263 return object && object._writableState instanceof WritableState;
16264 }
16265 });
16266} else {
16267 realHasInstance = function (object) {
16268 return object instanceof this;
16269 };
16270}
16271
16272function Writable(options) {
16273 Duplex = Duplex || _dereq_(82);
16274
16275 // Writable ctor is applied to Duplexes, too.
16276 // `realHasInstance` is necessary because using plain `instanceof`
16277 // would return false, as no `_writableState` property is attached.
16278
16279 // Trying to use the custom `instanceof` for Writable here will also break the
16280 // Node.js LazyTransform implementation, which has a non-trivial getter for
16281 // `_writableState` that would lead to infinite recursion.
16282 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
16283 return new Writable(options);
16284 }
16285
16286 this._writableState = new WritableState(options, this);
16287
16288 // legacy.
16289 this.writable = true;
16290
16291 if (options) {
16292 if (typeof options.write === 'function') this._write = options.write;
16293
16294 if (typeof options.writev === 'function') this._writev = options.writev;
16295
16296 if (typeof options.destroy === 'function') this._destroy = options.destroy;
16297
16298 if (typeof options.final === 'function') this._final = options.final;
16299 }
16300
16301 Stream.call(this);
16302}
16303
16304// Otherwise people can pipe Writable streams, which is just wrong.
16305Writable.prototype.pipe = function () {
16306 this.emit('error', new Error('Cannot pipe, not readable'));
16307};
16308
16309function writeAfterEnd(stream, cb) {
16310 var er = new Error('write after end');
16311 // TODO: defer error events consistently everywhere, not just the cb
16312 stream.emit('error', er);
16313 pna.nextTick(cb, er);
16314}
16315
16316// Checks that a user-supplied chunk is valid, especially for the particular
16317// mode the stream is in. Currently this means that `null` is never accepted
16318// and undefined/non-string values are only allowed in object mode.
16319function validChunk(stream, state, chunk, cb) {
16320 var valid = true;
16321 var er = false;
16322
16323 if (chunk === null) {
16324 er = new TypeError('May not write null values to stream');
16325 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
16326 er = new TypeError('Invalid non-string/buffer chunk');
16327 }
16328 if (er) {
16329 stream.emit('error', er);
16330 pna.nextTick(cb, er);
16331 valid = false;
16332 }
16333 return valid;
16334}
16335
16336Writable.prototype.write = function (chunk, encoding, cb) {
16337 var state = this._writableState;
16338 var ret = false;
16339 var isBuf = !state.objectMode && _isUint8Array(chunk);
16340
16341 if (isBuf && !Buffer.isBuffer(chunk)) {
16342 chunk = _uint8ArrayToBuffer(chunk);
16343 }
16344
16345 if (typeof encoding === 'function') {
16346 cb = encoding;
16347 encoding = null;
16348 }
16349
16350 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
16351
16352 if (typeof cb !== 'function') cb = nop;
16353
16354 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
16355 state.pendingcb++;
16356 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
16357 }
16358
16359 return ret;
16360};
16361
16362Writable.prototype.cork = function () {
16363 var state = this._writableState;
16364
16365 state.corked++;
16366};
16367
16368Writable.prototype.uncork = function () {
16369 var state = this._writableState;
16370
16371 if (state.corked) {
16372 state.corked--;
16373
16374 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
16375 }
16376};
16377
16378Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
16379 // node::ParseEncoding() requires lower case.
16380 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
16381 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);
16382 this._writableState.defaultEncoding = encoding;
16383 return this;
16384};
16385
16386function decodeChunk(state, chunk, encoding) {
16387 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
16388 chunk = Buffer.from(chunk, encoding);
16389 }
16390 return chunk;
16391}
16392
16393Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
16394 // making it explicit this property is not enumerable
16395 // because otherwise some prototype manipulation in
16396 // userland will fail
16397 enumerable: false,
16398 get: function () {
16399 return this._writableState.highWaterMark;
16400 }
16401});
16402
16403// if we're already writing something, then just put this
16404// in the queue, and wait our turn. Otherwise, call _write
16405// If we return false, then we need a drain event, so set that flag.
16406function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
16407 if (!isBuf) {
16408 var newChunk = decodeChunk(state, chunk, encoding);
16409 if (chunk !== newChunk) {
16410 isBuf = true;
16411 encoding = 'buffer';
16412 chunk = newChunk;
16413 }
16414 }
16415 var len = state.objectMode ? 1 : chunk.length;
16416
16417 state.length += len;
16418
16419 var ret = state.length < state.highWaterMark;
16420 // we must ensure that previous needDrain will not be reset to false.
16421 if (!ret) state.needDrain = true;
16422
16423 if (state.writing || state.corked) {
16424 var last = state.lastBufferedRequest;
16425 state.lastBufferedRequest = {
16426 chunk: chunk,
16427 encoding: encoding,
16428 isBuf: isBuf,
16429 callback: cb,
16430 next: null
16431 };
16432 if (last) {
16433 last.next = state.lastBufferedRequest;
16434 } else {
16435 state.bufferedRequest = state.lastBufferedRequest;
16436 }
16437 state.bufferedRequestCount += 1;
16438 } else {
16439 doWrite(stream, state, false, len, chunk, encoding, cb);
16440 }
16441
16442 return ret;
16443}
16444
16445function doWrite(stream, state, writev, len, chunk, encoding, cb) {
16446 state.writelen = len;
16447 state.writecb = cb;
16448 state.writing = true;
16449 state.sync = true;
16450 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
16451 state.sync = false;
16452}
16453
16454function onwriteError(stream, state, sync, er, cb) {
16455 --state.pendingcb;
16456
16457 if (sync) {
16458 // defer the callback if we are being called synchronously
16459 // to avoid piling up things on the stack
16460 pna.nextTick(cb, er);
16461 // this can emit finish, and it will always happen
16462 // after error
16463 pna.nextTick(finishMaybe, stream, state);
16464 stream._writableState.errorEmitted = true;
16465 stream.emit('error', er);
16466 } else {
16467 // the caller expect this to happen before if
16468 // it is async
16469 cb(er);
16470 stream._writableState.errorEmitted = true;
16471 stream.emit('error', er);
16472 // this can emit finish, but finish must
16473 // always follow error
16474 finishMaybe(stream, state);
16475 }
16476}
16477
16478function onwriteStateUpdate(state) {
16479 state.writing = false;
16480 state.writecb = null;
16481 state.length -= state.writelen;
16482 state.writelen = 0;
16483}
16484
16485function onwrite(stream, er) {
16486 var state = stream._writableState;
16487 var sync = state.sync;
16488 var cb = state.writecb;
16489
16490 onwriteStateUpdate(state);
16491
16492 if (er) onwriteError(stream, state, sync, er, cb);else {
16493 // Check if we're actually ready to finish, but don't emit yet
16494 var finished = needFinish(state);
16495
16496 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
16497 clearBuffer(stream, state);
16498 }
16499
16500 if (sync) {
16501 /*<replacement>*/
16502 asyncWrite(afterWrite, stream, state, finished, cb);
16503 /*</replacement>*/
16504 } else {
16505 afterWrite(stream, state, finished, cb);
16506 }
16507 }
16508}
16509
16510function afterWrite(stream, state, finished, cb) {
16511 if (!finished) onwriteDrain(stream, state);
16512 state.pendingcb--;
16513 cb();
16514 finishMaybe(stream, state);
16515}
16516
16517// Must force callback to be called on nextTick, so that we don't
16518// emit 'drain' before the write() consumer gets the 'false' return
16519// value, and has a chance to attach a 'drain' listener.
16520function onwriteDrain(stream, state) {
16521 if (state.length === 0 && state.needDrain) {
16522 state.needDrain = false;
16523 stream.emit('drain');
16524 }
16525}
16526
16527// if there's something in the buffer waiting, then process it
16528function clearBuffer(stream, state) {
16529 state.bufferProcessing = true;
16530 var entry = state.bufferedRequest;
16531
16532 if (stream._writev && entry && entry.next) {
16533 // Fast case, write everything using _writev()
16534 var l = state.bufferedRequestCount;
16535 var buffer = new Array(l);
16536 var holder = state.corkedRequestsFree;
16537 holder.entry = entry;
16538
16539 var count = 0;
16540 var allBuffers = true;
16541 while (entry) {
16542 buffer[count] = entry;
16543 if (!entry.isBuf) allBuffers = false;
16544 entry = entry.next;
16545 count += 1;
16546 }
16547 buffer.allBuffers = allBuffers;
16548
16549 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
16550
16551 // doWrite is almost always async, defer these to save a bit of time
16552 // as the hot path ends with doWrite
16553 state.pendingcb++;
16554 state.lastBufferedRequest = null;
16555 if (holder.next) {
16556 state.corkedRequestsFree = holder.next;
16557 holder.next = null;
16558 } else {
16559 state.corkedRequestsFree = new CorkedRequest(state);
16560 }
16561 state.bufferedRequestCount = 0;
16562 } else {
16563 // Slow case, write chunks one-by-one
16564 while (entry) {
16565 var chunk = entry.chunk;
16566 var encoding = entry.encoding;
16567 var cb = entry.callback;
16568 var len = state.objectMode ? 1 : chunk.length;
16569
16570 doWrite(stream, state, false, len, chunk, encoding, cb);
16571 entry = entry.next;
16572 state.bufferedRequestCount--;
16573 // if we didn't call the onwrite immediately, then
16574 // it means that we need to wait until it does.
16575 // also, that means that the chunk and cb are currently
16576 // being processed, so move the buffer counter past them.
16577 if (state.writing) {
16578 break;
16579 }
16580 }
16581
16582 if (entry === null) state.lastBufferedRequest = null;
16583 }
16584
16585 state.bufferedRequest = entry;
16586 state.bufferProcessing = false;
16587}
16588
16589Writable.prototype._write = function (chunk, encoding, cb) {
16590 cb(new Error('_write() is not implemented'));
16591};
16592
16593Writable.prototype._writev = null;
16594
16595Writable.prototype.end = function (chunk, encoding, cb) {
16596 var state = this._writableState;
16597
16598 if (typeof chunk === 'function') {
16599 cb = chunk;
16600 chunk = null;
16601 encoding = null;
16602 } else if (typeof encoding === 'function') {
16603 cb = encoding;
16604 encoding = null;
16605 }
16606
16607 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
16608
16609 // .end() fully uncorks
16610 if (state.corked) {
16611 state.corked = 1;
16612 this.uncork();
16613 }
16614
16615 // ignore unnecessary end() calls.
16616 if (!state.ending && !state.finished) endWritable(this, state, cb);
16617};
16618
16619function needFinish(state) {
16620 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
16621}
16622function callFinal(stream, state) {
16623 stream._final(function (err) {
16624 state.pendingcb--;
16625 if (err) {
16626 stream.emit('error', err);
16627 }
16628 state.prefinished = true;
16629 stream.emit('prefinish');
16630 finishMaybe(stream, state);
16631 });
16632}
16633function prefinish(stream, state) {
16634 if (!state.prefinished && !state.finalCalled) {
16635 if (typeof stream._final === 'function') {
16636 state.pendingcb++;
16637 state.finalCalled = true;
16638 pna.nextTick(callFinal, stream, state);
16639 } else {
16640 state.prefinished = true;
16641 stream.emit('prefinish');
16642 }
16643 }
16644}
16645
16646function finishMaybe(stream, state) {
16647 var need = needFinish(state);
16648 if (need) {
16649 prefinish(stream, state);
16650 if (state.pendingcb === 0) {
16651 state.finished = true;
16652 stream.emit('finish');
16653 }
16654 }
16655 return need;
16656}
16657
16658function endWritable(stream, state, cb) {
16659 state.ending = true;
16660 finishMaybe(stream, state);
16661 if (cb) {
16662 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
16663 }
16664 state.ended = true;
16665 stream.writable = false;
16666}
16667
16668function onCorkedFinish(corkReq, state, err) {
16669 var entry = corkReq.entry;
16670 corkReq.entry = null;
16671 while (entry) {
16672 var cb = entry.callback;
16673 state.pendingcb--;
16674 cb(err);
16675 entry = entry.next;
16676 }
16677 if (state.corkedRequestsFree) {
16678 state.corkedRequestsFree.next = corkReq;
16679 } else {
16680 state.corkedRequestsFree = corkReq;
16681 }
16682}
16683
16684Object.defineProperty(Writable.prototype, 'destroyed', {
16685 get: function () {
16686 if (this._writableState === undefined) {
16687 return false;
16688 }
16689 return this._writableState.destroyed;
16690 },
16691 set: function (value) {
16692 // we ignore the value if the stream
16693 // has not been initialized yet
16694 if (!this._writableState) {
16695 return;
16696 }
16697
16698 // backward compatibility, the user is explicitly
16699 // managing destroyed
16700 this._writableState.destroyed = value;
16701 }
16702});
16703
16704Writable.prototype.destroy = destroyImpl.destroy;
16705Writable.prototype._undestroy = destroyImpl.undestroy;
16706Writable.prototype._destroy = function (err, cb) {
16707 this.end();
16708 cb(err);
16709};
16710}).call(this)}).call(this,_dereq_(67),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(113).setImmediate)
16711},{"10":10,"113":113,"114":114,"30":30,"66":66,"67":67,"82":82,"88":88,"89":89,"94":94}],87:[function(_dereq_,module,exports){
16712'use strict';
16713
16714function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16715
16716var Buffer = _dereq_(94).Buffer;
16717var util = _dereq_(7);
16718
16719function copyBuffer(src, target, offset) {
16720 src.copy(target, offset);
16721}
16722
16723module.exports = function () {
16724 function BufferList() {
16725 _classCallCheck(this, BufferList);
16726
16727 this.head = null;
16728 this.tail = null;
16729 this.length = 0;
16730 }
16731
16732 BufferList.prototype.push = function push(v) {
16733 var entry = { data: v, next: null };
16734 if (this.length > 0) this.tail.next = entry;else this.head = entry;
16735 this.tail = entry;
16736 ++this.length;
16737 };
16738
16739 BufferList.prototype.unshift = function unshift(v) {
16740 var entry = { data: v, next: this.head };
16741 if (this.length === 0) this.tail = entry;
16742 this.head = entry;
16743 ++this.length;
16744 };
16745
16746 BufferList.prototype.shift = function shift() {
16747 if (this.length === 0) return;
16748 var ret = this.head.data;
16749 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
16750 --this.length;
16751 return ret;
16752 };
16753
16754 BufferList.prototype.clear = function clear() {
16755 this.head = this.tail = null;
16756 this.length = 0;
16757 };
16758
16759 BufferList.prototype.join = function join(s) {
16760 if (this.length === 0) return '';
16761 var p = this.head;
16762 var ret = '' + p.data;
16763 while (p = p.next) {
16764 ret += s + p.data;
16765 }return ret;
16766 };
16767
16768 BufferList.prototype.concat = function concat(n) {
16769 if (this.length === 0) return Buffer.alloc(0);
16770 if (this.length === 1) return this.head.data;
16771 var ret = Buffer.allocUnsafe(n >>> 0);
16772 var p = this.head;
16773 var i = 0;
16774 while (p) {
16775 copyBuffer(p.data, ret, i);
16776 i += p.data.length;
16777 p = p.next;
16778 }
16779 return ret;
16780 };
16781
16782 return BufferList;
16783}();
16784
16785if (util && util.inspect && util.inspect.custom) {
16786 module.exports.prototype[util.inspect.custom] = function () {
16787 var obj = util.inspect({ length: this.length });
16788 return this.constructor.name + ' ' + obj;
16789 };
16790}
16791},{"7":7,"94":94}],88:[function(_dereq_,module,exports){
16792'use strict';
16793
16794/*<replacement>*/
16795
16796var pna = _dereq_(66);
16797/*</replacement>*/
16798
16799// undocumented cb() API, needed for core, not for public API
16800function destroy(err, cb) {
16801 var _this = this;
16802
16803 var readableDestroyed = this._readableState && this._readableState.destroyed;
16804 var writableDestroyed = this._writableState && this._writableState.destroyed;
16805
16806 if (readableDestroyed || writableDestroyed) {
16807 if (cb) {
16808 cb(err);
16809 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
16810 pna.nextTick(emitErrorNT, this, err);
16811 }
16812 return this;
16813 }
16814
16815 // we set destroyed to true before firing error callbacks in order
16816 // to make it re-entrance safe in case destroy() is called within callbacks
16817
16818 if (this._readableState) {
16819 this._readableState.destroyed = true;
16820 }
16821
16822 // if this is a duplex stream mark the writable part as destroyed as well
16823 if (this._writableState) {
16824 this._writableState.destroyed = true;
16825 }
16826
16827 this._destroy(err || null, function (err) {
16828 if (!cb && err) {
16829 pna.nextTick(emitErrorNT, _this, err);
16830 if (_this._writableState) {
16831 _this._writableState.errorEmitted = true;
16832 }
16833 } else if (cb) {
16834 cb(err);
16835 }
16836 });
16837
16838 return this;
16839}
16840
16841function undestroy() {
16842 if (this._readableState) {
16843 this._readableState.destroyed = false;
16844 this._readableState.reading = false;
16845 this._readableState.ended = false;
16846 this._readableState.endEmitted = false;
16847 }
16848
16849 if (this._writableState) {
16850 this._writableState.destroyed = false;
16851 this._writableState.ended = false;
16852 this._writableState.ending = false;
16853 this._writableState.finished = false;
16854 this._writableState.errorEmitted = false;
16855 }
16856}
16857
16858function emitErrorNT(self, err) {
16859 self.emit('error', err);
16860}
16861
16862module.exports = {
16863 destroy: destroy,
16864 undestroy: undestroy
16865};
16866},{"66":66}],89:[function(_dereq_,module,exports){
16867arguments[4][49][0].apply(exports,arguments)
16868},{"21":21,"49":49}],90:[function(_dereq_,module,exports){
16869module.exports = _dereq_(91).PassThrough
16870
16871},{"91":91}],91:[function(_dereq_,module,exports){
16872exports = module.exports = _dereq_(84);
16873exports.Stream = exports;
16874exports.Readable = exports;
16875exports.Writable = _dereq_(86);
16876exports.Duplex = _dereq_(82);
16877exports.Transform = _dereq_(85);
16878exports.PassThrough = _dereq_(83);
16879
16880},{"82":82,"83":83,"84":84,"85":85,"86":86}],92:[function(_dereq_,module,exports){
16881module.exports = _dereq_(91).Transform
16882
16883},{"91":91}],93:[function(_dereq_,module,exports){
16884module.exports = _dereq_(86);
16885
16886},{"86":86}],94:[function(_dereq_,module,exports){
16887arguments[4][64][0].apply(exports,arguments)
16888},{"64":64,"9":9}],95:[function(_dereq_,module,exports){
16889// Copyright Joyent, Inc. and other Node contributors.
16890//
16891// Permission is hereby granted, free of charge, to any person obtaining a
16892// copy of this software and associated documentation files (the
16893// "Software"), to deal in the Software without restriction, including
16894// without limitation the rights to use, copy, modify, merge, publish,
16895// distribute, sublicense, and/or sell copies of the Software, and to permit
16896// persons to whom the Software is furnished to do so, subject to the
16897// following conditions:
16898//
16899// The above copyright notice and this permission notice shall be included
16900// in all copies or substantial portions of the Software.
16901//
16902// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16903// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16904// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16905// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16906// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16907// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16908// USE OR OTHER DEALINGS IN THE SOFTWARE.
16909
16910'use strict';
16911
16912/*<replacement>*/
16913
16914var Buffer = _dereq_(94).Buffer;
16915/*</replacement>*/
16916
16917var isEncoding = Buffer.isEncoding || function (encoding) {
16918 encoding = '' + encoding;
16919 switch (encoding && encoding.toLowerCase()) {
16920 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':
16921 return true;
16922 default:
16923 return false;
16924 }
16925};
16926
16927function _normalizeEncoding(enc) {
16928 if (!enc) return 'utf8';
16929 var retried;
16930 while (true) {
16931 switch (enc) {
16932 case 'utf8':
16933 case 'utf-8':
16934 return 'utf8';
16935 case 'ucs2':
16936 case 'ucs-2':
16937 case 'utf16le':
16938 case 'utf-16le':
16939 return 'utf16le';
16940 case 'latin1':
16941 case 'binary':
16942 return 'latin1';
16943 case 'base64':
16944 case 'ascii':
16945 case 'hex':
16946 return enc;
16947 default:
16948 if (retried) return; // undefined
16949 enc = ('' + enc).toLowerCase();
16950 retried = true;
16951 }
16952 }
16953};
16954
16955// Do not cache `Buffer.isEncoding` when checking encoding names as some
16956// modules monkey-patch it to support additional encodings
16957function normalizeEncoding(enc) {
16958 var nenc = _normalizeEncoding(enc);
16959 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16960 return nenc || enc;
16961}
16962
16963// StringDecoder provides an interface for efficiently splitting a series of
16964// buffers into a series of JS strings without breaking apart multi-byte
16965// characters.
16966exports.StringDecoder = StringDecoder;
16967function StringDecoder(encoding) {
16968 this.encoding = normalizeEncoding(encoding);
16969 var nb;
16970 switch (this.encoding) {
16971 case 'utf16le':
16972 this.text = utf16Text;
16973 this.end = utf16End;
16974 nb = 4;
16975 break;
16976 case 'utf8':
16977 this.fillLast = utf8FillLast;
16978 nb = 4;
16979 break;
16980 case 'base64':
16981 this.text = base64Text;
16982 this.end = base64End;
16983 nb = 3;
16984 break;
16985 default:
16986 this.write = simpleWrite;
16987 this.end = simpleEnd;
16988 return;
16989 }
16990 this.lastNeed = 0;
16991 this.lastTotal = 0;
16992 this.lastChar = Buffer.allocUnsafe(nb);
16993}
16994
16995StringDecoder.prototype.write = function (buf) {
16996 if (buf.length === 0) return '';
16997 var r;
16998 var i;
16999 if (this.lastNeed) {
17000 r = this.fillLast(buf);
17001 if (r === undefined) return '';
17002 i = this.lastNeed;
17003 this.lastNeed = 0;
17004 } else {
17005 i = 0;
17006 }
17007 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
17008 return r || '';
17009};
17010
17011StringDecoder.prototype.end = utf8End;
17012
17013// Returns only complete characters in a Buffer
17014StringDecoder.prototype.text = utf8Text;
17015
17016// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
17017StringDecoder.prototype.fillLast = function (buf) {
17018 if (this.lastNeed <= buf.length) {
17019 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
17020 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
17021 }
17022 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
17023 this.lastNeed -= buf.length;
17024};
17025
17026// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
17027// continuation byte. If an invalid byte is detected, -2 is returned.
17028function utf8CheckByte(byte) {
17029 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;
17030 return byte >> 6 === 0x02 ? -1 : -2;
17031}
17032
17033// Checks at most 3 bytes at the end of a Buffer in order to detect an
17034// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
17035// needed to complete the UTF-8 character (if applicable) are returned.
17036function utf8CheckIncomplete(self, buf, i) {
17037 var j = buf.length - 1;
17038 if (j < i) return 0;
17039 var nb = utf8CheckByte(buf[j]);
17040 if (nb >= 0) {
17041 if (nb > 0) self.lastNeed = nb - 1;
17042 return nb;
17043 }
17044 if (--j < i || nb === -2) return 0;
17045 nb = utf8CheckByte(buf[j]);
17046 if (nb >= 0) {
17047 if (nb > 0) self.lastNeed = nb - 2;
17048 return nb;
17049 }
17050 if (--j < i || nb === -2) return 0;
17051 nb = utf8CheckByte(buf[j]);
17052 if (nb >= 0) {
17053 if (nb > 0) {
17054 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
17055 }
17056 return nb;
17057 }
17058 return 0;
17059}
17060
17061// Validates as many continuation bytes for a multi-byte UTF-8 character as
17062// needed or are available. If we see a non-continuation byte where we expect
17063// one, we "replace" the validated continuation bytes we've seen so far with
17064// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
17065// behavior. The continuation byte check is included three times in the case
17066// where all of the continuation bytes for a character exist in the same buffer.
17067// It is also done this way as a slight performance increase instead of using a
17068// loop.
17069function utf8CheckExtraBytes(self, buf, p) {
17070 if ((buf[0] & 0xC0) !== 0x80) {
17071 self.lastNeed = 0;
17072 return '\ufffd';
17073 }
17074 if (self.lastNeed > 1 && buf.length > 1) {
17075 if ((buf[1] & 0xC0) !== 0x80) {
17076 self.lastNeed = 1;
17077 return '\ufffd';
17078 }
17079 if (self.lastNeed > 2 && buf.length > 2) {
17080 if ((buf[2] & 0xC0) !== 0x80) {
17081 self.lastNeed = 2;
17082 return '\ufffd';
17083 }
17084 }
17085 }
17086}
17087
17088// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
17089function utf8FillLast(buf) {
17090 var p = this.lastTotal - this.lastNeed;
17091 var r = utf8CheckExtraBytes(this, buf, p);
17092 if (r !== undefined) return r;
17093 if (this.lastNeed <= buf.length) {
17094 buf.copy(this.lastChar, p, 0, this.lastNeed);
17095 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
17096 }
17097 buf.copy(this.lastChar, p, 0, buf.length);
17098 this.lastNeed -= buf.length;
17099}
17100
17101// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
17102// partial character, the character's bytes are buffered until the required
17103// number of bytes are available.
17104function utf8Text(buf, i) {
17105 var total = utf8CheckIncomplete(this, buf, i);
17106 if (!this.lastNeed) return buf.toString('utf8', i);
17107 this.lastTotal = total;
17108 var end = buf.length - (total - this.lastNeed);
17109 buf.copy(this.lastChar, 0, end);
17110 return buf.toString('utf8', i, end);
17111}
17112
17113// For UTF-8, a replacement character is added when ending on a partial
17114// character.
17115function utf8End(buf) {
17116 var r = buf && buf.length ? this.write(buf) : '';
17117 if (this.lastNeed) return r + '\ufffd';
17118 return r;
17119}
17120
17121// UTF-16LE typically needs two bytes per character, but even if we have an even
17122// number of bytes available, we need to check if we end on a leading/high
17123// surrogate. In that case, we need to wait for the next two bytes in order to
17124// decode the last character properly.
17125function utf16Text(buf, i) {
17126 if ((buf.length - i) % 2 === 0) {
17127 var r = buf.toString('utf16le', i);
17128 if (r) {
17129 var c = r.charCodeAt(r.length - 1);
17130 if (c >= 0xD800 && c <= 0xDBFF) {
17131 this.lastNeed = 2;
17132 this.lastTotal = 4;
17133 this.lastChar[0] = buf[buf.length - 2];
17134 this.lastChar[1] = buf[buf.length - 1];
17135 return r.slice(0, -1);
17136 }
17137 }
17138 return r;
17139 }
17140 this.lastNeed = 1;
17141 this.lastTotal = 2;
17142 this.lastChar[0] = buf[buf.length - 1];
17143 return buf.toString('utf16le', i, buf.length - 1);
17144}
17145
17146// For UTF-16LE we do not explicitly append special replacement characters if we
17147// end on a partial character, we simply let v8 handle that.
17148function utf16End(buf) {
17149 var r = buf && buf.length ? this.write(buf) : '';
17150 if (this.lastNeed) {
17151 var end = this.lastTotal - this.lastNeed;
17152 return r + this.lastChar.toString('utf16le', 0, end);
17153 }
17154 return r;
17155}
17156
17157function base64Text(buf, i) {
17158 var n = (buf.length - i) % 3;
17159 if (n === 0) return buf.toString('base64', i);
17160 this.lastNeed = 3 - n;
17161 this.lastTotal = 3;
17162 if (n === 1) {
17163 this.lastChar[0] = buf[buf.length - 1];
17164 } else {
17165 this.lastChar[0] = buf[buf.length - 2];
17166 this.lastChar[1] = buf[buf.length - 1];
17167 }
17168 return buf.toString('base64', i, buf.length - n);
17169}
17170
17171function base64End(buf) {
17172 var r = buf && buf.length ? this.write(buf) : '';
17173 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
17174 return r;
17175}
17176
17177// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
17178function simpleWrite(buf) {
17179 return buf.toString(this.encoding);
17180}
17181
17182function simpleEnd(buf) {
17183 return buf && buf.length ? this.write(buf) : '';
17184}
17185},{"94":94}],96:[function(_dereq_,module,exports){
17186arguments[4][95][0].apply(exports,arguments)
17187},{"77":77,"95":95}],97:[function(_dereq_,module,exports){
17188arguments[4][36][0].apply(exports,arguments)
17189},{"36":36}],98:[function(_dereq_,module,exports){
17190arguments[4][37][0].apply(exports,arguments)
17191},{"100":100,"102":102,"30":30,"37":37,"67":67}],99:[function(_dereq_,module,exports){
17192arguments[4][38][0].apply(exports,arguments)
17193},{"101":101,"30":30,"38":38}],100:[function(_dereq_,module,exports){
17194arguments[4][39][0].apply(exports,arguments)
17195},{"103":103,"104":104,"105":105,"107":107,"109":109,"110":110,"21":21,"30":30,"39":39,"67":67,"7":7,"9":9,"96":96,"97":97,"98":98}],101:[function(_dereq_,module,exports){
17196arguments[4][40][0].apply(exports,arguments)
17197},{"30":30,"40":40,"97":97,"98":98}],102:[function(_dereq_,module,exports){
17198arguments[4][41][0].apply(exports,arguments)
17199},{"105":105,"109":109,"110":110,"114":114,"30":30,"41":41,"67":67,"9":9,"97":97,"98":98}],103:[function(_dereq_,module,exports){
17200arguments[4][42][0].apply(exports,arguments)
17201},{"106":106,"42":42,"67":67}],104:[function(_dereq_,module,exports){
17202arguments[4][43][0].apply(exports,arguments)
17203},{"43":43,"7":7,"9":9}],105:[function(_dereq_,module,exports){
17204arguments[4][44][0].apply(exports,arguments)
17205},{"44":44,"67":67}],106:[function(_dereq_,module,exports){
17206arguments[4][45][0].apply(exports,arguments)
17207},{"45":45,"97":97}],107:[function(_dereq_,module,exports){
17208arguments[4][46][0].apply(exports,arguments)
17209},{"46":46}],108:[function(_dereq_,module,exports){
17210arguments[4][47][0].apply(exports,arguments)
17211},{"106":106,"47":47,"97":97}],109:[function(_dereq_,module,exports){
17212arguments[4][48][0].apply(exports,arguments)
17213},{"48":48,"97":97}],110:[function(_dereq_,module,exports){
17214arguments[4][49][0].apply(exports,arguments)
17215},{"21":21,"49":49}],111:[function(_dereq_,module,exports){
17216arguments[4][50][0].apply(exports,arguments)
17217},{"100":100,"101":101,"102":102,"106":106,"108":108,"50":50,"98":98,"99":99}],112:[function(_dereq_,module,exports){
17218(function (process){(function (){
17219var Transform = _dereq_(111).Transform
17220 , inherits = _dereq_(30)
17221
17222function DestroyableTransform(opts) {
17223 Transform.call(this, opts)
17224 this._destroyed = false
17225}
17226
17227inherits(DestroyableTransform, Transform)
17228
17229DestroyableTransform.prototype.destroy = function(err) {
17230 if (this._destroyed) return
17231 this._destroyed = true
17232
17233 var self = this
17234 process.nextTick(function() {
17235 if (err)
17236 self.emit('error', err)
17237 self.emit('close')
17238 })
17239}
17240
17241// a noop _transform function
17242function noop (chunk, enc, callback) {
17243 callback(null, chunk)
17244}
17245
17246
17247// create a new export function, used by both the main export and
17248// the .ctor export, contains common logic for dealing with arguments
17249function through2 (construct) {
17250 return function (options, transform, flush) {
17251 if (typeof options == 'function') {
17252 flush = transform
17253 transform = options
17254 options = {}
17255 }
17256
17257 if (typeof transform != 'function')
17258 transform = noop
17259
17260 if (typeof flush != 'function')
17261 flush = null
17262
17263 return construct(options, transform, flush)
17264 }
17265}
17266
17267
17268// main export, just make me a transform stream!
17269module.exports = through2(function (options, transform, flush) {
17270 var t2 = new DestroyableTransform(options)
17271
17272 t2._transform = transform
17273
17274 if (flush)
17275 t2._flush = flush
17276
17277 return t2
17278})
17279
17280
17281// make me a reusable prototype that I can `new`, or implicitly `new`
17282// with a constructor call
17283module.exports.ctor = through2(function (options, transform, flush) {
17284 function Through2 (override) {
17285 if (!(this instanceof Through2))
17286 return new Through2(override)
17287
17288 this.options = Object.assign({}, options, override)
17289
17290 DestroyableTransform.call(this, this.options)
17291 }
17292
17293 inherits(Through2, DestroyableTransform)
17294
17295 Through2.prototype._transform = transform
17296
17297 if (flush)
17298 Through2.prototype._flush = flush
17299
17300 return Through2
17301})
17302
17303
17304module.exports.obj = through2(function (options, transform, flush) {
17305 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
17306
17307 t2._transform = transform
17308
17309 if (flush)
17310 t2._flush = flush
17311
17312 return t2
17313})
17314
17315}).call(this)}).call(this,_dereq_(67))
17316},{"111":111,"30":30,"67":67}],113:[function(_dereq_,module,exports){
17317(function (setImmediate,clearImmediate){(function (){
17318var nextTick = _dereq_(67).nextTick;
17319var apply = Function.prototype.apply;
17320var slice = Array.prototype.slice;
17321var immediateIds = {};
17322var nextImmediateId = 0;
17323
17324// DOM APIs, for completeness
17325
17326exports.setTimeout = function() {
17327 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
17328};
17329exports.setInterval = function() {
17330 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
17331};
17332exports.clearTimeout =
17333exports.clearInterval = function(timeout) { timeout.close(); };
17334
17335function Timeout(id, clearFn) {
17336 this._id = id;
17337 this._clearFn = clearFn;
17338}
17339Timeout.prototype.unref = Timeout.prototype.ref = function() {};
17340Timeout.prototype.close = function() {
17341 this._clearFn.call(window, this._id);
17342};
17343
17344// Does not start the time, just sets up the members needed.
17345exports.enroll = function(item, msecs) {
17346 clearTimeout(item._idleTimeoutId);
17347 item._idleTimeout = msecs;
17348};
17349
17350exports.unenroll = function(item) {
17351 clearTimeout(item._idleTimeoutId);
17352 item._idleTimeout = -1;
17353};
17354
17355exports._unrefActive = exports.active = function(item) {
17356 clearTimeout(item._idleTimeoutId);
17357
17358 var msecs = item._idleTimeout;
17359 if (msecs >= 0) {
17360 item._idleTimeoutId = setTimeout(function onTimeout() {
17361 if (item._onTimeout)
17362 item._onTimeout();
17363 }, msecs);
17364 }
17365};
17366
17367// That's not how node.js implements it but the exposed api is the same.
17368exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
17369 var id = nextImmediateId++;
17370 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
17371
17372 immediateIds[id] = true;
17373
17374 nextTick(function onNextTick() {
17375 if (immediateIds[id]) {
17376 // fn.call() is faster so we optimize for the common use-case
17377 // @see http://jsperf.com/call-apply-segu
17378 if (args) {
17379 fn.apply(null, args);
17380 } else {
17381 fn.call(null);
17382 }
17383 // Prevent ids from leaking
17384 exports.clearImmediate(id);
17385 }
17386 });
17387
17388 return id;
17389};
17390
17391exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
17392 delete immediateIds[id];
17393};
17394}).call(this)}).call(this,_dereq_(113).setImmediate,_dereq_(113).clearImmediate)
17395},{"113":113,"67":67}],114:[function(_dereq_,module,exports){
17396(function (global){(function (){
17397
17398/**
17399 * Module exports.
17400 */
17401
17402module.exports = deprecate;
17403
17404/**
17405 * Mark that a method should not be used.
17406 * Returns a modified function which warns once by default.
17407 *
17408 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
17409 *
17410 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
17411 * will throw an Error when invoked.
17412 *
17413 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
17414 * will invoke `console.trace()` instead of `console.error()`.
17415 *
17416 * @param {Function} fn - the function to deprecate
17417 * @param {String} msg - the string to print to the console when `fn` is invoked
17418 * @returns {Function} a new "deprecated" version of `fn`
17419 * @api public
17420 */
17421
17422function deprecate (fn, msg) {
17423 if (config('noDeprecation')) {
17424 return fn;
17425 }
17426
17427 var warned = false;
17428 function deprecated() {
17429 if (!warned) {
17430 if (config('throwDeprecation')) {
17431 throw new Error(msg);
17432 } else if (config('traceDeprecation')) {
17433 console.trace(msg);
17434 } else {
17435 console.warn(msg);
17436 }
17437 warned = true;
17438 }
17439 return fn.apply(this, arguments);
17440 }
17441
17442 return deprecated;
17443}
17444
17445/**
17446 * Checks `localStorage` for boolean values for the given `name`.
17447 *
17448 * @param {String} name
17449 * @returns {Boolean}
17450 * @api private
17451 */
17452
17453function config (name) {
17454 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
17455 try {
17456 if (!global.localStorage) return false;
17457 } catch (_) {
17458 return false;
17459 }
17460 var val = global.localStorage[name];
17461 if (null == val) return false;
17462 return String(val).toLowerCase() === 'true';
17463}
17464
17465}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17466},{}],115:[function(_dereq_,module,exports){
17467arguments[4][3][0].apply(exports,arguments)
17468},{"3":3}],116:[function(_dereq_,module,exports){
17469arguments[4][4][0].apply(exports,arguments)
17470},{"4":4}],117:[function(_dereq_,module,exports){
17471arguments[4][5][0].apply(exports,arguments)
17472},{"115":115,"116":116,"5":5,"67":67}],118:[function(_dereq_,module,exports){
17473"use strict";
17474
17475Object.defineProperty(exports, "__esModule", {
17476 value: true
17477});
17478Object.defineProperty(exports, "v1", {
17479 enumerable: true,
17480 get: function () {
17481 return _v.default;
17482 }
17483});
17484Object.defineProperty(exports, "v3", {
17485 enumerable: true,
17486 get: function () {
17487 return _v2.default;
17488 }
17489});
17490Object.defineProperty(exports, "v4", {
17491 enumerable: true,
17492 get: function () {
17493 return _v3.default;
17494 }
17495});
17496Object.defineProperty(exports, "v5", {
17497 enumerable: true,
17498 get: function () {
17499 return _v4.default;
17500 }
17501});
17502Object.defineProperty(exports, "NIL", {
17503 enumerable: true,
17504 get: function () {
17505 return _nil.default;
17506 }
17507});
17508Object.defineProperty(exports, "version", {
17509 enumerable: true,
17510 get: function () {
17511 return _version.default;
17512 }
17513});
17514Object.defineProperty(exports, "validate", {
17515 enumerable: true,
17516 get: function () {
17517 return _validate.default;
17518 }
17519});
17520Object.defineProperty(exports, "stringify", {
17521 enumerable: true,
17522 get: function () {
17523 return _stringify.default;
17524 }
17525});
17526Object.defineProperty(exports, "parse", {
17527 enumerable: true,
17528 get: function () {
17529 return _parse.default;
17530 }
17531});
17532
17533var _v = _interopRequireDefault(_dereq_(126));
17534
17535var _v2 = _interopRequireDefault(_dereq_(127));
17536
17537var _v3 = _interopRequireDefault(_dereq_(129));
17538
17539var _v4 = _interopRequireDefault(_dereq_(130));
17540
17541var _nil = _interopRequireDefault(_dereq_(120));
17542
17543var _version = _interopRequireDefault(_dereq_(132));
17544
17545var _validate = _interopRequireDefault(_dereq_(131));
17546
17547var _stringify = _interopRequireDefault(_dereq_(125));
17548
17549var _parse = _interopRequireDefault(_dereq_(121));
17550
17551function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17552},{"120":120,"121":121,"125":125,"126":126,"127":127,"129":129,"130":130,"131":131,"132":132}],119:[function(_dereq_,module,exports){
17553"use strict";
17554
17555Object.defineProperty(exports, "__esModule", {
17556 value: true
17557});
17558exports.default = void 0;
17559
17560/*
17561 * Browser-compatible JavaScript MD5
17562 *
17563 * Modification of JavaScript MD5
17564 * https://github.com/blueimp/JavaScript-MD5
17565 *
17566 * Copyright 2011, Sebastian Tschan
17567 * https://blueimp.net
17568 *
17569 * Licensed under the MIT license:
17570 * https://opensource.org/licenses/MIT
17571 *
17572 * Based on
17573 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
17574 * Digest Algorithm, as defined in RFC 1321.
17575 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
17576 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
17577 * Distributed under the BSD License
17578 * See http://pajhome.org.uk/crypt/md5 for more info.
17579 */
17580function md5(bytes) {
17581 if (typeof bytes === 'string') {
17582 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
17583
17584 bytes = new Uint8Array(msg.length);
17585
17586 for (let i = 0; i < msg.length; ++i) {
17587 bytes[i] = msg.charCodeAt(i);
17588 }
17589 }
17590
17591 return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
17592}
17593/*
17594 * Convert an array of little-endian words to an array of bytes
17595 */
17596
17597
17598function md5ToHexEncodedArray(input) {
17599 const output = [];
17600 const length32 = input.length * 32;
17601 const hexTab = '0123456789abcdef';
17602
17603 for (let i = 0; i < length32; i += 8) {
17604 const x = input[i >> 5] >>> i % 32 & 0xff;
17605 const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
17606 output.push(hex);
17607 }
17608
17609 return output;
17610}
17611/**
17612 * Calculate output length with padding and bit length
17613 */
17614
17615
17616function getOutputLength(inputLength8) {
17617 return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
17618}
17619/*
17620 * Calculate the MD5 of an array of little-endian words, and a bit length.
17621 */
17622
17623
17624function wordsToMd5(x, len) {
17625 /* append padding */
17626 x[len >> 5] |= 0x80 << len % 32;
17627 x[getOutputLength(len) - 1] = len;
17628 let a = 1732584193;
17629 let b = -271733879;
17630 let c = -1732584194;
17631 let d = 271733878;
17632
17633 for (let i = 0; i < x.length; i += 16) {
17634 const olda = a;
17635 const oldb = b;
17636 const oldc = c;
17637 const oldd = d;
17638 a = md5ff(a, b, c, d, x[i], 7, -680876936);
17639 d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
17640 c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
17641 b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
17642 a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
17643 d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
17644 c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
17645 b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
17646 a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
17647 d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
17648 c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
17649 b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
17650 a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
17651 d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
17652 c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
17653 b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
17654 a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
17655 d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
17656 c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
17657 b = md5gg(b, c, d, a, x[i], 20, -373897302);
17658 a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
17659 d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
17660 c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
17661 b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
17662 a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
17663 d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
17664 c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
17665 b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
17666 a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
17667 d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
17668 c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
17669 b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
17670 a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
17671 d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
17672 c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
17673 b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
17674 a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
17675 d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
17676 c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
17677 b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
17678 a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
17679 d = md5hh(d, a, b, c, x[i], 11, -358537222);
17680 c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
17681 b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
17682 a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
17683 d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
17684 c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
17685 b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
17686 a = md5ii(a, b, c, d, x[i], 6, -198630844);
17687 d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
17688 c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
17689 b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
17690 a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
17691 d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
17692 c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
17693 b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
17694 a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
17695 d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
17696 c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
17697 b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
17698 a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
17699 d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
17700 c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
17701 b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
17702 a = safeAdd(a, olda);
17703 b = safeAdd(b, oldb);
17704 c = safeAdd(c, oldc);
17705 d = safeAdd(d, oldd);
17706 }
17707
17708 return [a, b, c, d];
17709}
17710/*
17711 * Convert an array bytes to an array of little-endian words
17712 * Characters >255 have their high-byte silently ignored.
17713 */
17714
17715
17716function bytesToWords(input) {
17717 if (input.length === 0) {
17718 return [];
17719 }
17720
17721 const length8 = input.length * 8;
17722 const output = new Uint32Array(getOutputLength(length8));
17723
17724 for (let i = 0; i < length8; i += 8) {
17725 output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
17726 }
17727
17728 return output;
17729}
17730/*
17731 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
17732 * to work around bugs in some JS interpreters.
17733 */
17734
17735
17736function safeAdd(x, y) {
17737 const lsw = (x & 0xffff) + (y & 0xffff);
17738 const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
17739 return msw << 16 | lsw & 0xffff;
17740}
17741/*
17742 * Bitwise rotate a 32-bit number to the left.
17743 */
17744
17745
17746function bitRotateLeft(num, cnt) {
17747 return num << cnt | num >>> 32 - cnt;
17748}
17749/*
17750 * These functions implement the four basic operations the algorithm uses.
17751 */
17752
17753
17754function md5cmn(q, a, b, x, s, t) {
17755 return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
17756}
17757
17758function md5ff(a, b, c, d, x, s, t) {
17759 return md5cmn(b & c | ~b & d, a, b, x, s, t);
17760}
17761
17762function md5gg(a, b, c, d, x, s, t) {
17763 return md5cmn(b & d | c & ~d, a, b, x, s, t);
17764}
17765
17766function md5hh(a, b, c, d, x, s, t) {
17767 return md5cmn(b ^ c ^ d, a, b, x, s, t);
17768}
17769
17770function md5ii(a, b, c, d, x, s, t) {
17771 return md5cmn(c ^ (b | ~d), a, b, x, s, t);
17772}
17773
17774var _default = md5;
17775exports.default = _default;
17776},{}],120:[function(_dereq_,module,exports){
17777"use strict";
17778
17779Object.defineProperty(exports, "__esModule", {
17780 value: true
17781});
17782exports.default = void 0;
17783var _default = '00000000-0000-0000-0000-000000000000';
17784exports.default = _default;
17785},{}],121:[function(_dereq_,module,exports){
17786"use strict";
17787
17788Object.defineProperty(exports, "__esModule", {
17789 value: true
17790});
17791exports.default = void 0;
17792
17793var _validate = _interopRequireDefault(_dereq_(131));
17794
17795function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17796
17797function parse(uuid) {
17798 if (!(0, _validate.default)(uuid)) {
17799 throw TypeError('Invalid UUID');
17800 }
17801
17802 let v;
17803 const arr = new Uint8Array(16); // Parse ########-....-....-....-............
17804
17805 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
17806 arr[1] = v >>> 16 & 0xff;
17807 arr[2] = v >>> 8 & 0xff;
17808 arr[3] = v & 0xff; // Parse ........-####-....-....-............
17809
17810 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
17811 arr[5] = v & 0xff; // Parse ........-....-####-....-............
17812
17813 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
17814 arr[7] = v & 0xff; // Parse ........-....-....-####-............
17815
17816 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
17817 arr[9] = v & 0xff; // Parse ........-....-....-....-############
17818 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
17819
17820 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
17821 arr[11] = v / 0x100000000 & 0xff;
17822 arr[12] = v >>> 24 & 0xff;
17823 arr[13] = v >>> 16 & 0xff;
17824 arr[14] = v >>> 8 & 0xff;
17825 arr[15] = v & 0xff;
17826 return arr;
17827}
17828
17829var _default = parse;
17830exports.default = _default;
17831},{"131":131}],122:[function(_dereq_,module,exports){
17832"use strict";
17833
17834Object.defineProperty(exports, "__esModule", {
17835 value: true
17836});
17837exports.default = void 0;
17838var _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;
17839exports.default = _default;
17840},{}],123:[function(_dereq_,module,exports){
17841"use strict";
17842
17843Object.defineProperty(exports, "__esModule", {
17844 value: true
17845});
17846exports.default = rng;
17847// Unique ID creation requires a high quality random # generator. In the browser we therefore
17848// require the crypto API and do not support built-in fallback to lower quality random number
17849// generators (like Math.random()).
17850let getRandomValues;
17851const rnds8 = new Uint8Array(16);
17852
17853function rng() {
17854 // lazy load so that environments that need to polyfill have a chance to do so
17855 if (!getRandomValues) {
17856 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
17857 // find the complete implementation of crypto (msCrypto) on IE11.
17858 getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
17859
17860 if (!getRandomValues) {
17861 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
17862 }
17863 }
17864
17865 return getRandomValues(rnds8);
17866}
17867},{}],124:[function(_dereq_,module,exports){
17868"use strict";
17869
17870Object.defineProperty(exports, "__esModule", {
17871 value: true
17872});
17873exports.default = void 0;
17874
17875// Adapted from Chris Veness' SHA1 code at
17876// http://www.movable-type.co.uk/scripts/sha1.html
17877function f(s, x, y, z) {
17878 switch (s) {
17879 case 0:
17880 return x & y ^ ~x & z;
17881
17882 case 1:
17883 return x ^ y ^ z;
17884
17885 case 2:
17886 return x & y ^ x & z ^ y & z;
17887
17888 case 3:
17889 return x ^ y ^ z;
17890 }
17891}
17892
17893function ROTL(x, n) {
17894 return x << n | x >>> 32 - n;
17895}
17896
17897function sha1(bytes) {
17898 const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
17899 const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
17900
17901 if (typeof bytes === 'string') {
17902 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
17903
17904 bytes = [];
17905
17906 for (let i = 0; i < msg.length; ++i) {
17907 bytes.push(msg.charCodeAt(i));
17908 }
17909 } else if (!Array.isArray(bytes)) {
17910 // Convert Array-like to Array
17911 bytes = Array.prototype.slice.call(bytes);
17912 }
17913
17914 bytes.push(0x80);
17915 const l = bytes.length / 4 + 2;
17916 const N = Math.ceil(l / 16);
17917 const M = new Array(N);
17918
17919 for (let i = 0; i < N; ++i) {
17920 const arr = new Uint32Array(16);
17921
17922 for (let j = 0; j < 16; ++j) {
17923 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];
17924 }
17925
17926 M[i] = arr;
17927 }
17928
17929 M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
17930 M[N - 1][14] = Math.floor(M[N - 1][14]);
17931 M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
17932
17933 for (let i = 0; i < N; ++i) {
17934 const W = new Uint32Array(80);
17935
17936 for (let t = 0; t < 16; ++t) {
17937 W[t] = M[i][t];
17938 }
17939
17940 for (let t = 16; t < 80; ++t) {
17941 W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
17942 }
17943
17944 let a = H[0];
17945 let b = H[1];
17946 let c = H[2];
17947 let d = H[3];
17948 let e = H[4];
17949
17950 for (let t = 0; t < 80; ++t) {
17951 const s = Math.floor(t / 20);
17952 const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
17953 e = d;
17954 d = c;
17955 c = ROTL(b, 30) >>> 0;
17956 b = a;
17957 a = T;
17958 }
17959
17960 H[0] = H[0] + a >>> 0;
17961 H[1] = H[1] + b >>> 0;
17962 H[2] = H[2] + c >>> 0;
17963 H[3] = H[3] + d >>> 0;
17964 H[4] = H[4] + e >>> 0;
17965 }
17966
17967 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];
17968}
17969
17970var _default = sha1;
17971exports.default = _default;
17972},{}],125:[function(_dereq_,module,exports){
17973"use strict";
17974
17975Object.defineProperty(exports, "__esModule", {
17976 value: true
17977});
17978exports.default = void 0;
17979
17980var _validate = _interopRequireDefault(_dereq_(131));
17981
17982function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17983
17984/**
17985 * Convert array of 16 byte values to UUID string format of the form:
17986 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
17987 */
17988const byteToHex = [];
17989
17990for (let i = 0; i < 256; ++i) {
17991 byteToHex.push((i + 0x100).toString(16).substr(1));
17992}
17993
17994function stringify(arr, offset = 0) {
17995 // Note: Be careful editing this code! It's been tuned for performance
17996 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
17997 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
17998 // of the following:
17999 // - One or more input array values don't map to a hex octet (leading to
18000 // "undefined" in the uuid)
18001 // - Invalid input values for the RFC `version` or `variant` fields
18002
18003 if (!(0, _validate.default)(uuid)) {
18004 throw TypeError('Stringified UUID is invalid');
18005 }
18006
18007 return uuid;
18008}
18009
18010var _default = stringify;
18011exports.default = _default;
18012},{"131":131}],126:[function(_dereq_,module,exports){
18013"use strict";
18014
18015Object.defineProperty(exports, "__esModule", {
18016 value: true
18017});
18018exports.default = void 0;
18019
18020var _rng = _interopRequireDefault(_dereq_(123));
18021
18022var _stringify = _interopRequireDefault(_dereq_(125));
18023
18024function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18025
18026// **`v1()` - Generate time-based UUID**
18027//
18028// Inspired by https://github.com/LiosK/UUID.js
18029// and http://docs.python.org/library/uuid.html
18030let _nodeId;
18031
18032let _clockseq; // Previous uuid creation time
18033
18034
18035let _lastMSecs = 0;
18036let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
18037
18038function v1(options, buf, offset) {
18039 let i = buf && offset || 0;
18040 const b = buf || new Array(16);
18041 options = options || {};
18042 let node = options.node || _nodeId;
18043 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
18044 // specified. We do this lazily to minimize issues related to insufficient
18045 // system entropy. See #189
18046
18047 if (node == null || clockseq == null) {
18048 const seedBytes = options.random || (options.rng || _rng.default)();
18049
18050 if (node == null) {
18051 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
18052 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
18053 }
18054
18055 if (clockseq == null) {
18056 // Per 4.2.2, randomize (14 bit) clockseq
18057 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
18058 }
18059 } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
18060 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
18061 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
18062 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
18063
18064
18065 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
18066 // cycle to simulate higher resolution clock
18067
18068 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
18069
18070 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
18071
18072 if (dt < 0 && options.clockseq === undefined) {
18073 clockseq = clockseq + 1 & 0x3fff;
18074 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
18075 // time interval
18076
18077
18078 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
18079 nsecs = 0;
18080 } // Per 4.2.1.2 Throw error if too many uuids are requested
18081
18082
18083 if (nsecs >= 10000) {
18084 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
18085 }
18086
18087 _lastMSecs = msecs;
18088 _lastNSecs = nsecs;
18089 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
18090
18091 msecs += 12219292800000; // `time_low`
18092
18093 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
18094 b[i++] = tl >>> 24 & 0xff;
18095 b[i++] = tl >>> 16 & 0xff;
18096 b[i++] = tl >>> 8 & 0xff;
18097 b[i++] = tl & 0xff; // `time_mid`
18098
18099 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
18100 b[i++] = tmh >>> 8 & 0xff;
18101 b[i++] = tmh & 0xff; // `time_high_and_version`
18102
18103 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
18104
18105 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
18106
18107 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
18108
18109 b[i++] = clockseq & 0xff; // `node`
18110
18111 for (let n = 0; n < 6; ++n) {
18112 b[i + n] = node[n];
18113 }
18114
18115 return buf || (0, _stringify.default)(b);
18116}
18117
18118var _default = v1;
18119exports.default = _default;
18120},{"123":123,"125":125}],127:[function(_dereq_,module,exports){
18121"use strict";
18122
18123Object.defineProperty(exports, "__esModule", {
18124 value: true
18125});
18126exports.default = void 0;
18127
18128var _v = _interopRequireDefault(_dereq_(128));
18129
18130var _md = _interopRequireDefault(_dereq_(119));
18131
18132function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18133
18134const v3 = (0, _v.default)('v3', 0x30, _md.default);
18135var _default = v3;
18136exports.default = _default;
18137},{"119":119,"128":128}],128:[function(_dereq_,module,exports){
18138"use strict";
18139
18140Object.defineProperty(exports, "__esModule", {
18141 value: true
18142});
18143exports.default = _default;
18144exports.URL = exports.DNS = void 0;
18145
18146var _stringify = _interopRequireDefault(_dereq_(125));
18147
18148var _parse = _interopRequireDefault(_dereq_(121));
18149
18150function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18151
18152function stringToBytes(str) {
18153 str = unescape(encodeURIComponent(str)); // UTF8 escape
18154
18155 const bytes = [];
18156
18157 for (let i = 0; i < str.length; ++i) {
18158 bytes.push(str.charCodeAt(i));
18159 }
18160
18161 return bytes;
18162}
18163
18164const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
18165exports.DNS = DNS;
18166const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
18167exports.URL = URL;
18168
18169function _default(name, version, hashfunc) {
18170 function generateUUID(value, namespace, buf, offset) {
18171 if (typeof value === 'string') {
18172 value = stringToBytes(value);
18173 }
18174
18175 if (typeof namespace === 'string') {
18176 namespace = (0, _parse.default)(namespace);
18177 }
18178
18179 if (namespace.length !== 16) {
18180 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
18181 } // Compute hash of namespace and value, Per 4.3
18182 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
18183 // hashfunc([...namespace, ... value])`
18184
18185
18186 let bytes = new Uint8Array(16 + value.length);
18187 bytes.set(namespace);
18188 bytes.set(value, namespace.length);
18189 bytes = hashfunc(bytes);
18190 bytes[6] = bytes[6] & 0x0f | version;
18191 bytes[8] = bytes[8] & 0x3f | 0x80;
18192
18193 if (buf) {
18194 offset = offset || 0;
18195
18196 for (let i = 0; i < 16; ++i) {
18197 buf[offset + i] = bytes[i];
18198 }
18199
18200 return buf;
18201 }
18202
18203 return (0, _stringify.default)(bytes);
18204 } // Function#name is not settable on some platforms (#270)
18205
18206
18207 try {
18208 generateUUID.name = name; // eslint-disable-next-line no-empty
18209 } catch (err) {} // For CommonJS default export support
18210
18211
18212 generateUUID.DNS = DNS;
18213 generateUUID.URL = URL;
18214 return generateUUID;
18215}
18216},{"121":121,"125":125}],129:[function(_dereq_,module,exports){
18217"use strict";
18218
18219Object.defineProperty(exports, "__esModule", {
18220 value: true
18221});
18222exports.default = void 0;
18223
18224var _rng = _interopRequireDefault(_dereq_(123));
18225
18226var _stringify = _interopRequireDefault(_dereq_(125));
18227
18228function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18229
18230function v4(options, buf, offset) {
18231 options = options || {};
18232
18233 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
18234
18235
18236 rnds[6] = rnds[6] & 0x0f | 0x40;
18237 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
18238
18239 if (buf) {
18240 offset = offset || 0;
18241
18242 for (let i = 0; i < 16; ++i) {
18243 buf[offset + i] = rnds[i];
18244 }
18245
18246 return buf;
18247 }
18248
18249 return (0, _stringify.default)(rnds);
18250}
18251
18252var _default = v4;
18253exports.default = _default;
18254},{"123":123,"125":125}],130:[function(_dereq_,module,exports){
18255"use strict";
18256
18257Object.defineProperty(exports, "__esModule", {
18258 value: true
18259});
18260exports.default = void 0;
18261
18262var _v = _interopRequireDefault(_dereq_(128));
18263
18264var _sha = _interopRequireDefault(_dereq_(124));
18265
18266function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18267
18268const v5 = (0, _v.default)('v5', 0x50, _sha.default);
18269var _default = v5;
18270exports.default = _default;
18271},{"124":124,"128":128}],131:[function(_dereq_,module,exports){
18272"use strict";
18273
18274Object.defineProperty(exports, "__esModule", {
18275 value: true
18276});
18277exports.default = void 0;
18278
18279var _regex = _interopRequireDefault(_dereq_(122));
18280
18281function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18282
18283function validate(uuid) {
18284 return typeof uuid === 'string' && _regex.default.test(uuid);
18285}
18286
18287var _default = validate;
18288exports.default = _default;
18289},{"122":122}],132:[function(_dereq_,module,exports){
18290"use strict";
18291
18292Object.defineProperty(exports, "__esModule", {
18293 value: true
18294});
18295exports.default = void 0;
18296
18297var _validate = _interopRequireDefault(_dereq_(131));
18298
18299function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18300
18301function version(uuid) {
18302 if (!(0, _validate.default)(uuid)) {
18303 throw TypeError('Invalid UUID');
18304 }
18305
18306 return parseInt(uuid.substr(14, 1), 16);
18307}
18308
18309var _default = version;
18310exports.default = _default;
18311},{"131":131}],133:[function(_dereq_,module,exports){
18312'use strict';
18313
18314/**
18315 * Stringify/parse functions that don't operate
18316 * recursively, so they avoid call stack exceeded
18317 * errors.
18318 */
18319exports.stringify = function stringify(input) {
18320 var queue = [];
18321 queue.push({obj: input});
18322
18323 var res = '';
18324 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
18325 while ((next = queue.pop())) {
18326 obj = next.obj;
18327 prefix = next.prefix || '';
18328 val = next.val || '';
18329 res += prefix;
18330 if (val) {
18331 res += val;
18332 } else if (typeof obj !== 'object') {
18333 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
18334 } else if (obj === null) {
18335 res += 'null';
18336 } else if (Array.isArray(obj)) {
18337 queue.push({val: ']'});
18338 for (i = obj.length - 1; i >= 0; i--) {
18339 arrayPrefix = i === 0 ? '' : ',';
18340 queue.push({obj: obj[i], prefix: arrayPrefix});
18341 }
18342 queue.push({val: '['});
18343 } else { // object
18344 keys = [];
18345 for (k in obj) {
18346 if (obj.hasOwnProperty(k)) {
18347 keys.push(k);
18348 }
18349 }
18350 queue.push({val: '}'});
18351 for (i = keys.length - 1; i >= 0; i--) {
18352 key = keys[i];
18353 value = obj[key];
18354 objPrefix = (i > 0 ? ',' : '');
18355 objPrefix += JSON.stringify(key) + ':';
18356 queue.push({obj: value, prefix: objPrefix});
18357 }
18358 queue.push({val: '{'});
18359 }
18360 }
18361 return res;
18362};
18363
18364// Convenience function for the parse function.
18365// This pop function is basically copied from
18366// pouchCollate.parseIndexableString
18367function pop(obj, stack, metaStack) {
18368 var lastMetaElement = metaStack[metaStack.length - 1];
18369 if (obj === lastMetaElement.element) {
18370 // popping a meta-element, e.g. an object whose value is another object
18371 metaStack.pop();
18372 lastMetaElement = metaStack[metaStack.length - 1];
18373 }
18374 var element = lastMetaElement.element;
18375 var lastElementIndex = lastMetaElement.index;
18376 if (Array.isArray(element)) {
18377 element.push(obj);
18378 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
18379 var key = stack.pop();
18380 element[key] = obj;
18381 } else {
18382 stack.push(obj); // obj with key only
18383 }
18384}
18385
18386exports.parse = function (str) {
18387 var stack = [];
18388 var metaStack = []; // stack for arrays and objects
18389 var i = 0;
18390 var collationIndex,parsedNum,numChar;
18391 var parsedString,lastCh,numConsecutiveSlashes,ch;
18392 var arrayElement, objElement;
18393 while (true) {
18394 collationIndex = str[i++];
18395 if (collationIndex === '}' ||
18396 collationIndex === ']' ||
18397 typeof collationIndex === 'undefined') {
18398 if (stack.length === 1) {
18399 return stack.pop();
18400 } else {
18401 pop(stack.pop(), stack, metaStack);
18402 continue;
18403 }
18404 }
18405 switch (collationIndex) {
18406 case ' ':
18407 case '\t':
18408 case '\n':
18409 case ':':
18410 case ',':
18411 break;
18412 case 'n':
18413 i += 3; // 'ull'
18414 pop(null, stack, metaStack);
18415 break;
18416 case 't':
18417 i += 3; // 'rue'
18418 pop(true, stack, metaStack);
18419 break;
18420 case 'f':
18421 i += 4; // 'alse'
18422 pop(false, stack, metaStack);
18423 break;
18424 case '0':
18425 case '1':
18426 case '2':
18427 case '3':
18428 case '4':
18429 case '5':
18430 case '6':
18431 case '7':
18432 case '8':
18433 case '9':
18434 case '-':
18435 parsedNum = '';
18436 i--;
18437 while (true) {
18438 numChar = str[i++];
18439 if (/[\d\.\-e\+]/.test(numChar)) {
18440 parsedNum += numChar;
18441 } else {
18442 i--;
18443 break;
18444 }
18445 }
18446 pop(parseFloat(parsedNum), stack, metaStack);
18447 break;
18448 case '"':
18449 parsedString = '';
18450 lastCh = void 0;
18451 numConsecutiveSlashes = 0;
18452 while (true) {
18453 ch = str[i++];
18454 if (ch !== '"' || (lastCh === '\\' &&
18455 numConsecutiveSlashes % 2 === 1)) {
18456 parsedString += ch;
18457 lastCh = ch;
18458 if (lastCh === '\\') {
18459 numConsecutiveSlashes++;
18460 } else {
18461 numConsecutiveSlashes = 0;
18462 }
18463 } else {
18464 break;
18465 }
18466 }
18467 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
18468 break;
18469 case '[':
18470 arrayElement = { element: [], index: stack.length };
18471 stack.push(arrayElement.element);
18472 metaStack.push(arrayElement);
18473 break;
18474 case '{':
18475 objElement = { element: {}, index: stack.length };
18476 stack.push(objElement.element);
18477 metaStack.push(objElement);
18478 break;
18479 default:
18480 throw new Error(
18481 'unexpectedly reached end of input: ' + collationIndex);
18482 }
18483 }
18484};
18485
18486},{}],134:[function(_dereq_,module,exports){
18487module.exports = extend
18488
18489var hasOwnProperty = Object.prototype.hasOwnProperty;
18490
18491function extend() {
18492 var target = {}
18493
18494 for (var i = 0; i < arguments.length; i++) {
18495 var source = arguments[i]
18496
18497 for (var key in source) {
18498 if (hasOwnProperty.call(source, key)) {
18499 target[key] = source[key]
18500 }
18501 }
18502 }
18503
18504 return target
18505}
18506
18507},{}],135:[function(_dereq_,module,exports){
18508module.exports = extend
18509
18510var hasOwnProperty = Object.prototype.hasOwnProperty;
18511
18512function extend(target) {
18513 for (var i = 1; i < arguments.length; i++) {
18514 var source = arguments[i]
18515
18516 for (var key in source) {
18517 if (hasOwnProperty.call(source, key)) {
18518 target[key] = source[key]
18519 }
18520 }
18521 }
18522
18523 return target
18524}
18525
18526},{}],136:[function(_dereq_,module,exports){
18527'use strict';
18528
18529function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
18530
18531var immediate = _interopDefault(_dereq_(24));
18532var uuid = _dereq_(118);
18533var Md5 = _interopDefault(_dereq_(78));
18534var levelup = _interopDefault(_dereq_(54));
18535var ltgt = _interopDefault(_dereq_(56));
18536var EventEmitter = _interopDefault(_dereq_(21));
18537var Codec = _interopDefault(_dereq_(32));
18538var ReadableStreamCore = _interopDefault(_dereq_(76));
18539var inherits = _interopDefault(_dereq_(30));
18540var through2 = _dereq_(112);
18541var getArguments = _interopDefault(_dereq_(1));
18542var Deque = _interopDefault(_dereq_(18));
18543var bufferFrom = _interopDefault(_dereq_(8));
18544var vuvuzela = _interopDefault(_dereq_(133));
18545var memdown = _interopDefault(_dereq_(58));
18546
18547function isBinaryObject(object) {
18548 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
18549 (typeof Blob !== 'undefined' && object instanceof Blob);
18550}
18551
18552function cloneArrayBuffer(buff) {
18553 if (typeof buff.slice === 'function') {
18554 return buff.slice(0);
18555 }
18556 // IE10-11 slice() polyfill
18557 var target = new ArrayBuffer(buff.byteLength);
18558 var targetArray = new Uint8Array(target);
18559 var sourceArray = new Uint8Array(buff);
18560 targetArray.set(sourceArray);
18561 return target;
18562}
18563
18564function cloneBinaryObject(object) {
18565 if (object instanceof ArrayBuffer) {
18566 return cloneArrayBuffer(object);
18567 }
18568 var size = object.size;
18569 var type = object.type;
18570 // Blob
18571 if (typeof object.slice === 'function') {
18572 return object.slice(0, size, type);
18573 }
18574 // PhantomJS slice() replacement
18575 return object.webkitSlice(0, size, type);
18576}
18577
18578// most of this is borrowed from lodash.isPlainObject:
18579// https://github.com/fis-components/lodash.isplainobject/
18580// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
18581
18582var funcToString = Function.prototype.toString;
18583var objectCtorString = funcToString.call(Object);
18584
18585function isPlainObject(value) {
18586 var proto = Object.getPrototypeOf(value);
18587 /* istanbul ignore if */
18588 if (proto === null) { // not sure when this happens, but I guess it can
18589 return true;
18590 }
18591 var Ctor = proto.constructor;
18592 return (typeof Ctor == 'function' &&
18593 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
18594}
18595
18596function clone(object) {
18597 var newObject;
18598 var i;
18599 var len;
18600
18601 if (!object || typeof object !== 'object') {
18602 return object;
18603 }
18604
18605 if (Array.isArray(object)) {
18606 newObject = [];
18607 for (i = 0, len = object.length; i < len; i++) {
18608 newObject[i] = clone(object[i]);
18609 }
18610 return newObject;
18611 }
18612
18613 // special case: to avoid inconsistencies between IndexedDB
18614 // and other backends, we automatically stringify Dates
18615 if (object instanceof Date && isFinite(object)) {
18616 return object.toISOString();
18617 }
18618
18619 if (isBinaryObject(object)) {
18620 return cloneBinaryObject(object);
18621 }
18622
18623 if (!isPlainObject(object)) {
18624 return object; // don't clone objects like Workers
18625 }
18626
18627 newObject = {};
18628 for (i in object) {
18629 /* istanbul ignore else */
18630 if (Object.prototype.hasOwnProperty.call(object, i)) {
18631 var value = clone(object[i]);
18632 if (typeof value !== 'undefined') {
18633 newObject[i] = value;
18634 }
18635 }
18636 }
18637 return newObject;
18638}
18639
18640function mangle(key) {
18641 return '$' + key;
18642}
18643function unmangle(key) {
18644 return key.substring(1);
18645}
18646function Map$1() {
18647 this._store = {};
18648}
18649Map$1.prototype.get = function (key) {
18650 var mangled = mangle(key);
18651 return this._store[mangled];
18652};
18653Map$1.prototype.set = function (key, value) {
18654 var mangled = mangle(key);
18655 this._store[mangled] = value;
18656 return true;
18657};
18658Map$1.prototype.has = function (key) {
18659 var mangled = mangle(key);
18660 return mangled in this._store;
18661};
18662Map$1.prototype.keys = function () {
18663 return Object.keys(this._store).map(k => unmangle(k));
18664};
18665Map$1.prototype["delete"] = function (key) {
18666 var mangled = mangle(key);
18667 var res = mangled in this._store;
18668 delete this._store[mangled];
18669 return res;
18670};
18671Map$1.prototype.forEach = function (cb) {
18672 var keys = Object.keys(this._store);
18673 for (var i = 0, len = keys.length; i < len; i++) {
18674 var key = keys[i];
18675 var value = this._store[key];
18676 key = unmangle(key);
18677 cb(value, key);
18678 }
18679};
18680Object.defineProperty(Map$1.prototype, 'size', {
18681 get: function () {
18682 return Object.keys(this._store).length;
18683 }
18684});
18685
18686function Set$1(array) {
18687 this._store = new Map$1();
18688
18689 // init with an array
18690 if (array && Array.isArray(array)) {
18691 for (var i = 0, len = array.length; i < len; i++) {
18692 this.add(array[i]);
18693 }
18694 }
18695}
18696Set$1.prototype.add = function (key) {
18697 return this._store.set(key, true);
18698};
18699Set$1.prototype.has = function (key) {
18700 return this._store.has(key);
18701};
18702Set$1.prototype.forEach = function (cb) {
18703 this._store.forEach(function (value, key) {
18704 cb(key);
18705 });
18706};
18707Object.defineProperty(Set$1.prototype, 'size', {
18708 get: function () {
18709 return this._store.size;
18710 }
18711});
18712
18713// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
18714// incomplete Map/Set implementations which would otherwise cause our tests to fail.
18715// Notably they fail in IE11 and iOS 8.4, which this prevents.
18716function supportsMapAndSet() {
18717 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
18718 return false;
18719 }
18720 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
18721 return prop && 'get' in prop && Map[Symbol.species] === Map;
18722}
18723
18724// based on https://github.com/montagejs/collections
18725
18726var ExportedSet;
18727var ExportedMap;
18728
18729{
18730 if (supportsMapAndSet()) { // prefer built-in Map/Set
18731 ExportedSet = Set;
18732 ExportedMap = Map;
18733 } else { // fall back to our polyfill
18734 ExportedSet = Set$1;
18735 ExportedMap = Map$1;
18736 }
18737}
18738
18739// like underscore/lodash _.pick()
18740function pick(obj, arr) {
18741 var res = {};
18742 for (var i = 0, len = arr.length; i < len; i++) {
18743 var prop = arr[i];
18744 if (prop in obj) {
18745 res[prop] = obj[prop];
18746 }
18747 }
18748 return res;
18749}
18750
18751var hasLocal;
18752
18753try {
18754 localStorage.setItem('_pouch_check_localstorage', 1);
18755 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
18756} catch (e) {
18757 hasLocal = false;
18758}
18759
18760function hasLocalStorage() {
18761 return hasLocal;
18762}
18763
18764// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
18765
18766inherits(Changes, EventEmitter);
18767
18768/* istanbul ignore next */
18769function attachBrowserEvents(self) {
18770 if (hasLocalStorage()) {
18771 addEventListener("storage", function (e) {
18772 self.emit(e.key);
18773 });
18774 }
18775}
18776
18777function Changes() {
18778 EventEmitter.call(this);
18779 this._listeners = {};
18780
18781 attachBrowserEvents(this);
18782}
18783Changes.prototype.addListener = function (dbName, id, db, opts) {
18784 /* istanbul ignore if */
18785 if (this._listeners[id]) {
18786 return;
18787 }
18788 var self = this;
18789 var inprogress = false;
18790 function eventFunction() {
18791 /* istanbul ignore if */
18792 if (!self._listeners[id]) {
18793 return;
18794 }
18795 if (inprogress) {
18796 inprogress = 'waiting';
18797 return;
18798 }
18799 inprogress = true;
18800 var changesOpts = pick(opts, [
18801 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
18802 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
18803 ]);
18804
18805 /* istanbul ignore next */
18806 function onError() {
18807 inprogress = false;
18808 }
18809
18810 db.changes(changesOpts).on('change', function (c) {
18811 if (c.seq > opts.since && !opts.cancelled) {
18812 opts.since = c.seq;
18813 opts.onChange(c);
18814 }
18815 }).on('complete', function () {
18816 if (inprogress === 'waiting') {
18817 immediate(eventFunction);
18818 }
18819 inprogress = false;
18820 }).on('error', onError);
18821 }
18822 this._listeners[id] = eventFunction;
18823 this.on(dbName, eventFunction);
18824};
18825
18826Changes.prototype.removeListener = function (dbName, id) {
18827 /* istanbul ignore if */
18828 if (!(id in this._listeners)) {
18829 return;
18830 }
18831 EventEmitter.prototype.removeListener.call(this, dbName,
18832 this._listeners[id]);
18833 delete this._listeners[id];
18834};
18835
18836
18837/* istanbul ignore next */
18838Changes.prototype.notifyLocalWindows = function (dbName) {
18839 //do a useless change on a storage thing
18840 //in order to get other windows's listeners to activate
18841 if (hasLocalStorage()) {
18842 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
18843 }
18844};
18845
18846Changes.prototype.notify = function (dbName) {
18847 this.emit(dbName);
18848 this.notifyLocalWindows(dbName);
18849};
18850
18851function guardedConsole(method) {
18852 /* istanbul ignore else */
18853 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
18854 var args = Array.prototype.slice.call(arguments, 1);
18855 console[method].apply(console, args);
18856 }
18857}
18858
18859var assign;
18860{
18861 if (typeof Object.assign === 'function') {
18862 assign = Object.assign;
18863 } else {
18864 // lite Object.assign polyfill based on
18865 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
18866 assign = function (target) {
18867 var to = Object(target);
18868
18869 for (var index = 1; index < arguments.length; index++) {
18870 var nextSource = arguments[index];
18871
18872 if (nextSource != null) { // Skip over if undefined or null
18873 for (var nextKey in nextSource) {
18874 // Avoid bugs when hasOwnProperty is shadowed
18875 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
18876 to[nextKey] = nextSource[nextKey];
18877 }
18878 }
18879 }
18880 }
18881 return to;
18882 };
18883 }
18884}
18885
18886var $inject_Object_assign = assign;
18887
18888inherits(PouchError, Error);
18889
18890function PouchError(status, error, reason) {
18891 Error.call(this, reason);
18892 this.status = status;
18893 this.name = error;
18894 this.message = reason;
18895 this.error = true;
18896}
18897
18898PouchError.prototype.toString = function () {
18899 return JSON.stringify({
18900 status: this.status,
18901 name: this.name,
18902 message: this.message,
18903 reason: this.reason
18904 });
18905};
18906
18907var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
18908var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
18909var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
18910var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
18911var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
18912var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
18913var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
18914var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
18915var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
18916var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
18917var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
18918var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
18919var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
18920var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
18921var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
18922var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
18923var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
18924var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
18925var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
18926var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
18927var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
18928var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
18929var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
18930var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
18931
18932function createError(error, reason) {
18933 function CustomPouchError(reason) {
18934 // inherit error properties from our parent error manually
18935 // so as to allow proper JSON parsing.
18936 /* jshint ignore:start */
18937 var names = Object.getOwnPropertyNames(error);
18938 for (var i = 0, len = names.length; i < len; i++) {
18939 if (typeof error[names[i]] !== 'function') {
18940 this[names[i]] = error[names[i]];
18941 }
18942 }
18943
18944 if (this.stack === undefined) {
18945 this.stack = (new Error()).stack;
18946 }
18947
18948 /* jshint ignore:end */
18949 if (reason !== undefined) {
18950 this.reason = reason;
18951 }
18952 }
18953 CustomPouchError.prototype = PouchError.prototype;
18954 return new CustomPouchError(reason);
18955}
18956
18957function tryFilter(filter, doc, req) {
18958 try {
18959 return !filter(doc, req);
18960 } catch (err) {
18961 var msg = 'Filter function threw: ' + err.toString();
18962 return createError(BAD_REQUEST, msg);
18963 }
18964}
18965
18966function filterChange(opts) {
18967 var req = {};
18968 var hasFilter = opts.filter && typeof opts.filter === 'function';
18969 req.query = opts.query_params;
18970
18971 return function filter(change) {
18972 if (!change.doc) {
18973 // CSG sends events on the changes feed that don't have documents,
18974 // this hack makes a whole lot of existing code robust.
18975 change.doc = {};
18976 }
18977
18978 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
18979
18980 if (typeof filterReturn === 'object') {
18981 return filterReturn;
18982 }
18983
18984 if (filterReturn) {
18985 return false;
18986 }
18987
18988 if (!opts.include_docs) {
18989 delete change.doc;
18990 } else if (!opts.attachments) {
18991 for (var att in change.doc._attachments) {
18992 /* istanbul ignore else */
18993 if (Object.prototype.hasOwnProperty.call(change.doc._attachments, att)) {
18994 change.doc._attachments[att].stub = true;
18995 }
18996 }
18997 }
18998 return true;
18999 };
19000}
19001
19002// shim for Function.prototype.name,
19003// for browsers that don't support it like IE
19004
19005/* istanbul ignore next */
19006function f() {}
19007
19008var hasName = f.name;
19009var res;
19010
19011// We dont run coverage in IE
19012/* istanbul ignore else */
19013if (hasName) {
19014 res = function (fun) {
19015 return fun.name;
19016 };
19017} else {
19018 res = function (fun) {
19019 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
19020 if (match && match[1]) {
19021 return match[1];
19022 }
19023 else {
19024 return '';
19025 }
19026 };
19027}
19028
19029var functionName = res;
19030
19031// Determine id an ID is valid
19032// - invalid IDs begin with an underescore that does not begin '_design' or
19033// '_local'
19034// - any other string value is a valid id
19035// Returns the specific error object for each case
19036function invalidIdError(id) {
19037 var err;
19038 if (!id) {
19039 err = createError(MISSING_ID);
19040 } else if (typeof id !== 'string') {
19041 err = createError(INVALID_ID);
19042 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
19043 err = createError(RESERVED_ID);
19044 }
19045 if (err) {
19046 throw err;
19047 }
19048}
19049
19050// Checks if a PouchDB object is "remote" or not. This is
19051
19052// originally parseUri 1.2.2, now patched by us
19053
19054// Based on https://github.com/alexdavid/scope-eval v0.0.3
19055
19056var thisAtob = function (str) {
19057 return atob(str);
19058};
19059
19060var thisBtoa = function (str) {
19061 return btoa(str);
19062};
19063
19064// Abstracts constructing a Blob object, so it also works in older
19065// browsers that don't support the native Blob constructor (e.g.
19066// old QtWebKit versions, Android < 4.4).
19067function createBlob(parts, properties) {
19068 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
19069 parts = parts || [];
19070 properties = properties || {};
19071 try {
19072 return new Blob(parts, properties);
19073 } catch (e) {
19074 if (e.name !== "TypeError") {
19075 throw e;
19076 }
19077 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
19078 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
19079 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
19080 WebKitBlobBuilder;
19081 var builder = new Builder();
19082 for (var i = 0; i < parts.length; i += 1) {
19083 builder.append(parts[i]);
19084 }
19085 return builder.getBlob(properties.type);
19086 }
19087}
19088
19089// From http://stackoverflow.com/questions/14967647/ (continues on next line)
19090// encode-decode-image-with-base64-breaks-image (2013-04-21)
19091function binaryStringToArrayBuffer(bin) {
19092 var length = bin.length;
19093 var buf = new ArrayBuffer(length);
19094 var arr = new Uint8Array(buf);
19095 for (var i = 0; i < length; i++) {
19096 arr[i] = bin.charCodeAt(i);
19097 }
19098 return buf;
19099}
19100
19101function binStringToBluffer(binString, type) {
19102 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
19103}
19104
19105//Can't find original post, but this is close
19106//http://stackoverflow.com/questions/6965107/ (continues on next line)
19107//converting-between-strings-and-arraybuffers
19108function arrayBufferToBinaryString(buffer) {
19109 var binary = '';
19110 var bytes = new Uint8Array(buffer);
19111 var length = bytes.byteLength;
19112 for (var i = 0; i < length; i++) {
19113 binary += String.fromCharCode(bytes[i]);
19114 }
19115 return binary;
19116}
19117
19118// shim for browsers that don't support it
19119function readAsBinaryString(blob, callback) {
19120 var reader = new FileReader();
19121 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
19122 reader.onloadend = function (e) {
19123 var result = e.target.result || '';
19124 if (hasBinaryString) {
19125 return callback(result);
19126 }
19127 callback(arrayBufferToBinaryString(result));
19128 };
19129 if (hasBinaryString) {
19130 reader.readAsBinaryString(blob);
19131 } else {
19132 reader.readAsArrayBuffer(blob);
19133 }
19134}
19135
19136// simplified API. universal browser support is assumed
19137function readAsArrayBuffer(blob, callback) {
19138 var reader = new FileReader();
19139 reader.onloadend = function (e) {
19140 var result = e.target.result || new ArrayBuffer(0);
19141 callback(result);
19142 };
19143 reader.readAsArrayBuffer(blob);
19144}
19145
19146// this is not used in the browser
19147
19148var setImmediateShim = self.setImmediate || self.setTimeout;
19149var MD5_CHUNK_SIZE = 32768;
19150
19151function rawToBase64(raw) {
19152 return thisBtoa(raw);
19153}
19154
19155function sliceBlob(blob, start, end) {
19156 if (blob.webkitSlice) {
19157 return blob.webkitSlice(start, end);
19158 }
19159 return blob.slice(start, end);
19160}
19161
19162function appendBlob(buffer, blob, start, end, callback) {
19163 if (start > 0 || end < blob.size) {
19164 // only slice blob if we really need to
19165 blob = sliceBlob(blob, start, end);
19166 }
19167 readAsArrayBuffer(blob, function (arrayBuffer) {
19168 buffer.append(arrayBuffer);
19169 callback();
19170 });
19171}
19172
19173function appendString(buffer, string, start, end, callback) {
19174 if (start > 0 || end < string.length) {
19175 // only create a substring if we really need to
19176 string = string.substring(start, end);
19177 }
19178 buffer.appendBinary(string);
19179 callback();
19180}
19181
19182function binaryMd5(data, callback) {
19183 var inputIsString = typeof data === 'string';
19184 var len = inputIsString ? data.length : data.size;
19185 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
19186 var chunks = Math.ceil(len / chunkSize);
19187 var currentChunk = 0;
19188 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
19189
19190 var append = inputIsString ? appendString : appendBlob;
19191
19192 function next() {
19193 setImmediateShim(loadNextChunk);
19194 }
19195
19196 function done() {
19197 var raw = buffer.end(true);
19198 var base64 = rawToBase64(raw);
19199 callback(base64);
19200 buffer.destroy();
19201 }
19202
19203 function loadNextChunk() {
19204 var start = currentChunk * chunkSize;
19205 var end = start + chunkSize;
19206 currentChunk++;
19207 if (currentChunk < chunks) {
19208 append(buffer, data, start, end, next);
19209 } else {
19210 append(buffer, data, start, end, done);
19211 }
19212 }
19213 loadNextChunk();
19214}
19215
19216function stringMd5(string) {
19217 return Md5.hash(string);
19218}
19219
19220/**
19221 * Creates a new revision string that does NOT include the revision height
19222 * For example '56649f1b0506c6ca9fda0746eb0cacdf'
19223 */
19224function rev$$1(doc, deterministic_revs) {
19225 if (!deterministic_revs) {
19226 return uuid.v4().replace(/-/g, '').toLowerCase();
19227 }
19228
19229 var mutateableDoc = $inject_Object_assign({}, doc);
19230 delete mutateableDoc._rev_tree;
19231 return stringMd5(JSON.stringify(mutateableDoc));
19232}
19233
19234var uuid$1 = uuid.v4; // mimic old import, only v4 is ever used elsewhere
19235
19236function isFunction(f) {
19237 return 'function' === typeof f;
19238}
19239
19240function getPrefix(db) {
19241 if (isFunction(db.prefix)) {
19242 return db.prefix();
19243 }
19244 return db;
19245}
19246
19247function clone$1(_obj) {
19248 var obj = {};
19249 for (var k in _obj) {
19250 obj[k] = _obj[k];
19251 }
19252 return obj;
19253}
19254
19255function nut(db, precodec, codec) {
19256 function encodePrefix(prefix, key, opts1, opts2) {
19257 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
19258 }
19259
19260 function addEncodings(op, prefix) {
19261 if (prefix && prefix.options) {
19262 op.keyEncoding =
19263 op.keyEncoding || prefix.options.keyEncoding;
19264 op.valueEncoding =
19265 op.valueEncoding || prefix.options.valueEncoding;
19266 }
19267 return op;
19268 }
19269
19270 db.open(function () { /* no-op */});
19271
19272 return {
19273 apply: function (ops, opts, cb) {
19274 opts = opts || {};
19275
19276 var batch = [];
19277 var i = -1;
19278 var len = ops.length;
19279
19280 while (++i < len) {
19281 var op = ops[i];
19282 addEncodings(op, op.prefix);
19283 op.prefix = getPrefix(op.prefix);
19284 batch.push({
19285 key: encodePrefix(op.prefix, op.key, opts, op),
19286 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
19287 type: op.type
19288 });
19289 }
19290 db.db.batch(batch, opts, cb);
19291 },
19292 get: function (key, prefix, opts, cb) {
19293 opts.asBuffer = codec.valueAsBuffer(opts);
19294 return db.db.get(
19295 encodePrefix(prefix, key, opts),
19296 opts,
19297 function (err, value) {
19298 if (err) {
19299 cb(err);
19300 } else {
19301 cb(null, codec.decodeValue(value, opts));
19302 }
19303 }
19304 );
19305 },
19306 createDecoder: function (opts) {
19307 return function (key, value) {
19308 return {
19309 key: codec.decodeKey(precodec.decode(key)[1], opts),
19310 value: codec.decodeValue(value, opts)
19311 };
19312 };
19313 },
19314 isClosed: function isClosed() {
19315 return db.isClosed();
19316 },
19317 close: function close(cb) {
19318 return db.close(cb);
19319 },
19320 iterator: function (_opts) {
19321 var opts = clone$1(_opts || {});
19322 var prefix = _opts.prefix || [];
19323
19324 function encodeKey(key) {
19325 return encodePrefix(prefix, key, opts, {});
19326 }
19327
19328 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
19329
19330 // if these legacy values are in the options, remove them
19331
19332 opts.prefix = null;
19333
19334 //************************************************
19335 //hard coded defaults, for now...
19336 //TODO: pull defaults and encoding out of levelup.
19337 opts.keyAsBuffer = opts.valueAsBuffer = false;
19338 //************************************************
19339
19340
19341 //this is vital, otherwise limit: undefined will
19342 //create an empty stream.
19343 /* istanbul ignore next */
19344 if ('number' !== typeof opts.limit) {
19345 opts.limit = -1;
19346 }
19347
19348 opts.keyAsBuffer = precodec.buffer;
19349 opts.valueAsBuffer = codec.valueAsBuffer(opts);
19350
19351 function wrapIterator(iterator) {
19352 return {
19353 next: function (cb) {
19354 return iterator.next(cb);
19355 },
19356 end: function (cb) {
19357 iterator.end(cb);
19358 }
19359 };
19360 }
19361
19362 return wrapIterator(db.db.iterator(opts));
19363 }
19364 };
19365}
19366
19367function NotFoundError() {
19368 Error.call(this);
19369}
19370
19371inherits(NotFoundError, Error);
19372
19373NotFoundError.prototype.name = 'NotFoundError';
19374
19375var EventEmitter$1 = EventEmitter.EventEmitter;
19376var version = "6.5.4";
19377
19378var NOT_FOUND_ERROR = new NotFoundError();
19379
19380var sublevel = function (nut, prefix, createStream, options) {
19381 var emitter = new EventEmitter$1();
19382 emitter.sublevels = {};
19383 emitter.options = options;
19384
19385 emitter.version = version;
19386
19387 emitter.methods = {};
19388 prefix = prefix || [];
19389
19390 function mergeOpts(opts) {
19391 var o = {};
19392 var k;
19393 if (options) {
19394 for (k in options) {
19395 if (typeof options[k] !== 'undefined') {
19396 o[k] = options[k];
19397 }
19398 }
19399 }
19400 if (opts) {
19401 for (k in opts) {
19402 if (typeof opts[k] !== 'undefined') {
19403 o[k] = opts[k];
19404 }
19405 }
19406 }
19407 return o;
19408 }
19409
19410 emitter.put = function (key, value, opts, cb) {
19411 if ('function' === typeof opts) {
19412 cb = opts;
19413 opts = {};
19414 }
19415
19416 nut.apply([{
19417 key: key, value: value,
19418 prefix: prefix.slice(), type: 'put'
19419 }], mergeOpts(opts), function (err) {
19420 /* istanbul ignore next */
19421 if (err) {
19422 return cb(err);
19423 }
19424 emitter.emit('put', key, value);
19425 cb(null);
19426 });
19427 };
19428
19429 emitter.prefix = function () {
19430 return prefix.slice();
19431 };
19432
19433 emitter.batch = function (ops, opts, cb) {
19434 if ('function' === typeof opts) {
19435 cb = opts;
19436 opts = {};
19437 }
19438
19439 ops = ops.map(function (op) {
19440 return {
19441 key: op.key,
19442 value: op.value,
19443 prefix: op.prefix || prefix,
19444 keyEncoding: op.keyEncoding, // *
19445 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
19446 type: op.type
19447 };
19448 });
19449
19450 nut.apply(ops, mergeOpts(opts), function (err) {
19451 /* istanbul ignore next */
19452 if (err) {
19453 return cb(err);
19454 }
19455 emitter.emit('batch', ops);
19456 cb(null);
19457 });
19458 };
19459
19460 emitter.get = function (key, opts, cb) {
19461 /* istanbul ignore else */
19462 if ('function' === typeof opts) {
19463 cb = opts;
19464 opts = {};
19465 }
19466 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
19467 if (err) {
19468 cb(NOT_FOUND_ERROR);
19469 } else {
19470 cb(null, value);
19471 }
19472 });
19473 };
19474
19475 emitter.sublevel = function (name, opts) {
19476 return emitter.sublevels[name] =
19477 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
19478 };
19479
19480 emitter.readStream = emitter.createReadStream = function (opts) {
19481 opts = mergeOpts(opts);
19482 opts.prefix = prefix;
19483 var stream;
19484 var it = nut.iterator(opts);
19485
19486 stream = createStream(opts, nut.createDecoder(opts));
19487 stream.setIterator(it);
19488
19489 return stream;
19490 };
19491
19492 emitter.close = function (cb) {
19493 nut.close(cb);
19494 };
19495
19496 emitter.isOpen = nut.isOpen;
19497 emitter.isClosed = nut.isClosed;
19498
19499 return emitter;
19500};
19501
19502/* Copyright (c) 2012-2014 LevelUP contributors
19503 * See list at <https://github.com/rvagg/node-levelup#contributing>
19504 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
19505 */
19506
19507var Readable = ReadableStreamCore.Readable;
19508
19509function ReadStream(options, makeData) {
19510 if (!(this instanceof ReadStream)) {
19511 return new ReadStream(options, makeData);
19512 }
19513
19514 Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });
19515
19516 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
19517
19518 this._waiting = false;
19519 this._options = options;
19520 this._makeData = makeData;
19521}
19522
19523inherits(ReadStream, Readable);
19524
19525ReadStream.prototype.setIterator = function (it) {
19526 this._iterator = it;
19527 /* istanbul ignore if */
19528 if (this._destroyed) {
19529 return it.end(function () {});
19530 }
19531 /* istanbul ignore if */
19532 if (this._waiting) {
19533 this._waiting = false;
19534 return this._read();
19535 }
19536 return this;
19537};
19538
19539ReadStream.prototype._read = function read() {
19540 var self = this;
19541 /* istanbul ignore if */
19542 if (self._destroyed) {
19543 return;
19544 }
19545 /* istanbul ignore if */
19546 if (!self._iterator) {
19547 return this._waiting = true;
19548 }
19549
19550 self._iterator.next(function (err, key, value) {
19551 if (err || (key === undefined && value === undefined)) {
19552 if (!err && !self._destroyed) {
19553 self.push(null);
19554 }
19555 return self._cleanup(err);
19556 }
19557
19558
19559 value = self._makeData(key, value);
19560 if (!self._destroyed) {
19561 self.push(value);
19562 }
19563 });
19564};
19565
19566ReadStream.prototype._cleanup = function (err) {
19567 if (this._destroyed) {
19568 return;
19569 }
19570
19571 this._destroyed = true;
19572
19573 var self = this;
19574 /* istanbul ignore if */
19575 if (err && err.message !== 'iterator has ended') {
19576 self.emit('error', err);
19577 }
19578
19579 /* istanbul ignore else */
19580 if (self._iterator) {
19581 self._iterator.end(function () {
19582 self._iterator = null;
19583 self.emit('close');
19584 });
19585 } else {
19586 self.emit('close');
19587 }
19588};
19589
19590ReadStream.prototype.destroy = function () {
19591 this._cleanup();
19592};
19593
19594var precodec = {
19595 encode: function (decodedKey) {
19596 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
19597 },
19598 decode: function (encodedKeyAsBuffer) {
19599 var str = encodedKeyAsBuffer.toString();
19600 var idx = str.indexOf('\xff', 1);
19601 return [str.substring(1, idx), str.substring(idx + 1)];
19602 },
19603 lowerBound: '\x00',
19604 upperBound: '\xff'
19605};
19606
19607var codec = new Codec();
19608
19609function sublevelPouch(db) {
19610 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
19611}
19612
19613function allDocsKeysQuery(api, opts) {
19614 var keys = opts.keys;
19615 var finalResults = {
19616 offset: opts.skip
19617 };
19618 return Promise.all(keys.map(function (key) {
19619 var subOpts = $inject_Object_assign({key: key, deleted: 'ok'}, opts);
19620 ['limit', 'skip', 'keys'].forEach(function (optKey) {
19621 delete subOpts[optKey];
19622 });
19623 return new Promise(function (resolve, reject) {
19624 api._allDocs(subOpts, function (err, res) {
19625 /* istanbul ignore if */
19626 if (err) {
19627 return reject(err);
19628 }
19629 /* istanbul ignore if */
19630 if (opts.update_seq && res.update_seq !== undefined) {
19631 finalResults.update_seq = res.update_seq;
19632 }
19633 finalResults.total_rows = res.total_rows;
19634 resolve(res.rows[0] || {key: key, error: 'not_found'});
19635 });
19636 });
19637 })).then(function (results) {
19638 finalResults.rows = results;
19639 return finalResults;
19640 });
19641}
19642
19643function toObject(array) {
19644 return array.reduce(function (obj, item) {
19645 obj[item] = true;
19646 return obj;
19647 }, {});
19648}
19649// List of top level reserved words for doc
19650var reservedWords = toObject([
19651 '_id',
19652 '_rev',
19653 '_access',
19654 '_attachments',
19655 '_deleted',
19656 '_revisions',
19657 '_revs_info',
19658 '_conflicts',
19659 '_deleted_conflicts',
19660 '_local_seq',
19661 '_rev_tree',
19662 // replication documents
19663 '_replication_id',
19664 '_replication_state',
19665 '_replication_state_time',
19666 '_replication_state_reason',
19667 '_replication_stats',
19668 // Specific to Couchbase Sync Gateway
19669 '_removed'
19670]);
19671
19672// List of reserved words that should end up in the document
19673var dataWords = toObject([
19674 '_access',
19675 '_attachments',
19676 // replication documents
19677 '_replication_id',
19678 '_replication_state',
19679 '_replication_state_time',
19680 '_replication_state_reason',
19681 '_replication_stats'
19682]);
19683
19684function parseRevisionInfo(rev) {
19685 if (!/^\d+-/.test(rev)) {
19686 return createError(INVALID_REV);
19687 }
19688 var idx = rev.indexOf('-');
19689 var left = rev.substring(0, idx);
19690 var right = rev.substring(idx + 1);
19691 return {
19692 prefix: parseInt(left, 10),
19693 id: right
19694 };
19695}
19696
19697function makeRevTreeFromRevisions(revisions, opts) {
19698 var pos = revisions.start - revisions.ids.length + 1;
19699
19700 var revisionIds = revisions.ids;
19701 var ids = [revisionIds[0], opts, []];
19702
19703 for (var i = 1, len = revisionIds.length; i < len; i++) {
19704 ids = [revisionIds[i], {status: 'missing'}, [ids]];
19705 }
19706
19707 return [{
19708 pos: pos,
19709 ids: ids
19710 }];
19711}
19712
19713// Preprocess documents, parse their revisions, assign an id and a
19714// revision for new writes that are missing them, etc
19715function parseDoc(doc, newEdits, dbOpts) {
19716 if (!dbOpts) {
19717 dbOpts = {
19718 deterministic_revs: true
19719 };
19720 }
19721
19722 var nRevNum;
19723 var newRevId;
19724 var revInfo;
19725 var opts = {status: 'available'};
19726 if (doc._deleted) {
19727 opts.deleted = true;
19728 }
19729
19730 if (newEdits) {
19731 if (!doc._id) {
19732 doc._id = uuid$1();
19733 }
19734 newRevId = rev$$1(doc, dbOpts.deterministic_revs);
19735 if (doc._rev) {
19736 revInfo = parseRevisionInfo(doc._rev);
19737 if (revInfo.error) {
19738 return revInfo;
19739 }
19740 doc._rev_tree = [{
19741 pos: revInfo.prefix,
19742 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
19743 }];
19744 nRevNum = revInfo.prefix + 1;
19745 } else {
19746 doc._rev_tree = [{
19747 pos: 1,
19748 ids : [newRevId, opts, []]
19749 }];
19750 nRevNum = 1;
19751 }
19752 } else {
19753 if (doc._revisions) {
19754 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
19755 nRevNum = doc._revisions.start;
19756 newRevId = doc._revisions.ids[0];
19757 }
19758 if (!doc._rev_tree) {
19759 revInfo = parseRevisionInfo(doc._rev);
19760 if (revInfo.error) {
19761 return revInfo;
19762 }
19763 nRevNum = revInfo.prefix;
19764 newRevId = revInfo.id;
19765 doc._rev_tree = [{
19766 pos: nRevNum,
19767 ids: [newRevId, opts, []]
19768 }];
19769 }
19770 }
19771
19772 invalidIdError(doc._id);
19773
19774 doc._rev = nRevNum + '-' + newRevId;
19775
19776 var result = {metadata : {}, data : {}};
19777 for (var key in doc) {
19778 /* istanbul ignore else */
19779 if (Object.prototype.hasOwnProperty.call(doc, key)) {
19780 var specialKey = key[0] === '_';
19781 if (specialKey && !reservedWords[key]) {
19782 var error = createError(DOC_VALIDATION, key);
19783 error.message = DOC_VALIDATION.message + ': ' + key;
19784 throw error;
19785 } else if (specialKey && !dataWords[key]) {
19786 result.metadata[key.slice(1)] = doc[key];
19787 } else {
19788 result.data[key] = doc[key];
19789 }
19790 }
19791 }
19792 return result;
19793}
19794
19795// We fetch all leafs of the revision tree, and sort them based on tree length
19796// and whether they were deleted, undeleted documents with the longest revision
19797// tree (most edits) win
19798// The final sort algorithm is slightly documented in a sidebar here:
19799// http://guide.couchdb.org/draft/conflicts.html
19800function winningRev(metadata) {
19801 var winningId;
19802 var winningPos;
19803 var winningDeleted;
19804 var toVisit = metadata.rev_tree.slice();
19805 var node;
19806 while ((node = toVisit.pop())) {
19807 var tree = node.ids;
19808 var branches = tree[2];
19809 var pos = node.pos;
19810 if (branches.length) { // non-leaf
19811 for (var i = 0, len = branches.length; i < len; i++) {
19812 toVisit.push({pos: pos + 1, ids: branches[i]});
19813 }
19814 continue;
19815 }
19816 var deleted = !!tree[1].deleted;
19817 var id = tree[0];
19818 // sort by deleted, then pos, then id
19819 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
19820 winningPos !== pos ? winningPos < pos : winningId < id)) {
19821 winningId = id;
19822 winningPos = pos;
19823 winningDeleted = deleted;
19824 }
19825 }
19826
19827 return winningPos + '-' + winningId;
19828}
19829
19830// Pretty much all below can be combined into a higher order function to
19831// traverse revisions
19832// The return value from the callback will be passed as context to all
19833// children of that node
19834function traverseRevTree(revs, callback) {
19835 var toVisit = revs.slice();
19836
19837 var node;
19838 while ((node = toVisit.pop())) {
19839 var pos = node.pos;
19840 var tree = node.ids;
19841 var branches = tree[2];
19842 var newCtx =
19843 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
19844 for (var i = 0, len = branches.length; i < len; i++) {
19845 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
19846 }
19847 }
19848}
19849
19850function sortByPos(a, b) {
19851 return a.pos - b.pos;
19852}
19853
19854function collectLeaves(revs) {
19855 var leaves = [];
19856 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
19857 if (isLeaf) {
19858 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
19859 }
19860 });
19861 leaves.sort(sortByPos).reverse();
19862 for (var i = 0, len = leaves.length; i < len; i++) {
19863 delete leaves[i].pos;
19864 }
19865 return leaves;
19866}
19867
19868// returns revs of all conflicts that is leaves such that
19869// 1. are not deleted and
19870// 2. are different than winning revision
19871function collectConflicts(metadata) {
19872 var win = winningRev(metadata);
19873 var leaves = collectLeaves(metadata.rev_tree);
19874 var conflicts = [];
19875 for (var i = 0, len = leaves.length; i < len; i++) {
19876 var leaf = leaves[i];
19877 if (leaf.rev !== win && !leaf.opts.deleted) {
19878 conflicts.push(leaf.rev);
19879 }
19880 }
19881 return conflicts;
19882}
19883
19884// compact a tree by marking its non-leafs as missing,
19885// and return a list of revs to delete
19886function compactTree(metadata) {
19887 var revs = [];
19888 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
19889 revHash, ctx, opts) {
19890 if (opts.status === 'available' && !isLeaf) {
19891 revs.push(pos + '-' + revHash);
19892 opts.status = 'missing';
19893 }
19894 });
19895 return revs;
19896}
19897
19898// build up a list of all the paths to the leafs in this revision tree
19899function rootToLeaf(revs) {
19900 var paths = [];
19901 var toVisit = revs.slice();
19902 var node;
19903 while ((node = toVisit.pop())) {
19904 var pos = node.pos;
19905 var tree = node.ids;
19906 var id = tree[0];
19907 var opts = tree[1];
19908 var branches = tree[2];
19909 var isLeaf = branches.length === 0;
19910
19911 var history = node.history ? node.history.slice() : [];
19912 history.push({id: id, opts: opts});
19913 if (isLeaf) {
19914 paths.push({pos: (pos + 1 - history.length), ids: history});
19915 }
19916 for (var i = 0, len = branches.length; i < len; i++) {
19917 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
19918 }
19919 }
19920 return paths.reverse();
19921}
19922
19923// for a better overview of what this is doing, read:
19924
19925function sortByPos$1(a, b) {
19926 return a.pos - b.pos;
19927}
19928
19929// classic binary search
19930function binarySearch(arr, item, comparator) {
19931 var low = 0;
19932 var high = arr.length;
19933 var mid;
19934 while (low < high) {
19935 mid = (low + high) >>> 1;
19936 if (comparator(arr[mid], item) < 0) {
19937 low = mid + 1;
19938 } else {
19939 high = mid;
19940 }
19941 }
19942 return low;
19943}
19944
19945// assuming the arr is sorted, insert the item in the proper place
19946function insertSorted(arr, item, comparator) {
19947 var idx = binarySearch(arr, item, comparator);
19948 arr.splice(idx, 0, item);
19949}
19950
19951// Turn a path as a flat array into a tree with a single branch.
19952// If any should be stemmed from the beginning of the array, that's passed
19953// in as the second argument
19954function pathToTree(path, numStemmed) {
19955 var root;
19956 var leaf;
19957 for (var i = numStemmed, len = path.length; i < len; i++) {
19958 var node = path[i];
19959 var currentLeaf = [node.id, node.opts, []];
19960 if (leaf) {
19961 leaf[2].push(currentLeaf);
19962 leaf = currentLeaf;
19963 } else {
19964 root = leaf = currentLeaf;
19965 }
19966 }
19967 return root;
19968}
19969
19970// compare the IDs of two trees
19971function compareTree(a, b) {
19972 return a[0] < b[0] ? -1 : 1;
19973}
19974
19975// Merge two trees together
19976// The roots of tree1 and tree2 must be the same revision
19977function mergeTree(in_tree1, in_tree2) {
19978 var queue = [{tree1: in_tree1, tree2: in_tree2}];
19979 var conflicts = false;
19980 while (queue.length > 0) {
19981 var item = queue.pop();
19982 var tree1 = item.tree1;
19983 var tree2 = item.tree2;
19984
19985 if (tree1[1].status || tree2[1].status) {
19986 tree1[1].status =
19987 (tree1[1].status === 'available' ||
19988 tree2[1].status === 'available') ? 'available' : 'missing';
19989 }
19990
19991 for (var i = 0; i < tree2[2].length; i++) {
19992 if (!tree1[2][0]) {
19993 conflicts = 'new_leaf';
19994 tree1[2][0] = tree2[2][i];
19995 continue;
19996 }
19997
19998 var merged = false;
19999 for (var j = 0; j < tree1[2].length; j++) {
20000 if (tree1[2][j][0] === tree2[2][i][0]) {
20001 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
20002 merged = true;
20003 }
20004 }
20005 if (!merged) {
20006 conflicts = 'new_branch';
20007 insertSorted(tree1[2], tree2[2][i], compareTree);
20008 }
20009 }
20010 }
20011 return {conflicts: conflicts, tree: in_tree1};
20012}
20013
20014function doMerge(tree, path, dontExpand) {
20015 var restree = [];
20016 var conflicts = false;
20017 var merged = false;
20018 var res;
20019
20020 if (!tree.length) {
20021 return {tree: [path], conflicts: 'new_leaf'};
20022 }
20023
20024 for (var i = 0, len = tree.length; i < len; i++) {
20025 var branch = tree[i];
20026 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
20027 // Paths start at the same position and have the same root, so they need
20028 // merged
20029 res = mergeTree(branch.ids, path.ids);
20030 restree.push({pos: branch.pos, ids: res.tree});
20031 conflicts = conflicts || res.conflicts;
20032 merged = true;
20033 } else if (dontExpand !== true) {
20034 // The paths start at a different position, take the earliest path and
20035 // traverse up until it as at the same point from root as the path we
20036 // want to merge. If the keys match we return the longer path with the
20037 // other merged After stemming we dont want to expand the trees
20038
20039 var t1 = branch.pos < path.pos ? branch : path;
20040 var t2 = branch.pos < path.pos ? path : branch;
20041 var diff = t2.pos - t1.pos;
20042
20043 var candidateParents = [];
20044
20045 var trees = [];
20046 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
20047 while (trees.length > 0) {
20048 var item = trees.pop();
20049 if (item.diff === 0) {
20050 if (item.ids[0] === t2.ids[0]) {
20051 candidateParents.push(item);
20052 }
20053 continue;
20054 }
20055 var elements = item.ids[2];
20056 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
20057 trees.push({
20058 ids: elements[j],
20059 diff: item.diff - 1,
20060 parent: item.ids,
20061 parentIdx: j
20062 });
20063 }
20064 }
20065
20066 var el = candidateParents[0];
20067
20068 if (!el) {
20069 restree.push(branch);
20070 } else {
20071 res = mergeTree(el.ids, t2.ids);
20072 el.parent[2][el.parentIdx] = res.tree;
20073 restree.push({pos: t1.pos, ids: t1.ids});
20074 conflicts = conflicts || res.conflicts;
20075 merged = true;
20076 }
20077 } else {
20078 restree.push(branch);
20079 }
20080 }
20081
20082 // We didnt find
20083 if (!merged) {
20084 restree.push(path);
20085 }
20086
20087 restree.sort(sortByPos$1);
20088
20089 return {
20090 tree: restree,
20091 conflicts: conflicts || 'internal_node'
20092 };
20093}
20094
20095// To ensure we dont grow the revision tree infinitely, we stem old revisions
20096function stem(tree, depth) {
20097 // First we break out the tree into a complete list of root to leaf paths
20098 var paths = rootToLeaf(tree);
20099 var stemmedRevs;
20100
20101 var result;
20102 for (var i = 0, len = paths.length; i < len; i++) {
20103 // Then for each path, we cut off the start of the path based on the
20104 // `depth` to stem to, and generate a new set of flat trees
20105 var path = paths[i];
20106 var stemmed = path.ids;
20107 var node;
20108 if (stemmed.length > depth) {
20109 // only do the stemming work if we actually need to stem
20110 if (!stemmedRevs) {
20111 stemmedRevs = {}; // avoid allocating this object unnecessarily
20112 }
20113 var numStemmed = stemmed.length - depth;
20114 node = {
20115 pos: path.pos + numStemmed,
20116 ids: pathToTree(stemmed, numStemmed)
20117 };
20118
20119 for (var s = 0; s < numStemmed; s++) {
20120 var rev = (path.pos + s) + '-' + stemmed[s].id;
20121 stemmedRevs[rev] = true;
20122 }
20123 } else { // no need to actually stem
20124 node = {
20125 pos: path.pos,
20126 ids: pathToTree(stemmed, 0)
20127 };
20128 }
20129
20130 // Then we remerge all those flat trees together, ensuring that we dont
20131 // connect trees that would go beyond the depth limit
20132 if (result) {
20133 result = doMerge(result, node, true).tree;
20134 } else {
20135 result = [node];
20136 }
20137 }
20138
20139 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
20140 if (stemmedRevs) {
20141 traverseRevTree(result, function (isLeaf, pos, revHash) {
20142 // some revisions may have been removed in a branch but not in another
20143 delete stemmedRevs[pos + '-' + revHash];
20144 });
20145 }
20146
20147 return {
20148 tree: result,
20149 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
20150 };
20151}
20152
20153function merge(tree, path, depth) {
20154 var newTree = doMerge(tree, path);
20155 var stemmed = stem(newTree.tree, depth);
20156 return {
20157 tree: stemmed.tree,
20158 stemmedRevs: stemmed.revs,
20159 conflicts: newTree.conflicts
20160 };
20161}
20162
20163// return true if a rev exists in the rev tree, false otherwise
20164function revExists(revs, rev) {
20165 var toVisit = revs.slice();
20166 var splitRev = rev.split('-');
20167 var targetPos = parseInt(splitRev[0], 10);
20168 var targetId = splitRev[1];
20169
20170 var node;
20171 while ((node = toVisit.pop())) {
20172 if (node.pos === targetPos && node.ids[0] === targetId) {
20173 return true;
20174 }
20175 var branches = node.ids[2];
20176 for (var i = 0, len = branches.length; i < len; i++) {
20177 toVisit.push({pos: node.pos + 1, ids: branches[i]});
20178 }
20179 }
20180 return false;
20181}
20182
20183function getTrees(node) {
20184 return node.ids;
20185}
20186
20187// check if a specific revision of a doc has been deleted
20188// - metadata: the metadata object from the doc store
20189// - rev: (optional) the revision to check. defaults to winning revision
20190function isDeleted(metadata, rev) {
20191 if (!rev) {
20192 rev = winningRev(metadata);
20193 }
20194 var id = rev.substring(rev.indexOf('-') + 1);
20195 var toVisit = metadata.rev_tree.map(getTrees);
20196
20197 var tree;
20198 while ((tree = toVisit.pop())) {
20199 if (tree[0] === id) {
20200 return !!tree[1].deleted;
20201 }
20202 toVisit = toVisit.concat(tree[2]);
20203 }
20204}
20205
20206function isLocalId(id) {
20207 return (/^_local/).test(id);
20208}
20209
20210// returns the current leaf node for a given revision
20211function latest(rev, metadata) {
20212 var toVisit = metadata.rev_tree.slice();
20213 var node;
20214 while ((node = toVisit.pop())) {
20215 var pos = node.pos;
20216 var tree = node.ids;
20217 var id = tree[0];
20218 var opts = tree[1];
20219 var branches = tree[2];
20220 var isLeaf = branches.length === 0;
20221
20222 var history = node.history ? node.history.slice() : [];
20223 history.push({id: id, pos: pos, opts: opts});
20224
20225 if (isLeaf) {
20226 for (var i = 0, len = history.length; i < len; i++) {
20227 var historyNode = history[i];
20228 var historyRev = historyNode.pos + '-' + historyNode.id;
20229
20230 if (historyRev === rev) {
20231 // return the rev of this leaf
20232 return pos + '-' + id;
20233 }
20234 }
20235 }
20236
20237 for (var j = 0, l = branches.length; j < l; j++) {
20238 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
20239 }
20240 }
20241
20242 /* istanbul ignore next */
20243 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
20244}
20245
20246function updateDoc(revLimit, prev, docInfo, results,
20247 i, cb, writeDoc, newEdits) {
20248
20249 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
20250 results[i] = docInfo;
20251 return cb();
20252 }
20253
20254 // sometimes this is pre-calculated. historically not always
20255 var previousWinningRev = prev.winningRev || winningRev(prev);
20256 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
20257 isDeleted(prev, previousWinningRev);
20258 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
20259 isDeleted(docInfo.metadata);
20260 var isRoot = /^1-/.test(docInfo.metadata.rev);
20261
20262 if (previouslyDeleted && !deleted && newEdits && isRoot) {
20263 var newDoc = docInfo.data;
20264 newDoc._rev = previousWinningRev;
20265 newDoc._id = docInfo.metadata.id;
20266 docInfo = parseDoc(newDoc, newEdits);
20267 }
20268
20269 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
20270
20271 var inConflict = newEdits && ((
20272 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
20273 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
20274 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
20275
20276 if (inConflict) {
20277 var err = createError(REV_CONFLICT);
20278 results[i] = err;
20279 return cb();
20280 }
20281
20282 var newRev = docInfo.metadata.rev;
20283 docInfo.metadata.rev_tree = merged.tree;
20284 docInfo.stemmedRevs = merged.stemmedRevs || [];
20285 /* istanbul ignore else */
20286 if (prev.rev_map) {
20287 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
20288 }
20289
20290 // recalculate
20291 var winningRev$$1 = winningRev(docInfo.metadata);
20292 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
20293
20294 // calculate the total number of documents that were added/removed,
20295 // from the perspective of total_rows/doc_count
20296 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
20297 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
20298
20299 var newRevIsDeleted;
20300 if (newRev === winningRev$$1) {
20301 // if the new rev is the same as the winning rev, we can reuse that value
20302 newRevIsDeleted = winningRevIsDeleted;
20303 } else {
20304 // if they're not the same, then we need to recalculate
20305 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
20306 }
20307
20308 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
20309 true, delta, i, cb);
20310}
20311
20312function rootIsMissing(docInfo) {
20313 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
20314}
20315
20316function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
20317 writeDoc, opts, overallCallback) {
20318
20319 // Default to 1000 locally
20320 revLimit = revLimit || 1000;
20321
20322 function insertDoc(docInfo, resultsIdx, callback) {
20323 // Cant insert new deleted documents
20324 var winningRev$$1 = winningRev(docInfo.metadata);
20325 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
20326 if ('was_delete' in opts && deleted) {
20327 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
20328 return callback();
20329 }
20330
20331 // 4712 - detect whether a new document was inserted with a _rev
20332 var inConflict = newEdits && rootIsMissing(docInfo);
20333
20334 if (inConflict) {
20335 var err = createError(REV_CONFLICT);
20336 results[resultsIdx] = err;
20337 return callback();
20338 }
20339
20340 var delta = deleted ? 0 : 1;
20341
20342 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
20343 delta, resultsIdx, callback);
20344 }
20345
20346 var newEdits = opts.new_edits;
20347 var idsToDocs = new ExportedMap();
20348
20349 var docsDone = 0;
20350 var docsToDo = docInfos.length;
20351
20352 function checkAllDocsDone() {
20353 if (++docsDone === docsToDo && overallCallback) {
20354 overallCallback();
20355 }
20356 }
20357
20358 docInfos.forEach(function (currentDoc, resultsIdx) {
20359
20360 if (currentDoc._id && isLocalId(currentDoc._id)) {
20361 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
20362 api[fun](currentDoc, {ctx: tx}, function (err, res) {
20363 results[resultsIdx] = err || res;
20364 checkAllDocsDone();
20365 });
20366 return;
20367 }
20368
20369 var id = currentDoc.metadata.id;
20370 if (idsToDocs.has(id)) {
20371 docsToDo--; // duplicate
20372 idsToDocs.get(id).push([currentDoc, resultsIdx]);
20373 } else {
20374 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
20375 }
20376 });
20377
20378 // in the case of new_edits, the user can provide multiple docs
20379 // with the same id. these need to be processed sequentially
20380 idsToDocs.forEach(function (docs, id) {
20381 var numDone = 0;
20382
20383 function docWritten() {
20384 if (++numDone < docs.length) {
20385 nextDoc();
20386 } else {
20387 checkAllDocsDone();
20388 }
20389 }
20390 function nextDoc() {
20391 var value = docs[numDone];
20392 var currentDoc = value[0];
20393 var resultsIdx = value[1];
20394
20395 if (fetchedDocs.has(id)) {
20396 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
20397 resultsIdx, docWritten, writeDoc, newEdits);
20398 } else {
20399 // Ensure stemming applies to new writes as well
20400 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
20401 currentDoc.metadata.rev_tree = merged.tree;
20402 currentDoc.stemmedRevs = merged.stemmedRevs || [];
20403 insertDoc(currentDoc, resultsIdx, docWritten);
20404 }
20405 }
20406 nextDoc();
20407 });
20408}
20409
20410function safeJsonParse(str) {
20411 // This try/catch guards against stack overflow errors.
20412 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
20413 // cannot overflow.
20414 try {
20415 return JSON.parse(str);
20416 } catch (e) {
20417 /* istanbul ignore next */
20418 return vuvuzela.parse(str);
20419 }
20420}
20421
20422function safeJsonStringify(json) {
20423 try {
20424 return JSON.stringify(json);
20425 } catch (e) {
20426 /* istanbul ignore next */
20427 return vuvuzela.stringify(json);
20428 }
20429}
20430
20431function readAsBlobOrBuffer(storedObject, type) {
20432 // In the browser, we've stored a binary string. This now comes back as a
20433 // browserified Node-style Buffer (implemented as a typed array),
20434 // but we want a Blob instead.
20435 var byteArray = new Uint8Array(storedObject);
20436 return createBlob([byteArray], {type: type});
20437}
20438
20439// In the browser, we store a binary string
20440function prepareAttachmentForStorage(attData, cb) {
20441 readAsBinaryString(attData, cb);
20442}
20443
20444function createEmptyBlobOrBuffer(type) {
20445 return createBlob([''], {type: type});
20446}
20447
20448function getCacheFor(transaction, store) {
20449 var prefix = store.prefix()[0];
20450 var cache = transaction._cache;
20451 var subCache = cache.get(prefix);
20452 if (!subCache) {
20453 subCache = new ExportedMap();
20454 cache.set(prefix, subCache);
20455 }
20456 return subCache;
20457}
20458
20459function LevelTransaction() {
20460 this._batch = [];
20461 this._cache = new ExportedMap();
20462}
20463
20464LevelTransaction.prototype.get = function (store, key, callback) {
20465 var cache = getCacheFor(this, store);
20466 var exists = cache.get(key);
20467 if (exists) {
20468 return immediate(function () {
20469 callback(null, exists);
20470 });
20471 } else if (exists === null) { // deleted marker
20472 /* istanbul ignore next */
20473 return immediate(function () {
20474 callback({name: 'NotFoundError'});
20475 });
20476 }
20477 store.get(key, function (err, res) {
20478 if (err) {
20479 /* istanbul ignore else */
20480 if (err.name === 'NotFoundError') {
20481 cache.set(key, null);
20482 }
20483 return callback(err);
20484 }
20485 cache.set(key, res);
20486 callback(null, res);
20487 });
20488};
20489
20490LevelTransaction.prototype.batch = function (batch) {
20491 for (var i = 0, len = batch.length; i < len; i++) {
20492 var operation = batch[i];
20493
20494 var cache = getCacheFor(this, operation.prefix);
20495
20496 if (operation.type === 'put') {
20497 cache.set(operation.key, operation.value);
20498 } else {
20499 cache.set(operation.key, null);
20500 }
20501 }
20502 this._batch = this._batch.concat(batch);
20503};
20504
20505LevelTransaction.prototype.execute = function (db, callback) {
20506
20507 var keys = new ExportedSet();
20508 var uniqBatches = [];
20509
20510 // remove duplicates; last one wins
20511 for (var i = this._batch.length - 1; i >= 0; i--) {
20512 var operation = this._batch[i];
20513 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
20514 if (keys.has(lookupKey)) {
20515 continue;
20516 }
20517 keys.add(lookupKey);
20518 uniqBatches.push(operation);
20519 }
20520
20521 db.batch(uniqBatches, callback);
20522};
20523
20524var DOC_STORE = 'document-store';
20525var BY_SEQ_STORE = 'by-sequence';
20526var ATTACHMENT_STORE = 'attach-store';
20527var BINARY_STORE = 'attach-binary-store';
20528var LOCAL_STORE = 'local-store';
20529var META_STORE = 'meta-store';
20530
20531// leveldb barks if we try to open a db multiple times
20532// so we cache opened connections here for initstore()
20533var dbStores = new ExportedMap();
20534
20535// store the value of update_seq in the by-sequence store the key name will
20536// never conflict, since the keys in the by-sequence store are integers
20537var UPDATE_SEQ_KEY = '_local_last_update_seq';
20538var DOC_COUNT_KEY = '_local_doc_count';
20539var UUID_KEY = '_local_uuid';
20540
20541var MD5_PREFIX = 'md5-';
20542
20543var safeJsonEncoding = {
20544 encode: safeJsonStringify,
20545 decode: safeJsonParse,
20546 buffer: false,
20547 type: 'cheap-json'
20548};
20549
20550var levelChanges = new Changes();
20551
20552// winningRev and deleted are performance-killers, but
20553// in newer versions of PouchDB, they are cached on the metadata
20554function getWinningRev(metadata) {
20555 return 'winningRev' in metadata ?
20556 metadata.winningRev : winningRev(metadata);
20557}
20558
20559function getIsDeleted(metadata, winningRev$$1) {
20560 return 'deleted' in metadata ?
20561 metadata.deleted : isDeleted(metadata, winningRev$$1);
20562}
20563
20564function fetchAttachment(att, stores, opts) {
20565 var type = att.content_type;
20566 return new Promise(function (resolve, reject) {
20567 stores.binaryStore.get(att.digest, function (err, buffer) {
20568 var data;
20569 if (err) {
20570 /* istanbul ignore if */
20571 if (err.name !== 'NotFoundError') {
20572 return reject(err);
20573 } else {
20574 // empty
20575 if (!opts.binary) {
20576 data = '';
20577 } else {
20578 data = binStringToBluffer('', type);
20579 }
20580 }
20581 } else { // non-empty
20582 if (opts.binary) {
20583 data = readAsBlobOrBuffer(buffer, type);
20584 } else {
20585 data = buffer.toString('base64');
20586 }
20587 }
20588 delete att.stub;
20589 delete att.length;
20590 att.data = data;
20591 resolve();
20592 });
20593 });
20594}
20595
20596function fetchAttachments(results, stores, opts) {
20597 var atts = [];
20598 results.forEach(function (row) {
20599 if (!(row.doc && row.doc._attachments)) {
20600 return;
20601 }
20602 var attNames = Object.keys(row.doc._attachments);
20603 attNames.forEach(function (attName) {
20604 var att = row.doc._attachments[attName];
20605 if (!('data' in att)) {
20606 atts.push(att);
20607 }
20608 });
20609 });
20610
20611 return Promise.all(atts.map(function (att) {
20612 return fetchAttachment(att, stores, opts);
20613 }));
20614}
20615
20616function LevelPouch(opts, callback) {
20617 opts = clone(opts);
20618 var api = this;
20619 var instanceId;
20620 var stores = {};
20621 var revLimit = opts.revs_limit;
20622 var db;
20623 var name = opts.name;
20624 // TODO: this is undocumented and unused probably
20625 /* istanbul ignore else */
20626 if (typeof opts.createIfMissing === 'undefined') {
20627 opts.createIfMissing = true;
20628 }
20629
20630 var leveldown = opts.db;
20631
20632 var dbStore;
20633 var leveldownName = functionName(leveldown);
20634 if (dbStores.has(leveldownName)) {
20635 dbStore = dbStores.get(leveldownName);
20636 } else {
20637 dbStore = new ExportedMap();
20638 dbStores.set(leveldownName, dbStore);
20639 }
20640 if (dbStore.has(name)) {
20641 db = dbStore.get(name);
20642 afterDBCreated();
20643 } else {
20644 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
20645 /* istanbul ignore if */
20646 if (err) {
20647 dbStore["delete"](name);
20648 return callback(err);
20649 }
20650 db = dbStore.get(name);
20651 db._docCount = -1;
20652 db._queue = new Deque();
20653 /* istanbul ignore else */
20654 if (typeof opts.migrate === 'object') { // migration for leveldown
20655 opts.migrate.doMigrationOne(name, db, afterDBCreated);
20656 } else {
20657 afterDBCreated();
20658 }
20659 })));
20660 }
20661
20662 function afterDBCreated() {
20663 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
20664 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
20665 stores.attachmentStore =
20666 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
20667 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
20668 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
20669 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
20670 /* istanbul ignore else */
20671 if (typeof opts.migrate === 'object') { // migration for leveldown
20672 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
20673 } else {
20674 afterLastMigration();
20675 }
20676 }
20677
20678 function afterLastMigration() {
20679 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
20680 if (typeof db._updateSeq === 'undefined') {
20681 db._updateSeq = value || 0;
20682 }
20683 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
20684 db._docCount = !err ? value : 0;
20685 stores.metaStore.get(UUID_KEY, function (err, value) {
20686 instanceId = !err ? value : uuid$1();
20687 stores.metaStore.put(UUID_KEY, instanceId, function () {
20688 immediate(function () {
20689 callback(null, api);
20690 });
20691 });
20692 });
20693 });
20694 });
20695 }
20696
20697 function countDocs(callback) {
20698 /* istanbul ignore if */
20699 if (db.isClosed()) {
20700 return callback(new Error('database is closed'));
20701 }
20702 return callback(null, db._docCount); // use cached value
20703 }
20704
20705 api._remote = false;
20706 /* istanbul ignore next */
20707 api.type = function () {
20708 return 'leveldb';
20709 };
20710
20711 api._id = function (callback) {
20712 callback(null, instanceId);
20713 };
20714
20715 api._info = function (callback) {
20716 var res = {
20717 doc_count: db._docCount,
20718 update_seq: db._updateSeq,
20719 backend_adapter: functionName(leveldown)
20720 };
20721 return immediate(function () {
20722 callback(null, res);
20723 });
20724 };
20725
20726 function tryCode(fun, args) {
20727 try {
20728 fun.apply(null, args);
20729 } catch (err) {
20730 args[args.length - 1](err);
20731 }
20732 }
20733
20734 function executeNext() {
20735 var firstTask = db._queue.peekFront();
20736
20737 if (firstTask.type === 'read') {
20738 runReadOperation(firstTask);
20739 } else { // write, only do one at a time
20740 runWriteOperation(firstTask);
20741 }
20742 }
20743
20744 function runReadOperation(firstTask) {
20745 // do multiple reads at once simultaneously, because it's safe
20746
20747 var readTasks = [firstTask];
20748 var i = 1;
20749 var nextTask = db._queue.get(i);
20750 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
20751 readTasks.push(nextTask);
20752 i++;
20753 nextTask = db._queue.get(i);
20754 }
20755
20756 var numDone = 0;
20757
20758 readTasks.forEach(function (readTask) {
20759 var args = readTask.args;
20760 var callback = args[args.length - 1];
20761 args[args.length - 1] = getArguments(function (cbArgs) {
20762 callback.apply(null, cbArgs);
20763 if (++numDone === readTasks.length) {
20764 immediate(function () {
20765 // all read tasks have finished
20766 readTasks.forEach(function () {
20767 db._queue.shift();
20768 });
20769 if (db._queue.length) {
20770 executeNext();
20771 }
20772 });
20773 }
20774 });
20775 tryCode(readTask.fun, args);
20776 });
20777 }
20778
20779 function runWriteOperation(firstTask) {
20780 var args = firstTask.args;
20781 var callback = args[args.length - 1];
20782 args[args.length - 1] = getArguments(function (cbArgs) {
20783 callback.apply(null, cbArgs);
20784 immediate(function () {
20785 db._queue.shift();
20786 if (db._queue.length) {
20787 executeNext();
20788 }
20789 });
20790 });
20791 tryCode(firstTask.fun, args);
20792 }
20793
20794 // all read/write operations to the database are done in a queue,
20795 // similar to how websql/idb works. this avoids problems such
20796 // as e.g. compaction needing to have a lock on the database while
20797 // it updates stuff. in the future we can revisit this.
20798 function writeLock(fun) {
20799 return getArguments(function (args) {
20800 db._queue.push({
20801 fun: fun,
20802 args: args,
20803 type: 'write'
20804 });
20805
20806 if (db._queue.length === 1) {
20807 immediate(executeNext);
20808 }
20809 });
20810 }
20811
20812 // same as the writelock, but multiple can run at once
20813 function readLock(fun) {
20814 return getArguments(function (args) {
20815 db._queue.push({
20816 fun: fun,
20817 args: args,
20818 type: 'read'
20819 });
20820
20821 if (db._queue.length === 1) {
20822 immediate(executeNext);
20823 }
20824 });
20825 }
20826
20827 function formatSeq(n) {
20828 return ('0000000000000000' + n).slice(-16);
20829 }
20830
20831 function parseSeq(s) {
20832 return parseInt(s, 10);
20833 }
20834
20835 api._get = readLock(function (id, opts, callback) {
20836 opts = clone(opts);
20837
20838 stores.docStore.get(id, function (err, metadata) {
20839
20840 if (err || !metadata) {
20841 return callback(createError(MISSING_DOC, 'missing'));
20842 }
20843
20844 var rev;
20845 if (!opts.rev) {
20846 rev = getWinningRev(metadata);
20847 var deleted = getIsDeleted(metadata, rev);
20848 if (deleted) {
20849 return callback(createError(MISSING_DOC, "deleted"));
20850 }
20851 } else {
20852 rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;
20853 }
20854
20855 var seq = metadata.rev_map[rev];
20856
20857 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
20858 if (!doc) {
20859 return callback(createError(MISSING_DOC));
20860 }
20861 /* istanbul ignore if */
20862 if ('_id' in doc && doc._id !== metadata.id) {
20863 // this failing implies something very wrong
20864 return callback(new Error('wrong doc returned'));
20865 }
20866 doc._id = metadata.id;
20867 if ('_rev' in doc) {
20868 /* istanbul ignore if */
20869 if (doc._rev !== rev) {
20870 // this failing implies something very wrong
20871 return callback(new Error('wrong doc returned'));
20872 }
20873 } else {
20874 // we didn't always store this
20875 doc._rev = rev;
20876 }
20877 return callback(null, {doc: doc, metadata: metadata});
20878 });
20879 });
20880 });
20881
20882 // not technically part of the spec, but if putAttachment has its own
20883 // method...
20884 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
20885 var digest = attachment.digest;
20886 var type = attachment.content_type;
20887
20888 stores.binaryStore.get(digest, function (err, attach) {
20889 if (err) {
20890 /* istanbul ignore if */
20891 if (err.name !== 'NotFoundError') {
20892 return callback(err);
20893 }
20894 // Empty attachment
20895 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
20896 }
20897
20898 if (opts.binary) {
20899 callback(null, readAsBlobOrBuffer(attach, type));
20900 } else {
20901 callback(null, attach.toString('base64'));
20902 }
20903 });
20904 };
20905
20906 api._bulkDocs = writeLock(function (req, opts, callback) {
20907 var newEdits = opts.new_edits;
20908 var results = new Array(req.docs.length);
20909 var fetchedDocs = new ExportedMap();
20910 var stemmedRevs = new ExportedMap();
20911
20912 var txn = new LevelTransaction();
20913 var docCountDelta = 0;
20914 var newUpdateSeq = db._updateSeq;
20915
20916 // parse the docs and give each a sequence number
20917 var userDocs = req.docs;
20918 var docInfos = userDocs.map(function (doc) {
20919 if (doc._id && isLocalId(doc._id)) {
20920 return doc;
20921 }
20922 var newDoc = parseDoc(doc, newEdits, api.__opts);
20923
20924 if (newDoc.metadata && !newDoc.metadata.rev_map) {
20925 newDoc.metadata.rev_map = {};
20926 }
20927
20928 return newDoc;
20929 });
20930 var infoErrors = docInfos.filter(function (doc) {
20931 return doc.error;
20932 });
20933
20934 if (infoErrors.length) {
20935 return callback(infoErrors[0]);
20936 }
20937
20938 // verify any stub attachments as a precondition test
20939
20940 function verifyAttachment(digest, callback) {
20941 txn.get(stores.attachmentStore, digest, function (levelErr) {
20942 if (levelErr) {
20943 var err = createError(MISSING_STUB,
20944 'unknown stub attachment with digest ' +
20945 digest);
20946 callback(err);
20947 } else {
20948 callback();
20949 }
20950 });
20951 }
20952
20953 function verifyAttachments(finish) {
20954 var digests = [];
20955 userDocs.forEach(function (doc) {
20956 if (doc && doc._attachments) {
20957 Object.keys(doc._attachments).forEach(function (filename) {
20958 var att = doc._attachments[filename];
20959 if (att.stub) {
20960 digests.push(att.digest);
20961 }
20962 });
20963 }
20964 });
20965 if (!digests.length) {
20966 return finish();
20967 }
20968 var numDone = 0;
20969 var err;
20970
20971 digests.forEach(function (digest) {
20972 verifyAttachment(digest, function (attErr) {
20973 if (attErr && !err) {
20974 err = attErr;
20975 }
20976
20977 if (++numDone === digests.length) {
20978 finish(err);
20979 }
20980 });
20981 });
20982 }
20983
20984 function fetchExistingDocs(finish) {
20985 var numDone = 0;
20986 var overallErr;
20987 function checkDone() {
20988 if (++numDone === userDocs.length) {
20989 return finish(overallErr);
20990 }
20991 }
20992
20993 userDocs.forEach(function (doc) {
20994 if (doc._id && isLocalId(doc._id)) {
20995 // skip local docs
20996 return checkDone();
20997 }
20998 txn.get(stores.docStore, doc._id, function (err, info) {
20999 if (err) {
21000 /* istanbul ignore if */
21001 if (err.name !== 'NotFoundError') {
21002 overallErr = err;
21003 }
21004 } else {
21005 fetchedDocs.set(doc._id, info);
21006 }
21007 checkDone();
21008 });
21009 });
21010 }
21011
21012 function compact(revsMap, callback) {
21013 var promise = Promise.resolve();
21014 revsMap.forEach(function (revs, docId) {
21015 // TODO: parallelize, for now need to be sequential to
21016 // pass orphaned attachment tests
21017 promise = promise.then(function () {
21018 return new Promise(function (resolve, reject) {
21019 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
21020 /* istanbul ignore if */
21021 if (err) {
21022 return reject(err);
21023 }
21024 resolve();
21025 });
21026 });
21027 });
21028 });
21029
21030 promise.then(function () {
21031 callback();
21032 }, callback);
21033 }
21034
21035 function autoCompact(callback) {
21036 var revsMap = new ExportedMap();
21037 fetchedDocs.forEach(function (metadata, docId) {
21038 revsMap.set(docId, compactTree(metadata));
21039 });
21040 compact(revsMap, callback);
21041 }
21042
21043 function finish() {
21044 compact(stemmedRevs, function (error) {
21045 /* istanbul ignore if */
21046 if (error) {
21047 complete(error);
21048 }
21049 if (api.auto_compaction) {
21050 return autoCompact(complete);
21051 }
21052 complete();
21053 });
21054 }
21055
21056 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
21057 isUpdate, delta, resultsIdx, callback2) {
21058 docCountDelta += delta;
21059
21060 var err = null;
21061 var recv = 0;
21062
21063 docInfo.metadata.winningRev = winningRev$$1;
21064 docInfo.metadata.deleted = winningRevIsDeleted;
21065
21066 docInfo.data._id = docInfo.metadata.id;
21067 docInfo.data._rev = docInfo.metadata.rev;
21068
21069 if (newRevIsDeleted) {
21070 docInfo.data._deleted = true;
21071 }
21072
21073 if (docInfo.stemmedRevs.length) {
21074 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
21075 }
21076
21077 var attachments = docInfo.data._attachments ?
21078 Object.keys(docInfo.data._attachments) :
21079 [];
21080
21081 function attachmentSaved(attachmentErr) {
21082 recv++;
21083 if (!err) {
21084 /* istanbul ignore if */
21085 if (attachmentErr) {
21086 err = attachmentErr;
21087 callback2(err);
21088 } else if (recv === attachments.length) {
21089 finish();
21090 }
21091 }
21092 }
21093
21094 function onMD5Load(doc, key, data, attachmentSaved) {
21095 return function (result) {
21096 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
21097 };
21098 }
21099
21100 function doMD5(doc, key, attachmentSaved) {
21101 return function (data) {
21102 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
21103 };
21104 }
21105
21106 for (var i = 0; i < attachments.length; i++) {
21107 var key = attachments[i];
21108 var att = docInfo.data._attachments[key];
21109
21110 if (att.stub) {
21111 // still need to update the refs mapping
21112 var id = docInfo.data._id;
21113 var rev = docInfo.data._rev;
21114 saveAttachmentRefs(id, rev, att.digest, attachmentSaved);
21115 continue;
21116 }
21117 var data;
21118 if (typeof att.data === 'string') {
21119 // input is assumed to be a base64 string
21120 try {
21121 data = thisAtob(att.data);
21122 } catch (e) {
21123 callback(createError(BAD_ARG,
21124 'Attachment is not a valid base64 string'));
21125 return;
21126 }
21127 doMD5(docInfo, key, attachmentSaved)(data);
21128 } else {
21129 prepareAttachmentForStorage(att.data,
21130 doMD5(docInfo, key, attachmentSaved));
21131 }
21132 }
21133
21134 function finish() {
21135 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
21136 /* istanbul ignore if */
21137 if (seq) {
21138 // check that there aren't any existing revisions with the same
21139 // revision id, else we shouldn't do anything
21140 return callback2();
21141 }
21142 seq = ++newUpdateSeq;
21143 docInfo.metadata.rev_map[docInfo.metadata.rev] =
21144 docInfo.metadata.seq = seq;
21145 var seqKey = formatSeq(seq);
21146 var batch = [{
21147 key: seqKey,
21148 value: docInfo.data,
21149 prefix: stores.bySeqStore,
21150 type: 'put'
21151 }, {
21152 key: docInfo.metadata.id,
21153 value: docInfo.metadata,
21154 prefix: stores.docStore,
21155 type: 'put'
21156 }];
21157 txn.batch(batch);
21158 results[resultsIdx] = {
21159 ok: true,
21160 id: docInfo.metadata.id,
21161 rev: docInfo.metadata.rev
21162 };
21163 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
21164 callback2();
21165 }
21166
21167 if (!attachments.length) {
21168 finish();
21169 }
21170 }
21171
21172 // attachments are queued per-digest, otherwise the refs could be
21173 // overwritten by concurrent writes in the same bulkDocs session
21174 var attachmentQueues = {};
21175
21176 function saveAttachmentRefs(id, rev, digest, callback) {
21177
21178 function fetchAtt() {
21179 return new Promise(function (resolve, reject) {
21180 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
21181 /* istanbul ignore if */
21182 if (err && err.name !== 'NotFoundError') {
21183 return reject(err);
21184 }
21185 resolve(oldAtt);
21186 });
21187 });
21188 }
21189
21190 function saveAtt(oldAtt) {
21191 var ref = [id, rev].join('@');
21192 var newAtt = {};
21193
21194 if (oldAtt) {
21195 if (oldAtt.refs) {
21196 // only update references if this attachment already has them
21197 // since we cannot migrate old style attachments here without
21198 // doing a full db scan for references
21199 newAtt.refs = oldAtt.refs;
21200 newAtt.refs[ref] = true;
21201 }
21202 } else {
21203 newAtt.refs = {};
21204 newAtt.refs[ref] = true;
21205 }
21206
21207 return new Promise(function (resolve) {
21208 txn.batch([{
21209 type: 'put',
21210 prefix: stores.attachmentStore,
21211 key: digest,
21212 value: newAtt
21213 }]);
21214 resolve(!oldAtt);
21215 });
21216 }
21217
21218 // put attachments in a per-digest queue, to avoid two docs with the same
21219 // attachment overwriting each other
21220 var queue = attachmentQueues[digest] || Promise.resolve();
21221 attachmentQueues[digest] = queue.then(function () {
21222 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
21223 callback(null, isNewAttachment);
21224 }, callback);
21225 });
21226 }
21227
21228 function saveAttachment(docInfo, digest, key, data, callback) {
21229 var att = docInfo.data._attachments[key];
21230 delete att.data;
21231 att.digest = digest;
21232 att.length = data.length;
21233 var id = docInfo.metadata.id;
21234 var rev = docInfo.metadata.rev;
21235 att.revpos = parseInt(rev, 10);
21236
21237 saveAttachmentRefs(id, rev, digest, function (err, isNewAttachment) {
21238 /* istanbul ignore if */
21239 if (err) {
21240 return callback(err);
21241 }
21242 // do not try to store empty attachments
21243 if (data.length === 0) {
21244 return callback(err);
21245 }
21246 if (!isNewAttachment) {
21247 // small optimization - don't bother writing it again
21248 return callback(err);
21249 }
21250 txn.batch([{
21251 type: 'put',
21252 prefix: stores.binaryStore,
21253 key: digest,
21254 value: bufferFrom(data, 'binary')
21255 }]);
21256 callback();
21257 });
21258 }
21259
21260 function complete(err) {
21261 /* istanbul ignore if */
21262 if (err) {
21263 return immediate(function () {
21264 callback(err);
21265 });
21266 }
21267 txn.batch([
21268 {
21269 prefix: stores.metaStore,
21270 type: 'put',
21271 key: UPDATE_SEQ_KEY,
21272 value: newUpdateSeq
21273 },
21274 {
21275 prefix: stores.metaStore,
21276 type: 'put',
21277 key: DOC_COUNT_KEY,
21278 value: db._docCount + docCountDelta
21279 }
21280 ]);
21281 txn.execute(db, function (err) {
21282 /* istanbul ignore if */
21283 if (err) {
21284 return callback(err);
21285 }
21286 db._docCount += docCountDelta;
21287 db._updateSeq = newUpdateSeq;
21288 levelChanges.notify(name);
21289 immediate(function () {
21290 callback(null, results);
21291 });
21292 });
21293 }
21294
21295 if (!docInfos.length) {
21296 return callback(null, []);
21297 }
21298
21299 verifyAttachments(function (err) {
21300 if (err) {
21301 return callback(err);
21302 }
21303 fetchExistingDocs(function (err) {
21304 /* istanbul ignore if */
21305 if (err) {
21306 return callback(err);
21307 }
21308 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
21309 writeDoc, opts, finish);
21310 });
21311 });
21312 });
21313 api._allDocs = function (opts, callback) {
21314 if ('keys' in opts) {
21315 return allDocsKeysQuery(this, opts);
21316 }
21317 return readLock(function (opts, callback) {
21318 opts = clone(opts);
21319 countDocs(function (err, docCount) {
21320 /* istanbul ignore if */
21321 if (err) {
21322 return callback(err);
21323 }
21324 var readstreamOpts = {};
21325 var skip = opts.skip || 0;
21326 if (opts.startkey) {
21327 readstreamOpts.gte = opts.startkey;
21328 }
21329 if (opts.endkey) {
21330 readstreamOpts.lte = opts.endkey;
21331 }
21332 if (opts.key) {
21333 readstreamOpts.gte = readstreamOpts.lte = opts.key;
21334 }
21335 if (opts.descending) {
21336 readstreamOpts.reverse = true;
21337 // switch start and ends
21338 var tmp = readstreamOpts.lte;
21339 readstreamOpts.lte = readstreamOpts.gte;
21340 readstreamOpts.gte = tmp;
21341 }
21342 var limit;
21343 if (typeof opts.limit === 'number') {
21344 limit = opts.limit;
21345 }
21346 if (limit === 0 ||
21347 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
21348 readstreamOpts.gte > readstreamOpts.lte)) {
21349 // should return 0 results when start is greater than end.
21350 // normally level would "fix" this for us by reversing the order,
21351 // so short-circuit instead
21352 var returnVal = {
21353 total_rows: docCount,
21354 offset: opts.skip,
21355 rows: []
21356 };
21357 /* istanbul ignore if */
21358 if (opts.update_seq) {
21359 returnVal.update_seq = db._updateSeq;
21360 }
21361 return callback(null, returnVal);
21362 }
21363 var results = [];
21364 var docstream = stores.docStore.readStream(readstreamOpts);
21365
21366 var throughStream = through2.obj(function (entry, _, next) {
21367 var metadata = entry.value;
21368 // winningRev and deleted are performance-killers, but
21369 // in newer versions of PouchDB, they are cached on the metadata
21370 var winningRev$$1 = getWinningRev(metadata);
21371 var deleted = getIsDeleted(metadata, winningRev$$1);
21372 if (!deleted) {
21373 if (skip-- > 0) {
21374 next();
21375 return;
21376 } else if (typeof limit === 'number' && limit-- <= 0) {
21377 docstream.unpipe();
21378 docstream.destroy();
21379 next();
21380 return;
21381 }
21382 } else if (opts.deleted !== 'ok') {
21383 next();
21384 return;
21385 }
21386 function allDocsInner(data) {
21387 var doc = {
21388 id: metadata.id,
21389 key: metadata.id,
21390 value: {
21391 rev: winningRev$$1
21392 }
21393 };
21394 if (opts.include_docs) {
21395 doc.doc = data;
21396 doc.doc._rev = doc.value.rev;
21397 if (opts.conflicts) {
21398 var conflicts = collectConflicts(metadata);
21399 if (conflicts.length) {
21400 doc.doc._conflicts = conflicts;
21401 }
21402 }
21403 for (var att in doc.doc._attachments) {
21404 if (Object.prototype.hasOwnProperty.call(doc.doc._attachments, att)) {
21405 doc.doc._attachments[att].stub = true;
21406 }
21407 }
21408 }
21409 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
21410 return next();
21411 } else if (deleted) {
21412 if (opts.deleted === 'ok') {
21413 doc.value.deleted = true;
21414 doc.doc = null;
21415 } else {
21416 /* istanbul ignore next */
21417 return next();
21418 }
21419 }
21420 results.push(doc);
21421 next();
21422 }
21423 if (opts.include_docs) {
21424 var seq = metadata.rev_map[winningRev$$1];
21425 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
21426 allDocsInner(data);
21427 });
21428 }
21429 else {
21430 allDocsInner();
21431 }
21432 }, function (next) {
21433 Promise.resolve().then(function () {
21434 if (opts.include_docs && opts.attachments) {
21435 return fetchAttachments(results, stores, opts);
21436 }
21437 }).then(function () {
21438 var returnVal = {
21439 total_rows: docCount,
21440 offset: opts.skip,
21441 rows: results
21442 };
21443
21444 /* istanbul ignore if */
21445 if (opts.update_seq) {
21446 returnVal.update_seq = db._updateSeq;
21447 }
21448 callback(null, returnVal);
21449 }, callback);
21450 next();
21451 }).on('unpipe', function () {
21452 throughStream.end();
21453 });
21454
21455 docstream.on('error', callback);
21456
21457 docstream.pipe(throughStream);
21458 });
21459 })(opts, callback);
21460 };
21461
21462 api._changes = function (opts) {
21463 opts = clone(opts);
21464
21465 if (opts.continuous) {
21466 var id = name + ':' + uuid$1();
21467 levelChanges.addListener(name, id, api, opts);
21468 levelChanges.notify(name);
21469 return {
21470 cancel: function () {
21471 levelChanges.removeListener(name, id);
21472 }
21473 };
21474 }
21475
21476 var descending = opts.descending;
21477 var results = [];
21478 var lastSeq = opts.since || 0;
21479 var called = 0;
21480 var streamOpts = {
21481 reverse: descending
21482 };
21483 var limit;
21484 if ('limit' in opts && opts.limit > 0) {
21485 limit = opts.limit;
21486 }
21487 if (!streamOpts.reverse) {
21488 streamOpts.start = formatSeq(opts.since || 0);
21489 }
21490
21491 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
21492 var filter = filterChange(opts);
21493 var docIdsToMetadata = new ExportedMap();
21494
21495 function complete() {
21496 opts.done = true;
21497 if (opts.return_docs && opts.limit) {
21498 /* istanbul ignore if */
21499 if (opts.limit < results.length) {
21500 results.length = opts.limit;
21501 }
21502 }
21503 changeStream.unpipe(throughStream);
21504 changeStream.destroy();
21505 if (!opts.continuous && !opts.cancelled) {
21506 if (opts.include_docs && opts.attachments && opts.return_docs) {
21507 fetchAttachments(results, stores, opts).then(function () {
21508 opts.complete(null, {results: results, last_seq: lastSeq});
21509 });
21510 } else {
21511 opts.complete(null, {results: results, last_seq: lastSeq});
21512 }
21513 }
21514 }
21515 var changeStream = stores.bySeqStore.readStream(streamOpts);
21516 var throughStream = through2.obj(function (data, _, next) {
21517 if (limit && called >= limit) {
21518 complete();
21519 return next();
21520 }
21521 if (opts.cancelled || opts.done) {
21522 return next();
21523 }
21524
21525 var seq = parseSeq(data.key);
21526 var doc = data.value;
21527
21528 if (seq === opts.since && !descending) {
21529 // couchdb ignores `since` if descending=true
21530 return next();
21531 }
21532
21533 if (docIds && !docIds.has(doc._id)) {
21534 return next();
21535 }
21536
21537 var metadata;
21538
21539 function onGetMetadata(metadata) {
21540 var winningRev$$1 = getWinningRev(metadata);
21541
21542 function onGetWinningDoc(winningDoc) {
21543
21544 var change = opts.processChange(winningDoc, metadata, opts);
21545 change.seq = metadata.seq;
21546
21547 var filtered = filter(change);
21548 if (typeof filtered === 'object') {
21549 return opts.complete(filtered);
21550 }
21551
21552 if (filtered) {
21553 called++;
21554
21555 if (opts.attachments && opts.include_docs) {
21556 // fetch attachment immediately for the benefit
21557 // of live listeners
21558 fetchAttachments([change], stores, opts).then(function () {
21559 opts.onChange(change);
21560 });
21561 } else {
21562 opts.onChange(change);
21563 }
21564
21565 if (opts.return_docs) {
21566 results.push(change);
21567 }
21568 }
21569 next();
21570 }
21571
21572 if (metadata.seq !== seq) {
21573 // some other seq is later
21574 return next();
21575 }
21576
21577 lastSeq = seq;
21578
21579 if (winningRev$$1 === doc._rev) {
21580 return onGetWinningDoc(doc);
21581 }
21582
21583 // fetch the winner
21584
21585 var winningSeq = metadata.rev_map[winningRev$$1];
21586
21587 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
21588 onGetWinningDoc(doc);
21589 });
21590 }
21591
21592 metadata = docIdsToMetadata.get(doc._id);
21593 if (metadata) { // cached
21594 return onGetMetadata(metadata);
21595 }
21596 // metadata not cached, have to go fetch it
21597 stores.docStore.get(doc._id, function (err, metadata) {
21598 /* istanbul ignore if */
21599 if (opts.cancelled || opts.done || db.isClosed() ||
21600 isLocalId(metadata.id)) {
21601 return next();
21602 }
21603 docIdsToMetadata.set(doc._id, metadata);
21604 onGetMetadata(metadata);
21605 });
21606 }, function (next) {
21607 if (opts.cancelled) {
21608 return next();
21609 }
21610 if (opts.return_docs && opts.limit) {
21611 /* istanbul ignore if */
21612 if (opts.limit < results.length) {
21613 results.length = opts.limit;
21614 }
21615 }
21616
21617 next();
21618 }).on('unpipe', function () {
21619 throughStream.end();
21620 complete();
21621 });
21622 changeStream.pipe(throughStream);
21623 return {
21624 cancel: function () {
21625 opts.cancelled = true;
21626 complete();
21627 }
21628 };
21629 };
21630
21631 api._close = function (callback) {
21632 /* istanbul ignore if */
21633 if (db.isClosed()) {
21634 return callback(createError(NOT_OPEN));
21635 }
21636 db.close(function (err) {
21637 /* istanbul ignore if */
21638 if (err) {
21639 callback(err);
21640 } else {
21641 dbStore["delete"](name);
21642
21643 var adapterName = functionName(leveldown);
21644 var adapterStore = dbStores.get(adapterName);
21645 var keys = [...adapterStore.keys()].filter(k => k.includes("-mrview-"));
21646 keys.forEach(key => {
21647 var eventEmitter = adapterStore.get(key);
21648 eventEmitter.removeAllListeners();
21649 eventEmitter.close();
21650 adapterStore["delete"](key);
21651 });
21652
21653 callback();
21654 }
21655 });
21656 };
21657
21658 api._getRevisionTree = function (docId, callback) {
21659 stores.docStore.get(docId, function (err, metadata) {
21660 if (err) {
21661 callback(createError(MISSING_DOC));
21662 } else {
21663 callback(null, metadata.rev_tree);
21664 }
21665 });
21666 };
21667
21668 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
21669 api._doCompactionNoLock(docId, revs, opts, callback);
21670 });
21671
21672 // the NoLock version is for use by bulkDocs
21673 api._doCompactionNoLock = function (docId, revs, opts, callback) {
21674 if (typeof opts === 'function') {
21675 callback = opts;
21676 opts = {};
21677 }
21678
21679 if (!revs.length) {
21680 return callback();
21681 }
21682 var txn = opts.ctx || new LevelTransaction();
21683
21684 txn.get(stores.docStore, docId, function (err, metadata) {
21685 /* istanbul ignore if */
21686 if (err) {
21687 return callback(err);
21688 }
21689 var seqs = revs.map(function (rev) {
21690 var seq = metadata.rev_map[rev];
21691 delete metadata.rev_map[rev];
21692 return seq;
21693 });
21694 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
21695 revHash, ctx, opts) {
21696 var rev = pos + '-' + revHash;
21697 if (revs.indexOf(rev) !== -1) {
21698 opts.status = 'missing';
21699 }
21700 });
21701
21702 var batch = [];
21703 batch.push({
21704 key: metadata.id,
21705 value: metadata,
21706 type: 'put',
21707 prefix: stores.docStore
21708 });
21709
21710 var digestMap = {};
21711 var numDone = 0;
21712 var overallErr;
21713 function checkDone(err) {
21714 /* istanbul ignore if */
21715 if (err) {
21716 overallErr = err;
21717 }
21718 if (++numDone === revs.length) { // done
21719 /* istanbul ignore if */
21720 if (overallErr) {
21721 return callback(overallErr);
21722 }
21723 deleteOrphanedAttachments();
21724 }
21725 }
21726
21727 function finish(err) {
21728 /* istanbul ignore if */
21729 if (err) {
21730 return callback(err);
21731 }
21732 txn.batch(batch);
21733 if (opts.ctx) {
21734 // don't execute immediately
21735 return callback();
21736 }
21737 txn.execute(db, callback);
21738 }
21739
21740 function deleteOrphanedAttachments() {
21741 var possiblyOrphanedAttachments = Object.keys(digestMap);
21742 if (!possiblyOrphanedAttachments.length) {
21743 return finish();
21744 }
21745 var numDone = 0;
21746 var overallErr;
21747 function checkDone(err) {
21748 /* istanbul ignore if */
21749 if (err) {
21750 overallErr = err;
21751 }
21752 if (++numDone === possiblyOrphanedAttachments.length) {
21753 finish(overallErr);
21754 }
21755 }
21756 var refsToDelete = new ExportedMap();
21757 revs.forEach(function (rev) {
21758 refsToDelete.set(docId + '@' + rev, true);
21759 });
21760 possiblyOrphanedAttachments.forEach(function (digest) {
21761 txn.get(stores.attachmentStore, digest, function (err, attData) {
21762 /* istanbul ignore if */
21763 if (err) {
21764 if (err.name === 'NotFoundError') {
21765 return checkDone();
21766 } else {
21767 return checkDone(err);
21768 }
21769 }
21770 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
21771 return !refsToDelete.has(ref);
21772 });
21773 var newRefs = {};
21774 refs.forEach(function (ref) {
21775 newRefs[ref] = true;
21776 });
21777 if (refs.length) { // not orphaned
21778 batch.push({
21779 key: digest,
21780 type: 'put',
21781 value: {refs: newRefs},
21782 prefix: stores.attachmentStore
21783 });
21784 } else { // orphaned, can safely delete
21785 batch = batch.concat([{
21786 key: digest,
21787 type: 'del',
21788 prefix: stores.attachmentStore
21789 }, {
21790 key: digest,
21791 type: 'del',
21792 prefix: stores.binaryStore
21793 }]);
21794 }
21795 checkDone();
21796 });
21797 });
21798 }
21799
21800 seqs.forEach(function (seq) {
21801 batch.push({
21802 key: formatSeq(seq),
21803 type: 'del',
21804 prefix: stores.bySeqStore
21805 });
21806 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
21807 /* istanbul ignore if */
21808 if (err) {
21809 if (err.name === 'NotFoundError') {
21810 return checkDone();
21811 } else {
21812 return checkDone(err);
21813 }
21814 }
21815 var atts = Object.keys(doc._attachments || {});
21816 atts.forEach(function (attName) {
21817 var digest = doc._attachments[attName].digest;
21818 digestMap[digest] = true;
21819 });
21820 checkDone();
21821 });
21822 });
21823 });
21824 };
21825
21826 api._getLocal = function (id, callback) {
21827 stores.localStore.get(id, function (err, doc) {
21828 if (err) {
21829 callback(createError(MISSING_DOC));
21830 } else {
21831 callback(null, doc);
21832 }
21833 });
21834 };
21835
21836 api._putLocal = function (doc, opts, callback) {
21837 if (typeof opts === 'function') {
21838 callback = opts;
21839 opts = {};
21840 }
21841 if (opts.ctx) {
21842 api._putLocalNoLock(doc, opts, callback);
21843 } else {
21844 api._putLocalWithLock(doc, opts, callback);
21845 }
21846 };
21847
21848 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
21849 api._putLocalNoLock(doc, opts, callback);
21850 });
21851
21852 // the NoLock version is for use by bulkDocs
21853 api._putLocalNoLock = function (doc, opts, callback) {
21854 delete doc._revisions; // ignore this, trust the rev
21855 var oldRev = doc._rev;
21856 var id = doc._id;
21857
21858 var txn = opts.ctx || new LevelTransaction();
21859
21860 txn.get(stores.localStore, id, function (err, resp) {
21861 if (err && oldRev) {
21862 return callback(createError(REV_CONFLICT));
21863 }
21864 if (resp && resp._rev !== oldRev) {
21865 return callback(createError(REV_CONFLICT));
21866 }
21867 doc._rev =
21868 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
21869 var batch = [
21870 {
21871 type: 'put',
21872 prefix: stores.localStore,
21873 key: id,
21874 value: doc
21875 }
21876 ];
21877
21878 txn.batch(batch);
21879 var ret = {ok: true, id: doc._id, rev: doc._rev};
21880
21881 if (opts.ctx) {
21882 // don't execute immediately
21883 return callback(null, ret);
21884 }
21885 txn.execute(db, function (err) {
21886 /* istanbul ignore if */
21887 if (err) {
21888 return callback(err);
21889 }
21890 callback(null, ret);
21891 });
21892 });
21893 };
21894
21895 api._removeLocal = function (doc, opts, callback) {
21896 if (typeof opts === 'function') {
21897 callback = opts;
21898 opts = {};
21899 }
21900 if (opts.ctx) {
21901 api._removeLocalNoLock(doc, opts, callback);
21902 } else {
21903 api._removeLocalWithLock(doc, opts, callback);
21904 }
21905 };
21906
21907 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
21908 api._removeLocalNoLock(doc, opts, callback);
21909 });
21910
21911 // the NoLock version is for use by bulkDocs
21912 api._removeLocalNoLock = function (doc, opts, callback) {
21913 var txn = opts.ctx || new LevelTransaction();
21914 txn.get(stores.localStore, doc._id, function (err, resp) {
21915 if (err) {
21916 /* istanbul ignore if */
21917 if (err.name !== 'NotFoundError') {
21918 return callback(err);
21919 } else {
21920 return callback(createError(MISSING_DOC));
21921 }
21922 }
21923 if (resp._rev !== doc._rev) {
21924 return callback(createError(REV_CONFLICT));
21925 }
21926 txn.batch([{
21927 prefix: stores.localStore,
21928 type: 'del',
21929 key: doc._id
21930 }]);
21931 var ret = {ok: true, id: doc._id, rev: '0-0'};
21932 if (opts.ctx) {
21933 // don't execute immediately
21934 return callback(null, ret);
21935 }
21936 txn.execute(db, function (err) {
21937 /* istanbul ignore if */
21938 if (err) {
21939 return callback(err);
21940 }
21941 callback(null, ret);
21942 });
21943 });
21944 };
21945
21946 // close and delete open leveldb stores
21947 api._destroy = function (opts, callback) {
21948 var dbStore;
21949 var leveldownName = functionName(leveldown);
21950 /* istanbul ignore else */
21951 if (dbStores.has(leveldownName)) {
21952 dbStore = dbStores.get(leveldownName);
21953 } else {
21954 return callDestroy(name, callback);
21955 }
21956
21957 /* istanbul ignore else */
21958 if (dbStore.has(name)) {
21959 levelChanges.removeAllListeners(name);
21960
21961 dbStore.get(name).close(function () {
21962 dbStore["delete"](name);
21963 callDestroy(name, callback);
21964 });
21965 } else {
21966 callDestroy(name, callback);
21967 }
21968 };
21969 function callDestroy(name, cb) {
21970 // May not exist if leveldown is backed by memory adapter
21971 /* istanbul ignore else */
21972 if ('destroy' in leveldown) {
21973 leveldown.destroy(name, cb);
21974 } else {
21975 cb(null);
21976 }
21977 }
21978}
21979
21980function MemDownPouch(opts, callback) {
21981 var _opts = $inject_Object_assign({
21982 db: memdown
21983 }, opts);
21984
21985 LevelPouch.call(this, _opts, callback);
21986}
21987
21988// overrides for normal LevelDB behavior on Node
21989MemDownPouch.valid = function () {
21990 return true;
21991};
21992MemDownPouch.use_prefix = false;
21993
21994function MemoryPouchPlugin (PouchDB) {
21995 PouchDB.adapter('memory', MemDownPouch, true);
21996}
21997
21998// this code only runs in the browser, as its own dist/ script
21999
22000if (typeof PouchDB === 'undefined') {
22001 guardedConsole('error', 'memory adapter plugin error: ' +
22002 'Cannot find global "PouchDB" object! ' +
22003 'Did you remember to include pouchdb.js?');
22004} else {
22005 PouchDB.plugin(MemoryPouchPlugin);
22006}
22007
22008},{"1":1,"112":112,"118":118,"133":133,"18":18,"21":21,"24":24,"30":30,"32":32,"54":54,"56":56,"58":58,"76":76,"78":78,"8":8}]},{},[136]);
22009
\No newline at end of file