UNPKG

596 kBJavaScriptView Raw
1// PouchDB in-memory plugin 7.1.1
2// Based on MemDOWN: https://github.com/rvagg/memdown
3//
4// (c) 2012-2019 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){
30'use strict';
31
32var objectAssign = _dereq_(69);
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,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
538},{"5":5,"69":69}],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){
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,_dereq_(71),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1160},{"3":3,"4":4,"71":71}],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 for (var i = 0; i < len; i += 4) {
1229 tmp =
1230 (revLookup[b64.charCodeAt(i)] << 18) |
1231 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1232 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1233 revLookup[b64.charCodeAt(i + 3)]
1234 arr[curByte++] = (tmp >> 16) & 0xFF
1235 arr[curByte++] = (tmp >> 8) & 0xFF
1236 arr[curByte++] = tmp & 0xFF
1237 }
1238
1239 if (placeHoldersLen === 2) {
1240 tmp =
1241 (revLookup[b64.charCodeAt(i)] << 2) |
1242 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1243 arr[curByte++] = tmp & 0xFF
1244 }
1245
1246 if (placeHoldersLen === 1) {
1247 tmp =
1248 (revLookup[b64.charCodeAt(i)] << 10) |
1249 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1250 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1251 arr[curByte++] = (tmp >> 8) & 0xFF
1252 arr[curByte++] = tmp & 0xFF
1253 }
1254
1255 return arr
1256}
1257
1258function tripletToBase64 (num) {
1259 return lookup[num >> 18 & 0x3F] +
1260 lookup[num >> 12 & 0x3F] +
1261 lookup[num >> 6 & 0x3F] +
1262 lookup[num & 0x3F]
1263}
1264
1265function encodeChunk (uint8, start, end) {
1266 var tmp
1267 var output = []
1268 for (var i = start; i < end; i += 3) {
1269 tmp =
1270 ((uint8[i] << 16) & 0xFF0000) +
1271 ((uint8[i + 1] << 8) & 0xFF00) +
1272 (uint8[i + 2] & 0xFF)
1273 output.push(tripletToBase64(tmp))
1274 }
1275 return output.join('')
1276}
1277
1278function fromByteArray (uint8) {
1279 var tmp
1280 var len = uint8.length
1281 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1282 var parts = []
1283 var maxChunkLength = 16383 // must be multiple of 3
1284
1285 // go through the array every three bytes, we'll deal with trailing stuff later
1286 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1287 parts.push(encodeChunk(
1288 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
1289 ))
1290 }
1291
1292 // pad the end with zeros, but make sure to not forget the extra bytes
1293 if (extraBytes === 1) {
1294 tmp = uint8[len - 1]
1295 parts.push(
1296 lookup[tmp >> 2] +
1297 lookup[(tmp << 4) & 0x3F] +
1298 '=='
1299 )
1300 } else if (extraBytes === 2) {
1301 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1302 parts.push(
1303 lookup[tmp >> 10] +
1304 lookup[(tmp >> 4) & 0x3F] +
1305 lookup[(tmp << 2) & 0x3F] +
1306 '='
1307 )
1308 }
1309
1310 return parts.join('')
1311}
1312
1313},{}],7:[function(_dereq_,module,exports){
1314
1315},{}],8:[function(_dereq_,module,exports){
1316(function (Buffer){
1317var toString = Object.prototype.toString
1318
1319var isModern = (
1320 typeof Buffer.alloc === 'function' &&
1321 typeof Buffer.allocUnsafe === 'function' &&
1322 typeof Buffer.from === 'function'
1323)
1324
1325function isArrayBuffer (input) {
1326 return toString.call(input).slice(8, -1) === 'ArrayBuffer'
1327}
1328
1329function fromArrayBuffer (obj, byteOffset, length) {
1330 byteOffset >>>= 0
1331
1332 var maxLength = obj.byteLength - byteOffset
1333
1334 if (maxLength < 0) {
1335 throw new RangeError("'offset' is out of bounds")
1336 }
1337
1338 if (length === undefined) {
1339 length = maxLength
1340 } else {
1341 length >>>= 0
1342
1343 if (length > maxLength) {
1344 throw new RangeError("'length' is out of bounds")
1345 }
1346 }
1347
1348 return isModern
1349 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
1350 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
1351}
1352
1353function fromString (string, encoding) {
1354 if (typeof encoding !== 'string' || encoding === '') {
1355 encoding = 'utf8'
1356 }
1357
1358 if (!Buffer.isEncoding(encoding)) {
1359 throw new TypeError('"encoding" must be a valid string encoding')
1360 }
1361
1362 return isModern
1363 ? Buffer.from(string, encoding)
1364 : new Buffer(string, encoding)
1365}
1366
1367function bufferFrom (value, encodingOrOffset, length) {
1368 if (typeof value === 'number') {
1369 throw new TypeError('"value" argument must not be a number')
1370 }
1371
1372 if (isArrayBuffer(value)) {
1373 return fromArrayBuffer(value, encodingOrOffset, length)
1374 }
1375
1376 if (typeof value === 'string') {
1377 return fromString(value, encodingOrOffset)
1378 }
1379
1380 return isModern
1381 ? Buffer.from(value)
1382 : new Buffer(value)
1383}
1384
1385module.exports = bufferFrom
1386
1387}).call(this,_dereq_(9).Buffer)
1388},{"9":9}],9:[function(_dereq_,module,exports){
1389(function (Buffer){
1390/*!
1391 * The buffer module from node.js, for the browser.
1392 *
1393 * @author Feross Aboukhadijeh <https://feross.org>
1394 * @license MIT
1395 */
1396/* eslint-disable no-proto */
1397
1398'use strict'
1399
1400var base64 = _dereq_(6)
1401var ieee754 = _dereq_(23)
1402
1403exports.Buffer = Buffer
1404exports.SlowBuffer = SlowBuffer
1405exports.INSPECT_MAX_BYTES = 50
1406
1407var K_MAX_LENGTH = 0x7fffffff
1408exports.kMaxLength = K_MAX_LENGTH
1409
1410/**
1411 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1412 * === true Use Uint8Array implementation (fastest)
1413 * === false Print warning and recommend using `buffer` v4.x which has an Object
1414 * implementation (most compatible, even IE6)
1415 *
1416 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1417 * Opera 11.6+, iOS 4.2+.
1418 *
1419 * We report that the browser does not support typed arrays if the are not subclassable
1420 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1421 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1422 * for __proto__ and has a buggy typed array implementation.
1423 */
1424Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1425
1426if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1427 typeof console.error === 'function') {
1428 console.error(
1429 'This browser lacks typed array (Uint8Array) support which is required by ' +
1430 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1431 )
1432}
1433
1434function typedArraySupport () {
1435 // Can typed array instances can be augmented?
1436 try {
1437 var arr = new Uint8Array(1)
1438 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
1439 return arr.foo() === 42
1440 } catch (e) {
1441 return false
1442 }
1443}
1444
1445Object.defineProperty(Buffer.prototype, 'parent', {
1446 enumerable: true,
1447 get: function () {
1448 if (!Buffer.isBuffer(this)) return undefined
1449 return this.buffer
1450 }
1451})
1452
1453Object.defineProperty(Buffer.prototype, 'offset', {
1454 enumerable: true,
1455 get: function () {
1456 if (!Buffer.isBuffer(this)) return undefined
1457 return this.byteOffset
1458 }
1459})
1460
1461function createBuffer (length) {
1462 if (length > K_MAX_LENGTH) {
1463 throw new RangeError('The value "' + length + '" is invalid for option "size"')
1464 }
1465 // Return an augmented `Uint8Array` instance
1466 var buf = new Uint8Array(length)
1467 buf.__proto__ = Buffer.prototype
1468 return buf
1469}
1470
1471/**
1472 * The Buffer constructor returns instances of `Uint8Array` that have their
1473 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1474 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1475 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1476 * returns a single octet.
1477 *
1478 * The `Uint8Array` prototype remains unmodified.
1479 */
1480
1481function Buffer (arg, encodingOrOffset, length) {
1482 // Common case.
1483 if (typeof arg === 'number') {
1484 if (typeof encodingOrOffset === 'string') {
1485 throw new TypeError(
1486 'The "string" argument must be of type string. Received type number'
1487 )
1488 }
1489 return allocUnsafe(arg)
1490 }
1491 return from(arg, encodingOrOffset, length)
1492}
1493
1494// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
1495if (typeof Symbol !== 'undefined' && Symbol.species != null &&
1496 Buffer[Symbol.species] === Buffer) {
1497 Object.defineProperty(Buffer, Symbol.species, {
1498 value: null,
1499 configurable: true,
1500 enumerable: false,
1501 writable: false
1502 })
1503}
1504
1505Buffer.poolSize = 8192 // not used by this implementation
1506
1507function from (value, encodingOrOffset, length) {
1508 if (typeof value === 'string') {
1509 return fromString(value, encodingOrOffset)
1510 }
1511
1512 if (ArrayBuffer.isView(value)) {
1513 return fromArrayLike(value)
1514 }
1515
1516 if (value == null) {
1517 throw TypeError(
1518 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1519 'or Array-like Object. Received type ' + (typeof value)
1520 )
1521 }
1522
1523 if (isInstance(value, ArrayBuffer) ||
1524 (value && isInstance(value.buffer, ArrayBuffer))) {
1525 return fromArrayBuffer(value, encodingOrOffset, length)
1526 }
1527
1528 if (typeof value === 'number') {
1529 throw new TypeError(
1530 'The "value" argument must not be of type number. Received type number'
1531 )
1532 }
1533
1534 var valueOf = value.valueOf && value.valueOf()
1535 if (valueOf != null && valueOf !== value) {
1536 return Buffer.from(valueOf, encodingOrOffset, length)
1537 }
1538
1539 var b = fromObject(value)
1540 if (b) return b
1541
1542 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
1543 typeof value[Symbol.toPrimitive] === 'function') {
1544 return Buffer.from(
1545 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
1546 )
1547 }
1548
1549 throw new TypeError(
1550 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
1551 'or Array-like Object. Received type ' + (typeof value)
1552 )
1553}
1554
1555/**
1556 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1557 * if value is a number.
1558 * Buffer.from(str[, encoding])
1559 * Buffer.from(array)
1560 * Buffer.from(buffer)
1561 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1562 **/
1563Buffer.from = function (value, encodingOrOffset, length) {
1564 return from(value, encodingOrOffset, length)
1565}
1566
1567// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1568// https://github.com/feross/buffer/pull/148
1569Buffer.prototype.__proto__ = Uint8Array.prototype
1570Buffer.__proto__ = Uint8Array
1571
1572function assertSize (size) {
1573 if (typeof size !== 'number') {
1574 throw new TypeError('"size" argument must be of type number')
1575 } else if (size < 0) {
1576 throw new RangeError('The value "' + size + '" is invalid for option "size"')
1577 }
1578}
1579
1580function alloc (size, fill, encoding) {
1581 assertSize(size)
1582 if (size <= 0) {
1583 return createBuffer(size)
1584 }
1585 if (fill !== undefined) {
1586 // Only pay attention to encoding if it's a string. This
1587 // prevents accidentally sending in a number that would
1588 // be interpretted as a start offset.
1589 return typeof encoding === 'string'
1590 ? createBuffer(size).fill(fill, encoding)
1591 : createBuffer(size).fill(fill)
1592 }
1593 return createBuffer(size)
1594}
1595
1596/**
1597 * Creates a new filled Buffer instance.
1598 * alloc(size[, fill[, encoding]])
1599 **/
1600Buffer.alloc = function (size, fill, encoding) {
1601 return alloc(size, fill, encoding)
1602}
1603
1604function allocUnsafe (size) {
1605 assertSize(size)
1606 return createBuffer(size < 0 ? 0 : checked(size) | 0)
1607}
1608
1609/**
1610 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
1611 * */
1612Buffer.allocUnsafe = function (size) {
1613 return allocUnsafe(size)
1614}
1615/**
1616 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
1617 */
1618Buffer.allocUnsafeSlow = function (size) {
1619 return allocUnsafe(size)
1620}
1621
1622function fromString (string, encoding) {
1623 if (typeof encoding !== 'string' || encoding === '') {
1624 encoding = 'utf8'
1625 }
1626
1627 if (!Buffer.isEncoding(encoding)) {
1628 throw new TypeError('Unknown encoding: ' + encoding)
1629 }
1630
1631 var length = byteLength(string, encoding) | 0
1632 var buf = createBuffer(length)
1633
1634 var actual = buf.write(string, encoding)
1635
1636 if (actual !== length) {
1637 // Writing a hex string, for example, that contains invalid characters will
1638 // cause everything after the first invalid character to be ignored. (e.g.
1639 // 'abxxcd' will be treated as 'ab')
1640 buf = buf.slice(0, actual)
1641 }
1642
1643 return buf
1644}
1645
1646function fromArrayLike (array) {
1647 var length = array.length < 0 ? 0 : checked(array.length) | 0
1648 var buf = createBuffer(length)
1649 for (var i = 0; i < length; i += 1) {
1650 buf[i] = array[i] & 255
1651 }
1652 return buf
1653}
1654
1655function fromArrayBuffer (array, byteOffset, length) {
1656 if (byteOffset < 0 || array.byteLength < byteOffset) {
1657 throw new RangeError('"offset" is outside of buffer bounds')
1658 }
1659
1660 if (array.byteLength < byteOffset + (length || 0)) {
1661 throw new RangeError('"length" is outside of buffer bounds')
1662 }
1663
1664 var buf
1665 if (byteOffset === undefined && length === undefined) {
1666 buf = new Uint8Array(array)
1667 } else if (length === undefined) {
1668 buf = new Uint8Array(array, byteOffset)
1669 } else {
1670 buf = new Uint8Array(array, byteOffset, length)
1671 }
1672
1673 // Return an augmented `Uint8Array` instance
1674 buf.__proto__ = Buffer.prototype
1675 return buf
1676}
1677
1678function fromObject (obj) {
1679 if (Buffer.isBuffer(obj)) {
1680 var len = checked(obj.length) | 0
1681 var buf = createBuffer(len)
1682
1683 if (buf.length === 0) {
1684 return buf
1685 }
1686
1687 obj.copy(buf, 0, 0, len)
1688 return buf
1689 }
1690
1691 if (obj.length !== undefined) {
1692 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
1693 return createBuffer(0)
1694 }
1695 return fromArrayLike(obj)
1696 }
1697
1698 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
1699 return fromArrayLike(obj.data)
1700 }
1701}
1702
1703function checked (length) {
1704 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
1705 // length is NaN (which is otherwise coerced to zero.)
1706 if (length >= K_MAX_LENGTH) {
1707 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1708 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1709 }
1710 return length | 0
1711}
1712
1713function SlowBuffer (length) {
1714 if (+length != length) { // eslint-disable-line eqeqeq
1715 length = 0
1716 }
1717 return Buffer.alloc(+length)
1718}
1719
1720Buffer.isBuffer = function isBuffer (b) {
1721 return b != null && b._isBuffer === true &&
1722 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
1723}
1724
1725Buffer.compare = function compare (a, b) {
1726 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
1727 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
1728 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1729 throw new TypeError(
1730 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
1731 )
1732 }
1733
1734 if (a === b) return 0
1735
1736 var x = a.length
1737 var y = b.length
1738
1739 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1740 if (a[i] !== b[i]) {
1741 x = a[i]
1742 y = b[i]
1743 break
1744 }
1745 }
1746
1747 if (x < y) return -1
1748 if (y < x) return 1
1749 return 0
1750}
1751
1752Buffer.isEncoding = function isEncoding (encoding) {
1753 switch (String(encoding).toLowerCase()) {
1754 case 'hex':
1755 case 'utf8':
1756 case 'utf-8':
1757 case 'ascii':
1758 case 'latin1':
1759 case 'binary':
1760 case 'base64':
1761 case 'ucs2':
1762 case 'ucs-2':
1763 case 'utf16le':
1764 case 'utf-16le':
1765 return true
1766 default:
1767 return false
1768 }
1769}
1770
1771Buffer.concat = function concat (list, length) {
1772 if (!Array.isArray(list)) {
1773 throw new TypeError('"list" argument must be an Array of Buffers')
1774 }
1775
1776 if (list.length === 0) {
1777 return Buffer.alloc(0)
1778 }
1779
1780 var i
1781 if (length === undefined) {
1782 length = 0
1783 for (i = 0; i < list.length; ++i) {
1784 length += list[i].length
1785 }
1786 }
1787
1788 var buffer = Buffer.allocUnsafe(length)
1789 var pos = 0
1790 for (i = 0; i < list.length; ++i) {
1791 var buf = list[i]
1792 if (isInstance(buf, Uint8Array)) {
1793 buf = Buffer.from(buf)
1794 }
1795 if (!Buffer.isBuffer(buf)) {
1796 throw new TypeError('"list" argument must be an Array of Buffers')
1797 }
1798 buf.copy(buffer, pos)
1799 pos += buf.length
1800 }
1801 return buffer
1802}
1803
1804function byteLength (string, encoding) {
1805 if (Buffer.isBuffer(string)) {
1806 return string.length
1807 }
1808 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
1809 return string.byteLength
1810 }
1811 if (typeof string !== 'string') {
1812 throw new TypeError(
1813 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
1814 'Received type ' + typeof string
1815 )
1816 }
1817
1818 var len = string.length
1819 var mustMatch = (arguments.length > 2 && arguments[2] === true)
1820 if (!mustMatch && len === 0) return 0
1821
1822 // Use a for loop to avoid recursion
1823 var loweredCase = false
1824 for (;;) {
1825 switch (encoding) {
1826 case 'ascii':
1827 case 'latin1':
1828 case 'binary':
1829 return len
1830 case 'utf8':
1831 case 'utf-8':
1832 return utf8ToBytes(string).length
1833 case 'ucs2':
1834 case 'ucs-2':
1835 case 'utf16le':
1836 case 'utf-16le':
1837 return len * 2
1838 case 'hex':
1839 return len >>> 1
1840 case 'base64':
1841 return base64ToBytes(string).length
1842 default:
1843 if (loweredCase) {
1844 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
1845 }
1846 encoding = ('' + encoding).toLowerCase()
1847 loweredCase = true
1848 }
1849 }
1850}
1851Buffer.byteLength = byteLength
1852
1853function slowToString (encoding, start, end) {
1854 var loweredCase = false
1855
1856 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1857 // property of a typed array.
1858
1859 // This behaves neither like String nor Uint8Array in that we set start/end
1860 // to their upper/lower bounds if the value passed is out of range.
1861 // undefined is handled specially as per ECMA-262 6th Edition,
1862 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1863 if (start === undefined || start < 0) {
1864 start = 0
1865 }
1866 // Return early if start > this.length. Done here to prevent potential uint32
1867 // coercion fail below.
1868 if (start > this.length) {
1869 return ''
1870 }
1871
1872 if (end === undefined || end > this.length) {
1873 end = this.length
1874 }
1875
1876 if (end <= 0) {
1877 return ''
1878 }
1879
1880 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1881 end >>>= 0
1882 start >>>= 0
1883
1884 if (end <= start) {
1885 return ''
1886 }
1887
1888 if (!encoding) encoding = 'utf8'
1889
1890 while (true) {
1891 switch (encoding) {
1892 case 'hex':
1893 return hexSlice(this, start, end)
1894
1895 case 'utf8':
1896 case 'utf-8':
1897 return utf8Slice(this, start, end)
1898
1899 case 'ascii':
1900 return asciiSlice(this, start, end)
1901
1902 case 'latin1':
1903 case 'binary':
1904 return latin1Slice(this, start, end)
1905
1906 case 'base64':
1907 return base64Slice(this, start, end)
1908
1909 case 'ucs2':
1910 case 'ucs-2':
1911 case 'utf16le':
1912 case 'utf-16le':
1913 return utf16leSlice(this, start, end)
1914
1915 default:
1916 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1917 encoding = (encoding + '').toLowerCase()
1918 loweredCase = true
1919 }
1920 }
1921}
1922
1923// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1924// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1925// reliably in a browserify context because there could be multiple different
1926// copies of the 'buffer' package in use. This method works even for Buffer
1927// instances that were created from another copy of the `buffer` package.
1928// See: https://github.com/feross/buffer/issues/154
1929Buffer.prototype._isBuffer = true
1930
1931function swap (b, n, m) {
1932 var i = b[n]
1933 b[n] = b[m]
1934 b[m] = i
1935}
1936
1937Buffer.prototype.swap16 = function swap16 () {
1938 var len = this.length
1939 if (len % 2 !== 0) {
1940 throw new RangeError('Buffer size must be a multiple of 16-bits')
1941 }
1942 for (var i = 0; i < len; i += 2) {
1943 swap(this, i, i + 1)
1944 }
1945 return this
1946}
1947
1948Buffer.prototype.swap32 = function swap32 () {
1949 var len = this.length
1950 if (len % 4 !== 0) {
1951 throw new RangeError('Buffer size must be a multiple of 32-bits')
1952 }
1953 for (var i = 0; i < len; i += 4) {
1954 swap(this, i, i + 3)
1955 swap(this, i + 1, i + 2)
1956 }
1957 return this
1958}
1959
1960Buffer.prototype.swap64 = function swap64 () {
1961 var len = this.length
1962 if (len % 8 !== 0) {
1963 throw new RangeError('Buffer size must be a multiple of 64-bits')
1964 }
1965 for (var i = 0; i < len; i += 8) {
1966 swap(this, i, i + 7)
1967 swap(this, i + 1, i + 6)
1968 swap(this, i + 2, i + 5)
1969 swap(this, i + 3, i + 4)
1970 }
1971 return this
1972}
1973
1974Buffer.prototype.toString = function toString () {
1975 var length = this.length
1976 if (length === 0) return ''
1977 if (arguments.length === 0) return utf8Slice(this, 0, length)
1978 return slowToString.apply(this, arguments)
1979}
1980
1981Buffer.prototype.toLocaleString = Buffer.prototype.toString
1982
1983Buffer.prototype.equals = function equals (b) {
1984 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1985 if (this === b) return true
1986 return Buffer.compare(this, b) === 0
1987}
1988
1989Buffer.prototype.inspect = function inspect () {
1990 var str = ''
1991 var max = exports.INSPECT_MAX_BYTES
1992 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
1993 if (this.length > max) str += ' ... '
1994 return '<Buffer ' + str + '>'
1995}
1996
1997Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1998 if (isInstance(target, Uint8Array)) {
1999 target = Buffer.from(target, target.offset, target.byteLength)
2000 }
2001 if (!Buffer.isBuffer(target)) {
2002 throw new TypeError(
2003 'The "target" argument must be one of type Buffer or Uint8Array. ' +
2004 'Received type ' + (typeof target)
2005 )
2006 }
2007
2008 if (start === undefined) {
2009 start = 0
2010 }
2011 if (end === undefined) {
2012 end = target ? target.length : 0
2013 }
2014 if (thisStart === undefined) {
2015 thisStart = 0
2016 }
2017 if (thisEnd === undefined) {
2018 thisEnd = this.length
2019 }
2020
2021 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2022 throw new RangeError('out of range index')
2023 }
2024
2025 if (thisStart >= thisEnd && start >= end) {
2026 return 0
2027 }
2028 if (thisStart >= thisEnd) {
2029 return -1
2030 }
2031 if (start >= end) {
2032 return 1
2033 }
2034
2035 start >>>= 0
2036 end >>>= 0
2037 thisStart >>>= 0
2038 thisEnd >>>= 0
2039
2040 if (this === target) return 0
2041
2042 var x = thisEnd - thisStart
2043 var y = end - start
2044 var len = Math.min(x, y)
2045
2046 var thisCopy = this.slice(thisStart, thisEnd)
2047 var targetCopy = target.slice(start, end)
2048
2049 for (var i = 0; i < len; ++i) {
2050 if (thisCopy[i] !== targetCopy[i]) {
2051 x = thisCopy[i]
2052 y = targetCopy[i]
2053 break
2054 }
2055 }
2056
2057 if (x < y) return -1
2058 if (y < x) return 1
2059 return 0
2060}
2061
2062// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2063// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2064//
2065// Arguments:
2066// - buffer - a Buffer to search
2067// - val - a string, Buffer, or number
2068// - byteOffset - an index into `buffer`; will be clamped to an int32
2069// - encoding - an optional encoding, relevant is val is a string
2070// - dir - true for indexOf, false for lastIndexOf
2071function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2072 // Empty buffer means no match
2073 if (buffer.length === 0) return -1
2074
2075 // Normalize byteOffset
2076 if (typeof byteOffset === 'string') {
2077 encoding = byteOffset
2078 byteOffset = 0
2079 } else if (byteOffset > 0x7fffffff) {
2080 byteOffset = 0x7fffffff
2081 } else if (byteOffset < -0x80000000) {
2082 byteOffset = -0x80000000
2083 }
2084 byteOffset = +byteOffset // Coerce to Number.
2085 if (numberIsNaN(byteOffset)) {
2086 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2087 byteOffset = dir ? 0 : (buffer.length - 1)
2088 }
2089
2090 // Normalize byteOffset: negative offsets start from the end of the buffer
2091 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2092 if (byteOffset >= buffer.length) {
2093 if (dir) return -1
2094 else byteOffset = buffer.length - 1
2095 } else if (byteOffset < 0) {
2096 if (dir) byteOffset = 0
2097 else return -1
2098 }
2099
2100 // Normalize val
2101 if (typeof val === 'string') {
2102 val = Buffer.from(val, encoding)
2103 }
2104
2105 // Finally, search either indexOf (if dir is true) or lastIndexOf
2106 if (Buffer.isBuffer(val)) {
2107 // Special case: looking for empty string/buffer always fails
2108 if (val.length === 0) {
2109 return -1
2110 }
2111 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2112 } else if (typeof val === 'number') {
2113 val = val & 0xFF // Search for a byte value [0-255]
2114 if (typeof Uint8Array.prototype.indexOf === 'function') {
2115 if (dir) {
2116 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2117 } else {
2118 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2119 }
2120 }
2121 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
2122 }
2123
2124 throw new TypeError('val must be string, number or Buffer')
2125}
2126
2127function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2128 var indexSize = 1
2129 var arrLength = arr.length
2130 var valLength = val.length
2131
2132 if (encoding !== undefined) {
2133 encoding = String(encoding).toLowerCase()
2134 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2135 encoding === 'utf16le' || encoding === 'utf-16le') {
2136 if (arr.length < 2 || val.length < 2) {
2137 return -1
2138 }
2139 indexSize = 2
2140 arrLength /= 2
2141 valLength /= 2
2142 byteOffset /= 2
2143 }
2144 }
2145
2146 function read (buf, i) {
2147 if (indexSize === 1) {
2148 return buf[i]
2149 } else {
2150 return buf.readUInt16BE(i * indexSize)
2151 }
2152 }
2153
2154 var i
2155 if (dir) {
2156 var foundIndex = -1
2157 for (i = byteOffset; i < arrLength; i++) {
2158 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2159 if (foundIndex === -1) foundIndex = i
2160 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2161 } else {
2162 if (foundIndex !== -1) i -= i - foundIndex
2163 foundIndex = -1
2164 }
2165 }
2166 } else {
2167 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2168 for (i = byteOffset; i >= 0; i--) {
2169 var found = true
2170 for (var j = 0; j < valLength; j++) {
2171 if (read(arr, i + j) !== read(val, j)) {
2172 found = false
2173 break
2174 }
2175 }
2176 if (found) return i
2177 }
2178 }
2179
2180 return -1
2181}
2182
2183Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2184 return this.indexOf(val, byteOffset, encoding) !== -1
2185}
2186
2187Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2188 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2189}
2190
2191Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2192 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2193}
2194
2195function hexWrite (buf, string, offset, length) {
2196 offset = Number(offset) || 0
2197 var remaining = buf.length - offset
2198 if (!length) {
2199 length = remaining
2200 } else {
2201 length = Number(length)
2202 if (length > remaining) {
2203 length = remaining
2204 }
2205 }
2206
2207 var strLen = string.length
2208
2209 if (length > strLen / 2) {
2210 length = strLen / 2
2211 }
2212 for (var i = 0; i < length; ++i) {
2213 var parsed = parseInt(string.substr(i * 2, 2), 16)
2214 if (numberIsNaN(parsed)) return i
2215 buf[offset + i] = parsed
2216 }
2217 return i
2218}
2219
2220function utf8Write (buf, string, offset, length) {
2221 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2222}
2223
2224function asciiWrite (buf, string, offset, length) {
2225 return blitBuffer(asciiToBytes(string), buf, offset, length)
2226}
2227
2228function latin1Write (buf, string, offset, length) {
2229 return asciiWrite(buf, string, offset, length)
2230}
2231
2232function base64Write (buf, string, offset, length) {
2233 return blitBuffer(base64ToBytes(string), buf, offset, length)
2234}
2235
2236function ucs2Write (buf, string, offset, length) {
2237 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2238}
2239
2240Buffer.prototype.write = function write (string, offset, length, encoding) {
2241 // Buffer#write(string)
2242 if (offset === undefined) {
2243 encoding = 'utf8'
2244 length = this.length
2245 offset = 0
2246 // Buffer#write(string, encoding)
2247 } else if (length === undefined && typeof offset === 'string') {
2248 encoding = offset
2249 length = this.length
2250 offset = 0
2251 // Buffer#write(string, offset[, length][, encoding])
2252 } else if (isFinite(offset)) {
2253 offset = offset >>> 0
2254 if (isFinite(length)) {
2255 length = length >>> 0
2256 if (encoding === undefined) encoding = 'utf8'
2257 } else {
2258 encoding = length
2259 length = undefined
2260 }
2261 } else {
2262 throw new Error(
2263 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2264 )
2265 }
2266
2267 var remaining = this.length - offset
2268 if (length === undefined || length > remaining) length = remaining
2269
2270 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2271 throw new RangeError('Attempt to write outside buffer bounds')
2272 }
2273
2274 if (!encoding) encoding = 'utf8'
2275
2276 var loweredCase = false
2277 for (;;) {
2278 switch (encoding) {
2279 case 'hex':
2280 return hexWrite(this, string, offset, length)
2281
2282 case 'utf8':
2283 case 'utf-8':
2284 return utf8Write(this, string, offset, length)
2285
2286 case 'ascii':
2287 return asciiWrite(this, string, offset, length)
2288
2289 case 'latin1':
2290 case 'binary':
2291 return latin1Write(this, string, offset, length)
2292
2293 case 'base64':
2294 // Warning: maxLength not taken into account in base64Write
2295 return base64Write(this, string, offset, length)
2296
2297 case 'ucs2':
2298 case 'ucs-2':
2299 case 'utf16le':
2300 case 'utf-16le':
2301 return ucs2Write(this, string, offset, length)
2302
2303 default:
2304 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2305 encoding = ('' + encoding).toLowerCase()
2306 loweredCase = true
2307 }
2308 }
2309}
2310
2311Buffer.prototype.toJSON = function toJSON () {
2312 return {
2313 type: 'Buffer',
2314 data: Array.prototype.slice.call(this._arr || this, 0)
2315 }
2316}
2317
2318function base64Slice (buf, start, end) {
2319 if (start === 0 && end === buf.length) {
2320 return base64.fromByteArray(buf)
2321 } else {
2322 return base64.fromByteArray(buf.slice(start, end))
2323 }
2324}
2325
2326function utf8Slice (buf, start, end) {
2327 end = Math.min(buf.length, end)
2328 var res = []
2329
2330 var i = start
2331 while (i < end) {
2332 var firstByte = buf[i]
2333 var codePoint = null
2334 var bytesPerSequence = (firstByte > 0xEF) ? 4
2335 : (firstByte > 0xDF) ? 3
2336 : (firstByte > 0xBF) ? 2
2337 : 1
2338
2339 if (i + bytesPerSequence <= end) {
2340 var secondByte, thirdByte, fourthByte, tempCodePoint
2341
2342 switch (bytesPerSequence) {
2343 case 1:
2344 if (firstByte < 0x80) {
2345 codePoint = firstByte
2346 }
2347 break
2348 case 2:
2349 secondByte = buf[i + 1]
2350 if ((secondByte & 0xC0) === 0x80) {
2351 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2352 if (tempCodePoint > 0x7F) {
2353 codePoint = tempCodePoint
2354 }
2355 }
2356 break
2357 case 3:
2358 secondByte = buf[i + 1]
2359 thirdByte = buf[i + 2]
2360 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2361 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2362 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2363 codePoint = tempCodePoint
2364 }
2365 }
2366 break
2367 case 4:
2368 secondByte = buf[i + 1]
2369 thirdByte = buf[i + 2]
2370 fourthByte = buf[i + 3]
2371 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2372 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2373 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2374 codePoint = tempCodePoint
2375 }
2376 }
2377 }
2378 }
2379
2380 if (codePoint === null) {
2381 // we did not generate a valid codePoint so insert a
2382 // replacement char (U+FFFD) and advance only 1 byte
2383 codePoint = 0xFFFD
2384 bytesPerSequence = 1
2385 } else if (codePoint > 0xFFFF) {
2386 // encode to utf16 (surrogate pair dance)
2387 codePoint -= 0x10000
2388 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2389 codePoint = 0xDC00 | codePoint & 0x3FF
2390 }
2391
2392 res.push(codePoint)
2393 i += bytesPerSequence
2394 }
2395
2396 return decodeCodePointsArray(res)
2397}
2398
2399// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2400// the lowest limit is Chrome, with 0x10000 args.
2401// We go 1 magnitude less, for safety
2402var MAX_ARGUMENTS_LENGTH = 0x1000
2403
2404function decodeCodePointsArray (codePoints) {
2405 var len = codePoints.length
2406 if (len <= MAX_ARGUMENTS_LENGTH) {
2407 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2408 }
2409
2410 // Decode in chunks to avoid "call stack size exceeded".
2411 var res = ''
2412 var i = 0
2413 while (i < len) {
2414 res += String.fromCharCode.apply(
2415 String,
2416 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2417 )
2418 }
2419 return res
2420}
2421
2422function asciiSlice (buf, start, end) {
2423 var ret = ''
2424 end = Math.min(buf.length, end)
2425
2426 for (var i = start; i < end; ++i) {
2427 ret += String.fromCharCode(buf[i] & 0x7F)
2428 }
2429 return ret
2430}
2431
2432function latin1Slice (buf, start, end) {
2433 var ret = ''
2434 end = Math.min(buf.length, end)
2435
2436 for (var i = start; i < end; ++i) {
2437 ret += String.fromCharCode(buf[i])
2438 }
2439 return ret
2440}
2441
2442function hexSlice (buf, start, end) {
2443 var len = buf.length
2444
2445 if (!start || start < 0) start = 0
2446 if (!end || end < 0 || end > len) end = len
2447
2448 var out = ''
2449 for (var i = start; i < end; ++i) {
2450 out += toHex(buf[i])
2451 }
2452 return out
2453}
2454
2455function utf16leSlice (buf, start, end) {
2456 var bytes = buf.slice(start, end)
2457 var res = ''
2458 for (var i = 0; i < bytes.length; i += 2) {
2459 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2460 }
2461 return res
2462}
2463
2464Buffer.prototype.slice = function slice (start, end) {
2465 var len = this.length
2466 start = ~~start
2467 end = end === undefined ? len : ~~end
2468
2469 if (start < 0) {
2470 start += len
2471 if (start < 0) start = 0
2472 } else if (start > len) {
2473 start = len
2474 }
2475
2476 if (end < 0) {
2477 end += len
2478 if (end < 0) end = 0
2479 } else if (end > len) {
2480 end = len
2481 }
2482
2483 if (end < start) end = start
2484
2485 var newBuf = this.subarray(start, end)
2486 // Return an augmented `Uint8Array` instance
2487 newBuf.__proto__ = Buffer.prototype
2488 return newBuf
2489}
2490
2491/*
2492 * Need to make sure that buffer isn't trying to write out of bounds.
2493 */
2494function checkOffset (offset, ext, length) {
2495 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2496 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2497}
2498
2499Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2500 offset = offset >>> 0
2501 byteLength = byteLength >>> 0
2502 if (!noAssert) checkOffset(offset, byteLength, this.length)
2503
2504 var val = this[offset]
2505 var mul = 1
2506 var i = 0
2507 while (++i < byteLength && (mul *= 0x100)) {
2508 val += this[offset + i] * mul
2509 }
2510
2511 return val
2512}
2513
2514Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2515 offset = offset >>> 0
2516 byteLength = byteLength >>> 0
2517 if (!noAssert) {
2518 checkOffset(offset, byteLength, this.length)
2519 }
2520
2521 var val = this[offset + --byteLength]
2522 var mul = 1
2523 while (byteLength > 0 && (mul *= 0x100)) {
2524 val += this[offset + --byteLength] * mul
2525 }
2526
2527 return val
2528}
2529
2530Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2531 offset = offset >>> 0
2532 if (!noAssert) checkOffset(offset, 1, this.length)
2533 return this[offset]
2534}
2535
2536Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2537 offset = offset >>> 0
2538 if (!noAssert) checkOffset(offset, 2, this.length)
2539 return this[offset] | (this[offset + 1] << 8)
2540}
2541
2542Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2543 offset = offset >>> 0
2544 if (!noAssert) checkOffset(offset, 2, this.length)
2545 return (this[offset] << 8) | this[offset + 1]
2546}
2547
2548Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2549 offset = offset >>> 0
2550 if (!noAssert) checkOffset(offset, 4, this.length)
2551
2552 return ((this[offset]) |
2553 (this[offset + 1] << 8) |
2554 (this[offset + 2] << 16)) +
2555 (this[offset + 3] * 0x1000000)
2556}
2557
2558Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2559 offset = offset >>> 0
2560 if (!noAssert) checkOffset(offset, 4, this.length)
2561
2562 return (this[offset] * 0x1000000) +
2563 ((this[offset + 1] << 16) |
2564 (this[offset + 2] << 8) |
2565 this[offset + 3])
2566}
2567
2568Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2569 offset = offset >>> 0
2570 byteLength = byteLength >>> 0
2571 if (!noAssert) checkOffset(offset, byteLength, this.length)
2572
2573 var val = this[offset]
2574 var mul = 1
2575 var i = 0
2576 while (++i < byteLength && (mul *= 0x100)) {
2577 val += this[offset + i] * mul
2578 }
2579 mul *= 0x80
2580
2581 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2582
2583 return val
2584}
2585
2586Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2587 offset = offset >>> 0
2588 byteLength = byteLength >>> 0
2589 if (!noAssert) checkOffset(offset, byteLength, this.length)
2590
2591 var i = byteLength
2592 var mul = 1
2593 var val = this[offset + --i]
2594 while (i > 0 && (mul *= 0x100)) {
2595 val += this[offset + --i] * mul
2596 }
2597 mul *= 0x80
2598
2599 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2600
2601 return val
2602}
2603
2604Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2605 offset = offset >>> 0
2606 if (!noAssert) checkOffset(offset, 1, this.length)
2607 if (!(this[offset] & 0x80)) return (this[offset])
2608 return ((0xff - this[offset] + 1) * -1)
2609}
2610
2611Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2612 offset = offset >>> 0
2613 if (!noAssert) checkOffset(offset, 2, this.length)
2614 var val = this[offset] | (this[offset + 1] << 8)
2615 return (val & 0x8000) ? val | 0xFFFF0000 : val
2616}
2617
2618Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2619 offset = offset >>> 0
2620 if (!noAssert) checkOffset(offset, 2, this.length)
2621 var val = this[offset + 1] | (this[offset] << 8)
2622 return (val & 0x8000) ? val | 0xFFFF0000 : val
2623}
2624
2625Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2626 offset = offset >>> 0
2627 if (!noAssert) checkOffset(offset, 4, this.length)
2628
2629 return (this[offset]) |
2630 (this[offset + 1] << 8) |
2631 (this[offset + 2] << 16) |
2632 (this[offset + 3] << 24)
2633}
2634
2635Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2636 offset = offset >>> 0
2637 if (!noAssert) checkOffset(offset, 4, this.length)
2638
2639 return (this[offset] << 24) |
2640 (this[offset + 1] << 16) |
2641 (this[offset + 2] << 8) |
2642 (this[offset + 3])
2643}
2644
2645Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2646 offset = offset >>> 0
2647 if (!noAssert) checkOffset(offset, 4, this.length)
2648 return ieee754.read(this, offset, true, 23, 4)
2649}
2650
2651Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
2652 offset = offset >>> 0
2653 if (!noAssert) checkOffset(offset, 4, this.length)
2654 return ieee754.read(this, offset, false, 23, 4)
2655}
2656
2657Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
2658 offset = offset >>> 0
2659 if (!noAssert) checkOffset(offset, 8, this.length)
2660 return ieee754.read(this, offset, true, 52, 8)
2661}
2662
2663Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
2664 offset = offset >>> 0
2665 if (!noAssert) checkOffset(offset, 8, this.length)
2666 return ieee754.read(this, offset, false, 52, 8)
2667}
2668
2669function checkInt (buf, value, offset, ext, max, min) {
2670 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
2671 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
2672 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2673}
2674
2675Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
2676 value = +value
2677 offset = offset >>> 0
2678 byteLength = byteLength >>> 0
2679 if (!noAssert) {
2680 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2681 checkInt(this, value, offset, byteLength, maxBytes, 0)
2682 }
2683
2684 var mul = 1
2685 var i = 0
2686 this[offset] = value & 0xFF
2687 while (++i < byteLength && (mul *= 0x100)) {
2688 this[offset + i] = (value / mul) & 0xFF
2689 }
2690
2691 return offset + byteLength
2692}
2693
2694Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2695 value = +value
2696 offset = offset >>> 0
2697 byteLength = byteLength >>> 0
2698 if (!noAssert) {
2699 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2700 checkInt(this, value, offset, byteLength, maxBytes, 0)
2701 }
2702
2703 var i = byteLength - 1
2704 var mul = 1
2705 this[offset + i] = value & 0xFF
2706 while (--i >= 0 && (mul *= 0x100)) {
2707 this[offset + i] = (value / mul) & 0xFF
2708 }
2709
2710 return offset + byteLength
2711}
2712
2713Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
2714 value = +value
2715 offset = offset >>> 0
2716 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
2717 this[offset] = (value & 0xff)
2718 return offset + 1
2719}
2720
2721Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2722 value = +value
2723 offset = offset >>> 0
2724 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2725 this[offset] = (value & 0xff)
2726 this[offset + 1] = (value >>> 8)
2727 return offset + 2
2728}
2729
2730Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2731 value = +value
2732 offset = offset >>> 0
2733 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2734 this[offset] = (value >>> 8)
2735 this[offset + 1] = (value & 0xff)
2736 return offset + 2
2737}
2738
2739Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2740 value = +value
2741 offset = offset >>> 0
2742 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2743 this[offset + 3] = (value >>> 24)
2744 this[offset + 2] = (value >>> 16)
2745 this[offset + 1] = (value >>> 8)
2746 this[offset] = (value & 0xff)
2747 return offset + 4
2748}
2749
2750Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2751 value = +value
2752 offset = offset >>> 0
2753 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2754 this[offset] = (value >>> 24)
2755 this[offset + 1] = (value >>> 16)
2756 this[offset + 2] = (value >>> 8)
2757 this[offset + 3] = (value & 0xff)
2758 return offset + 4
2759}
2760
2761Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2762 value = +value
2763 offset = offset >>> 0
2764 if (!noAssert) {
2765 var limit = Math.pow(2, (8 * byteLength) - 1)
2766
2767 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2768 }
2769
2770 var i = 0
2771 var mul = 1
2772 var sub = 0
2773 this[offset] = value & 0xFF
2774 while (++i < byteLength && (mul *= 0x100)) {
2775 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2776 sub = 1
2777 }
2778 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2779 }
2780
2781 return offset + byteLength
2782}
2783
2784Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2785 value = +value
2786 offset = offset >>> 0
2787 if (!noAssert) {
2788 var limit = Math.pow(2, (8 * byteLength) - 1)
2789
2790 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2791 }
2792
2793 var i = byteLength - 1
2794 var mul = 1
2795 var sub = 0
2796 this[offset + i] = value & 0xFF
2797 while (--i >= 0 && (mul *= 0x100)) {
2798 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2799 sub = 1
2800 }
2801 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2802 }
2803
2804 return offset + byteLength
2805}
2806
2807Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2808 value = +value
2809 offset = offset >>> 0
2810 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2811 if (value < 0) value = 0xff + value + 1
2812 this[offset] = (value & 0xff)
2813 return offset + 1
2814}
2815
2816Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2817 value = +value
2818 offset = offset >>> 0
2819 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2820 this[offset] = (value & 0xff)
2821 this[offset + 1] = (value >>> 8)
2822 return offset + 2
2823}
2824
2825Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2826 value = +value
2827 offset = offset >>> 0
2828 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2829 this[offset] = (value >>> 8)
2830 this[offset + 1] = (value & 0xff)
2831 return offset + 2
2832}
2833
2834Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2835 value = +value
2836 offset = offset >>> 0
2837 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2838 this[offset] = (value & 0xff)
2839 this[offset + 1] = (value >>> 8)
2840 this[offset + 2] = (value >>> 16)
2841 this[offset + 3] = (value >>> 24)
2842 return offset + 4
2843}
2844
2845Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2846 value = +value
2847 offset = offset >>> 0
2848 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2849 if (value < 0) value = 0xffffffff + value + 1
2850 this[offset] = (value >>> 24)
2851 this[offset + 1] = (value >>> 16)
2852 this[offset + 2] = (value >>> 8)
2853 this[offset + 3] = (value & 0xff)
2854 return offset + 4
2855}
2856
2857function checkIEEE754 (buf, value, offset, ext, max, min) {
2858 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2859 if (offset < 0) throw new RangeError('Index out of range')
2860}
2861
2862function writeFloat (buf, value, offset, littleEndian, noAssert) {
2863 value = +value
2864 offset = offset >>> 0
2865 if (!noAssert) {
2866 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2867 }
2868 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2869 return offset + 4
2870}
2871
2872Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2873 return writeFloat(this, value, offset, true, noAssert)
2874}
2875
2876Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2877 return writeFloat(this, value, offset, false, noAssert)
2878}
2879
2880function writeDouble (buf, value, offset, littleEndian, noAssert) {
2881 value = +value
2882 offset = offset >>> 0
2883 if (!noAssert) {
2884 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2885 }
2886 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2887 return offset + 8
2888}
2889
2890Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2891 return writeDouble(this, value, offset, true, noAssert)
2892}
2893
2894Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2895 return writeDouble(this, value, offset, false, noAssert)
2896}
2897
2898// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2899Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2900 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
2901 if (!start) start = 0
2902 if (!end && end !== 0) end = this.length
2903 if (targetStart >= target.length) targetStart = target.length
2904 if (!targetStart) targetStart = 0
2905 if (end > 0 && end < start) end = start
2906
2907 // Copy 0 bytes; we're done
2908 if (end === start) return 0
2909 if (target.length === 0 || this.length === 0) return 0
2910
2911 // Fatal error conditions
2912 if (targetStart < 0) {
2913 throw new RangeError('targetStart out of bounds')
2914 }
2915 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
2916 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2917
2918 // Are we oob?
2919 if (end > this.length) end = this.length
2920 if (target.length - targetStart < end - start) {
2921 end = target.length - targetStart + start
2922 }
2923
2924 var len = end - start
2925
2926 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
2927 // Use built-in when available, missing from IE11
2928 this.copyWithin(targetStart, start, end)
2929 } else if (this === target && start < targetStart && targetStart < end) {
2930 // descending copy from end
2931 for (var i = len - 1; i >= 0; --i) {
2932 target[i + targetStart] = this[i + start]
2933 }
2934 } else {
2935 Uint8Array.prototype.set.call(
2936 target,
2937 this.subarray(start, end),
2938 targetStart
2939 )
2940 }
2941
2942 return len
2943}
2944
2945// Usage:
2946// buffer.fill(number[, offset[, end]])
2947// buffer.fill(buffer[, offset[, end]])
2948// buffer.fill(string[, offset[, end]][, encoding])
2949Buffer.prototype.fill = function fill (val, start, end, encoding) {
2950 // Handle string cases:
2951 if (typeof val === 'string') {
2952 if (typeof start === 'string') {
2953 encoding = start
2954 start = 0
2955 end = this.length
2956 } else if (typeof end === 'string') {
2957 encoding = end
2958 end = this.length
2959 }
2960 if (encoding !== undefined && typeof encoding !== 'string') {
2961 throw new TypeError('encoding must be a string')
2962 }
2963 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2964 throw new TypeError('Unknown encoding: ' + encoding)
2965 }
2966 if (val.length === 1) {
2967 var code = val.charCodeAt(0)
2968 if ((encoding === 'utf8' && code < 128) ||
2969 encoding === 'latin1') {
2970 // Fast path: If `val` fits into a single byte, use that numeric value.
2971 val = code
2972 }
2973 }
2974 } else if (typeof val === 'number') {
2975 val = val & 255
2976 }
2977
2978 // Invalid ranges are not set to a default, so can range check early.
2979 if (start < 0 || this.length < start || this.length < end) {
2980 throw new RangeError('Out of range index')
2981 }
2982
2983 if (end <= start) {
2984 return this
2985 }
2986
2987 start = start >>> 0
2988 end = end === undefined ? this.length : end >>> 0
2989
2990 if (!val) val = 0
2991
2992 var i
2993 if (typeof val === 'number') {
2994 for (i = start; i < end; ++i) {
2995 this[i] = val
2996 }
2997 } else {
2998 var bytes = Buffer.isBuffer(val)
2999 ? val
3000 : Buffer.from(val, encoding)
3001 var len = bytes.length
3002 if (len === 0) {
3003 throw new TypeError('The value "' + val +
3004 '" is invalid for argument "value"')
3005 }
3006 for (i = 0; i < end - start; ++i) {
3007 this[i + start] = bytes[i % len]
3008 }
3009 }
3010
3011 return this
3012}
3013
3014// HELPER FUNCTIONS
3015// ================
3016
3017var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3018
3019function base64clean (str) {
3020 // Node takes equal signs as end of the Base64 encoding
3021 str = str.split('=')[0]
3022 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3023 str = str.trim().replace(INVALID_BASE64_RE, '')
3024 // Node converts strings with length < 2 to ''
3025 if (str.length < 2) return ''
3026 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3027 while (str.length % 4 !== 0) {
3028 str = str + '='
3029 }
3030 return str
3031}
3032
3033function toHex (n) {
3034 if (n < 16) return '0' + n.toString(16)
3035 return n.toString(16)
3036}
3037
3038function utf8ToBytes (string, units) {
3039 units = units || Infinity
3040 var codePoint
3041 var length = string.length
3042 var leadSurrogate = null
3043 var bytes = []
3044
3045 for (var i = 0; i < length; ++i) {
3046 codePoint = string.charCodeAt(i)
3047
3048 // is surrogate component
3049 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3050 // last char was a lead
3051 if (!leadSurrogate) {
3052 // no lead yet
3053 if (codePoint > 0xDBFF) {
3054 // unexpected trail
3055 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3056 continue
3057 } else if (i + 1 === length) {
3058 // unpaired lead
3059 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3060 continue
3061 }
3062
3063 // valid lead
3064 leadSurrogate = codePoint
3065
3066 continue
3067 }
3068
3069 // 2 leads in a row
3070 if (codePoint < 0xDC00) {
3071 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3072 leadSurrogate = codePoint
3073 continue
3074 }
3075
3076 // valid surrogate pair
3077 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3078 } else if (leadSurrogate) {
3079 // valid bmp char, but last char was a lead
3080 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3081 }
3082
3083 leadSurrogate = null
3084
3085 // encode utf8
3086 if (codePoint < 0x80) {
3087 if ((units -= 1) < 0) break
3088 bytes.push(codePoint)
3089 } else if (codePoint < 0x800) {
3090 if ((units -= 2) < 0) break
3091 bytes.push(
3092 codePoint >> 0x6 | 0xC0,
3093 codePoint & 0x3F | 0x80
3094 )
3095 } else if (codePoint < 0x10000) {
3096 if ((units -= 3) < 0) break
3097 bytes.push(
3098 codePoint >> 0xC | 0xE0,
3099 codePoint >> 0x6 & 0x3F | 0x80,
3100 codePoint & 0x3F | 0x80
3101 )
3102 } else if (codePoint < 0x110000) {
3103 if ((units -= 4) < 0) break
3104 bytes.push(
3105 codePoint >> 0x12 | 0xF0,
3106 codePoint >> 0xC & 0x3F | 0x80,
3107 codePoint >> 0x6 & 0x3F | 0x80,
3108 codePoint & 0x3F | 0x80
3109 )
3110 } else {
3111 throw new Error('Invalid code point')
3112 }
3113 }
3114
3115 return bytes
3116}
3117
3118function asciiToBytes (str) {
3119 var byteArray = []
3120 for (var i = 0; i < str.length; ++i) {
3121 // Node's code seems to be doing this and not & 0x7F..
3122 byteArray.push(str.charCodeAt(i) & 0xFF)
3123 }
3124 return byteArray
3125}
3126
3127function utf16leToBytes (str, units) {
3128 var c, hi, lo
3129 var byteArray = []
3130 for (var i = 0; i < str.length; ++i) {
3131 if ((units -= 2) < 0) break
3132
3133 c = str.charCodeAt(i)
3134 hi = c >> 8
3135 lo = c % 256
3136 byteArray.push(lo)
3137 byteArray.push(hi)
3138 }
3139
3140 return byteArray
3141}
3142
3143function base64ToBytes (str) {
3144 return base64.toByteArray(base64clean(str))
3145}
3146
3147function blitBuffer (src, dst, offset, length) {
3148 for (var i = 0; i < length; ++i) {
3149 if ((i + offset >= dst.length) || (i >= src.length)) break
3150 dst[i + offset] = src[i]
3151 }
3152 return i
3153}
3154
3155// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
3156// the `instanceof` check but they should be treated as of that type.
3157// See: https://github.com/feross/buffer/issues/166
3158function isInstance (obj, type) {
3159 return obj instanceof type ||
3160 (obj != null && obj.constructor != null && obj.constructor.name != null &&
3161 obj.constructor.name === type.name)
3162}
3163function numberIsNaN (obj) {
3164 // For IE11 support
3165 return obj !== obj // eslint-disable-line no-self-compare
3166}
3167
3168}).call(this,_dereq_(9).Buffer)
3169},{"23":23,"6":6,"9":9}],10:[function(_dereq_,module,exports){
3170(function (Buffer){
3171// Copyright Joyent, Inc. and other Node contributors.
3172//
3173// Permission is hereby granted, free of charge, to any person obtaining a
3174// copy of this software and associated documentation files (the
3175// "Software"), to deal in the Software without restriction, including
3176// without limitation the rights to use, copy, modify, merge, publish,
3177// distribute, sublicense, and/or sell copies of the Software, and to permit
3178// persons to whom the Software is furnished to do so, subject to the
3179// following conditions:
3180//
3181// The above copyright notice and this permission notice shall be included
3182// in all copies or substantial portions of the Software.
3183//
3184// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3185// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3186// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3187// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3188// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3189// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3190// USE OR OTHER DEALINGS IN THE SOFTWARE.
3191
3192// NOTE: These type checking functions intentionally don't use `instanceof`
3193// because it is fragile and can be easily faked with `Object.create()`.
3194
3195function isArray(arg) {
3196 if (Array.isArray) {
3197 return Array.isArray(arg);
3198 }
3199 return objectToString(arg) === '[object Array]';
3200}
3201exports.isArray = isArray;
3202
3203function isBoolean(arg) {
3204 return typeof arg === 'boolean';
3205}
3206exports.isBoolean = isBoolean;
3207
3208function isNull(arg) {
3209 return arg === null;
3210}
3211exports.isNull = isNull;
3212
3213function isNullOrUndefined(arg) {
3214 return arg == null;
3215}
3216exports.isNullOrUndefined = isNullOrUndefined;
3217
3218function isNumber(arg) {
3219 return typeof arg === 'number';
3220}
3221exports.isNumber = isNumber;
3222
3223function isString(arg) {
3224 return typeof arg === 'string';
3225}
3226exports.isString = isString;
3227
3228function isSymbol(arg) {
3229 return typeof arg === 'symbol';
3230}
3231exports.isSymbol = isSymbol;
3232
3233function isUndefined(arg) {
3234 return arg === void 0;
3235}
3236exports.isUndefined = isUndefined;
3237
3238function isRegExp(re) {
3239 return objectToString(re) === '[object RegExp]';
3240}
3241exports.isRegExp = isRegExp;
3242
3243function isObject(arg) {
3244 return typeof arg === 'object' && arg !== null;
3245}
3246exports.isObject = isObject;
3247
3248function isDate(d) {
3249 return objectToString(d) === '[object Date]';
3250}
3251exports.isDate = isDate;
3252
3253function isError(e) {
3254 return (objectToString(e) === '[object Error]' || e instanceof Error);
3255}
3256exports.isError = isError;
3257
3258function isFunction(arg) {
3259 return typeof arg === 'function';
3260}
3261exports.isFunction = isFunction;
3262
3263function isPrimitive(arg) {
3264 return arg === null ||
3265 typeof arg === 'boolean' ||
3266 typeof arg === 'number' ||
3267 typeof arg === 'string' ||
3268 typeof arg === 'symbol' || // ES6 symbol
3269 typeof arg === 'undefined';
3270}
3271exports.isPrimitive = isPrimitive;
3272
3273exports.isBuffer = Buffer.isBuffer;
3274
3275function objectToString(o) {
3276 return Object.prototype.toString.call(o);
3277}
3278
3279}).call(this,{"isBuffer":_dereq_(26)})
3280},{"26":26}],11:[function(_dereq_,module,exports){
3281var AbstractIterator = _dereq_(16).AbstractIterator
3282var inherits = _dereq_(25)
3283
3284function DeferredIterator (options) {
3285 AbstractIterator.call(this, options)
3286
3287 this._options = options
3288 this._iterator = null
3289 this._operations = []
3290}
3291
3292inherits(DeferredIterator, AbstractIterator)
3293
3294DeferredIterator.prototype.setDb = function (db) {
3295 var it = this._iterator = db.iterator(this._options)
3296 this._operations.forEach(function (op) {
3297 it[op.method].apply(it, op.args)
3298 })
3299}
3300
3301DeferredIterator.prototype._operation = function (method, args) {
3302 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
3303 this._operations.push({ method: method, args: args })
3304}
3305
3306'next end'.split(' ').forEach(function (m) {
3307 DeferredIterator.prototype['_' + m] = function () {
3308 this._operation(m, arguments)
3309 }
3310})
3311
3312module.exports = DeferredIterator
3313
3314},{"16":16,"25":25}],12:[function(_dereq_,module,exports){
3315var AbstractLevelDOWN = _dereq_(16).AbstractLevelDOWN
3316var inherits = _dereq_(25)
3317var DeferredIterator = _dereq_(11)
3318var deferrables = 'put get del batch'.split(' ')
3319
3320function DeferredLevelDOWN (db) {
3321 AbstractLevelDOWN.call(this, '')
3322 this._db = db
3323 this._operations = []
3324 this._iterators = []
3325 closed(this)
3326}
3327
3328inherits(DeferredLevelDOWN, AbstractLevelDOWN)
3329
3330DeferredLevelDOWN.prototype._open = function (options, callback) {
3331 var self = this
3332
3333 this._db.open(options, function (err) {
3334 if (err) return callback(err)
3335
3336 self._operations.forEach(function (op) {
3337 self._db[op.method].apply(self._db, op.args)
3338 })
3339 self._operations = []
3340 self._iterators.forEach(function (it) {
3341 it.setDb(self._db)
3342 })
3343 self._iterators = []
3344 open(self)
3345 callback()
3346 })
3347}
3348
3349DeferredLevelDOWN.prototype._close = function (callback) {
3350 var self = this
3351
3352 this._db.close(function (err) {
3353 if (err) return callback(err)
3354 closed(self)
3355 callback()
3356 })
3357}
3358
3359function open (self) {
3360 deferrables.concat('iterator').forEach(function (m) {
3361 self['_' + m] = function () {
3362 return this._db[m].apply(this._db, arguments)
3363 }
3364 })
3365 if (self._db.approximateSize) {
3366 self.approximateSize = function () {
3367 return this._db.approximateSize.apply(this._db, arguments)
3368 }
3369 }
3370}
3371
3372function closed (self) {
3373 deferrables.forEach(function (m) {
3374 self['_' + m] = function () {
3375 this._operations.push({ method: m, args: arguments })
3376 }
3377 })
3378 if (typeof self._db.approximateSize === 'function') {
3379 self.approximateSize = function () {
3380 this._operations.push({
3381 method: 'approximateSize',
3382 args: arguments
3383 })
3384 }
3385 }
3386 self._iterator = function (options) {
3387 var it = new DeferredIterator(options)
3388 this._iterators.push(it)
3389 return it
3390 }
3391}
3392
3393DeferredLevelDOWN.prototype._serializeKey = function (key) {
3394 return key
3395}
3396
3397DeferredLevelDOWN.prototype._serializeValue = function (value) {
3398 return value
3399}
3400
3401module.exports = DeferredLevelDOWN
3402module.exports.DeferredIterator = DeferredIterator
3403
3404},{"11":11,"16":16,"25":25}],13:[function(_dereq_,module,exports){
3405function AbstractChainedBatch (db) {
3406 if (typeof db !== 'object' || db === null) {
3407 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3408 }
3409
3410 this.db = db
3411 this._operations = []
3412 this._written = false
3413}
3414
3415AbstractChainedBatch.prototype._checkWritten = function () {
3416 if (this._written) {
3417 throw new Error('write() already called on this batch')
3418 }
3419}
3420
3421AbstractChainedBatch.prototype.put = function (key, value) {
3422 this._checkWritten()
3423
3424 var err = this.db._checkKey(key) || this.db._checkValue(value)
3425 if (err) throw err
3426
3427 key = this.db._serializeKey(key)
3428 value = this.db._serializeValue(value)
3429
3430 this._put(key, value)
3431
3432 return this
3433}
3434
3435AbstractChainedBatch.prototype._put = function (key, value) {
3436 this._operations.push({ type: 'put', key: key, value: value })
3437}
3438
3439AbstractChainedBatch.prototype.del = function (key) {
3440 this._checkWritten()
3441
3442 var err = this.db._checkKey(key)
3443 if (err) throw err
3444
3445 key = this.db._serializeKey(key)
3446 this._del(key)
3447
3448 return this
3449}
3450
3451AbstractChainedBatch.prototype._del = function (key) {
3452 this._operations.push({ type: 'del', key: key })
3453}
3454
3455AbstractChainedBatch.prototype.clear = function () {
3456 this._checkWritten()
3457 this._clear()
3458
3459 return this
3460}
3461
3462AbstractChainedBatch.prototype._clear = function () {
3463 this._operations = []
3464}
3465
3466AbstractChainedBatch.prototype.write = function (options, callback) {
3467 this._checkWritten()
3468
3469 if (typeof options === 'function') { callback = options }
3470 if (typeof callback !== 'function') {
3471 throw new Error('write() requires a callback argument')
3472 }
3473 if (typeof options !== 'object' || options === null) {
3474 options = {}
3475 }
3476
3477 this._written = true
3478 this._write(options, callback)
3479}
3480
3481AbstractChainedBatch.prototype._write = function (options, callback) {
3482 this.db._batch(this._operations, options, callback)
3483}
3484
3485module.exports = AbstractChainedBatch
3486
3487},{}],14:[function(_dereq_,module,exports){
3488(function (process){
3489function AbstractIterator (db) {
3490 if (typeof db !== 'object' || db === null) {
3491 throw new TypeError('First argument must be an abstract-leveldown compliant store')
3492 }
3493
3494 this.db = db
3495 this._ended = false
3496 this._nexting = false
3497}
3498
3499AbstractIterator.prototype.next = function (callback) {
3500 var self = this
3501
3502 if (typeof callback !== 'function') {
3503 throw new Error('next() requires a callback argument')
3504 }
3505
3506 if (self._ended) {
3507 process.nextTick(callback, new Error('cannot call next() after end()'))
3508 return self
3509 }
3510
3511 if (self._nexting) {
3512 process.nextTick(callback, new Error('cannot call next() before previous next() has completed'))
3513 return self
3514 }
3515
3516 self._nexting = true
3517 self._next(function () {
3518 self._nexting = false
3519 callback.apply(null, arguments)
3520 })
3521
3522 return self
3523}
3524
3525AbstractIterator.prototype._next = function (callback) {
3526 process.nextTick(callback)
3527}
3528
3529AbstractIterator.prototype.seek = function (target) {
3530 if (this._ended) {
3531 throw new Error('cannot call seek() after end()')
3532 }
3533 if (this._nexting) {
3534 throw new Error('cannot call seek() before next() has completed')
3535 }
3536
3537 target = this.db._serializeKey(target)
3538 this._seek(target)
3539}
3540
3541AbstractIterator.prototype._seek = function (target) {}
3542
3543AbstractIterator.prototype.end = function (callback) {
3544 if (typeof callback !== 'function') {
3545 throw new Error('end() requires a callback argument')
3546 }
3547
3548 if (this._ended) {
3549 return process.nextTick(callback, new Error('end() already called on iterator'))
3550 }
3551
3552 this._ended = true
3553 this._end(callback)
3554}
3555
3556AbstractIterator.prototype._end = function (callback) {
3557 process.nextTick(callback)
3558}
3559
3560module.exports = AbstractIterator
3561
3562}).call(this,_dereq_(71))
3563},{"71":71}],15:[function(_dereq_,module,exports){
3564(function (Buffer,process){
3565var xtend = _dereq_(17)
3566var AbstractIterator = _dereq_(14)
3567var AbstractChainedBatch = _dereq_(13)
3568var hasOwnProperty = Object.prototype.hasOwnProperty
3569var rangeOptions = 'start end gt gte lt lte'.split(' ')
3570
3571function AbstractLevelDOWN () {
3572 this.status = 'new'
3573}
3574
3575AbstractLevelDOWN.prototype.open = function (options, callback) {
3576 var self = this
3577 var oldStatus = this.status
3578
3579 if (typeof options === 'function') callback = options
3580
3581 if (typeof callback !== 'function') {
3582 throw new Error('open() requires a callback argument')
3583 }
3584
3585 if (typeof options !== 'object' || options === null) options = {}
3586
3587 options.createIfMissing = options.createIfMissing !== false
3588 options.errorIfExists = !!options.errorIfExists
3589
3590 this.status = 'opening'
3591 this._open(options, function (err) {
3592 if (err) {
3593 self.status = oldStatus
3594 return callback(err)
3595 }
3596 self.status = 'open'
3597 callback()
3598 })
3599}
3600
3601AbstractLevelDOWN.prototype._open = function (options, callback) {
3602 process.nextTick(callback)
3603}
3604
3605AbstractLevelDOWN.prototype.close = function (callback) {
3606 var self = this
3607 var oldStatus = this.status
3608
3609 if (typeof callback !== 'function') {
3610 throw new Error('close() requires a callback argument')
3611 }
3612
3613 this.status = 'closing'
3614 this._close(function (err) {
3615 if (err) {
3616 self.status = oldStatus
3617 return callback(err)
3618 }
3619 self.status = 'closed'
3620 callback()
3621 })
3622}
3623
3624AbstractLevelDOWN.prototype._close = function (callback) {
3625 process.nextTick(callback)
3626}
3627
3628AbstractLevelDOWN.prototype.get = function (key, options, callback) {
3629 if (typeof options === 'function') callback = options
3630
3631 if (typeof callback !== 'function') {
3632 throw new Error('get() requires a callback argument')
3633 }
3634
3635 var err = this._checkKey(key)
3636 if (err) return process.nextTick(callback, err)
3637
3638 key = this._serializeKey(key)
3639
3640 if (typeof options !== 'object' || options === null) options = {}
3641
3642 options.asBuffer = options.asBuffer !== false
3643
3644 this._get(key, options, callback)
3645}
3646
3647AbstractLevelDOWN.prototype._get = function (key, options, callback) {
3648 process.nextTick(function () { callback(new Error('NotFound')) })
3649}
3650
3651AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
3652 if (typeof options === 'function') callback = options
3653
3654 if (typeof callback !== 'function') {
3655 throw new Error('put() requires a callback argument')
3656 }
3657
3658 var err = this._checkKey(key) || this._checkValue(value)
3659 if (err) return process.nextTick(callback, err)
3660
3661 key = this._serializeKey(key)
3662 value = this._serializeValue(value)
3663
3664 if (typeof options !== 'object' || options === null) options = {}
3665
3666 this._put(key, value, options, callback)
3667}
3668
3669AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
3670 process.nextTick(callback)
3671}
3672
3673AbstractLevelDOWN.prototype.del = function (key, options, callback) {
3674 if (typeof options === 'function') callback = options
3675
3676 if (typeof callback !== 'function') {
3677 throw new Error('del() requires a callback argument')
3678 }
3679
3680 var err = this._checkKey(key)
3681 if (err) return process.nextTick(callback, err)
3682
3683 key = this._serializeKey(key)
3684
3685 if (typeof options !== 'object' || options === null) options = {}
3686
3687 this._del(key, options, callback)
3688}
3689
3690AbstractLevelDOWN.prototype._del = function (key, options, callback) {
3691 process.nextTick(callback)
3692}
3693
3694AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
3695 if (!arguments.length) return this._chainedBatch()
3696
3697 if (typeof options === 'function') callback = options
3698
3699 if (typeof array === 'function') callback = array
3700
3701 if (typeof callback !== 'function') {
3702 throw new Error('batch(array) requires a callback argument')
3703 }
3704
3705 if (!Array.isArray(array)) {
3706 return process.nextTick(callback, new Error('batch(array) requires an array argument'))
3707 }
3708
3709 if (array.length === 0) {
3710 return process.nextTick(callback)
3711 }
3712
3713 if (typeof options !== 'object' || options === null) options = {}
3714
3715 var serialized = new Array(array.length)
3716
3717 for (var i = 0; i < array.length; i++) {
3718 if (typeof array[i] !== 'object' || array[i] === null) {
3719 return process.nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
3720 }
3721
3722 var e = xtend(array[i])
3723
3724 if (e.type !== 'put' && e.type !== 'del') {
3725 return process.nextTick(callback, new Error("`type` must be 'put' or 'del'"))
3726 }
3727
3728 var err = this._checkKey(e.key)
3729 if (err) return process.nextTick(callback, err)
3730
3731 e.key = this._serializeKey(e.key)
3732
3733 if (e.type === 'put') {
3734 var valueErr = this._checkValue(e.value)
3735 if (valueErr) return process.nextTick(callback, valueErr)
3736
3737 e.value = this._serializeValue(e.value)
3738 }
3739
3740 serialized[i] = e
3741 }
3742
3743 this._batch(serialized, options, callback)
3744}
3745
3746AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
3747 process.nextTick(callback)
3748}
3749
3750AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
3751 options = cleanRangeOptions(this, options)
3752
3753 options.reverse = !!options.reverse
3754 options.keys = options.keys !== false
3755 options.values = options.values !== false
3756 options.limit = 'limit' in options ? options.limit : -1
3757 options.keyAsBuffer = options.keyAsBuffer !== false
3758 options.valueAsBuffer = options.valueAsBuffer !== false
3759
3760 return options
3761}
3762
3763function cleanRangeOptions (db, options) {
3764 var result = {}
3765
3766 for (var k in options) {
3767 if (!hasOwnProperty.call(options, k)) continue
3768
3769 var opt = options[k]
3770
3771 if (isRangeOption(k)) {
3772 // Note that we don't reject nullish and empty options here. While
3773 // those types are invalid as keys, they are valid as range options.
3774 opt = db._serializeKey(opt)
3775 }
3776
3777 result[k] = opt
3778 }
3779
3780 return result
3781}
3782
3783function isRangeOption (k) {
3784 return rangeOptions.indexOf(k) !== -1
3785}
3786
3787AbstractLevelDOWN.prototype.iterator = function (options) {
3788 if (typeof options !== 'object' || options === null) options = {}
3789 options = this._setupIteratorOptions(options)
3790 return this._iterator(options)
3791}
3792
3793AbstractLevelDOWN.prototype._iterator = function (options) {
3794 return new AbstractIterator(this)
3795}
3796
3797AbstractLevelDOWN.prototype._chainedBatch = function () {
3798 return new AbstractChainedBatch(this)
3799}
3800
3801AbstractLevelDOWN.prototype._serializeKey = function (key) {
3802 return key
3803}
3804
3805AbstractLevelDOWN.prototype._serializeValue = function (value) {
3806 return value
3807}
3808
3809AbstractLevelDOWN.prototype._checkKey = function (key) {
3810 if (key === null || key === undefined) {
3811 return new Error('key cannot be `null` or `undefined`')
3812 } else if (Buffer.isBuffer(key) && key.length === 0) {
3813 return new Error('key cannot be an empty Buffer')
3814 } else if (key === '') {
3815 return new Error('key cannot be an empty String')
3816 } else if (Array.isArray(key) && key.length === 0) {
3817 return new Error('key cannot be an empty Array')
3818 }
3819}
3820
3821AbstractLevelDOWN.prototype._checkValue = function (value) {
3822 if (value === null || value === undefined) {
3823 return new Error('value cannot be `null` or `undefined`')
3824 }
3825}
3826
3827module.exports = AbstractLevelDOWN
3828
3829}).call(this,{"isBuffer":_dereq_(26)},_dereq_(71))
3830},{"13":13,"14":14,"17":17,"26":26,"71":71}],16:[function(_dereq_,module,exports){
3831exports.AbstractLevelDOWN = _dereq_(15)
3832exports.AbstractIterator = _dereq_(14)
3833exports.AbstractChainedBatch = _dereq_(13)
3834
3835},{"13":13,"14":14,"15":15}],17:[function(_dereq_,module,exports){
3836module.exports = extend
3837
3838var hasOwnProperty = Object.prototype.hasOwnProperty;
3839
3840function extend() {
3841 var target = {}
3842
3843 for (var i = 0; i < arguments.length; i++) {
3844 var source = arguments[i]
3845
3846 for (var key in source) {
3847 if (hasOwnProperty.call(source, key)) {
3848 target[key] = source[key]
3849 }
3850 }
3851 }
3852
3853 return target
3854}
3855
3856},{}],18:[function(_dereq_,module,exports){
3857/**
3858 * Copyright (c) 2013 Petka Antonov
3859 *
3860 * Permission is hereby granted, free of charge, to any person obtaining a copy
3861 * of this software and associated documentation files (the "Software"), to deal
3862 * in the Software without restriction, including without limitation the rights
3863 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3864 * copies of the Software, and to permit persons to whom the Software is
3865 * furnished to do so, subject to the following conditions:</p>
3866 *
3867 * The above copyright notice and this permission notice shall be included in
3868 * all copies or substantial portions of the Software.
3869 *
3870 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3871 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3872 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3873 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3874 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3875 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3876 * THE SOFTWARE.
3877 */
3878"use strict";
3879function Deque(capacity) {
3880 this._capacity = getCapacity(capacity);
3881 this._length = 0;
3882 this._front = 0;
3883 if (isArray(capacity)) {
3884 var len = capacity.length;
3885 for (var i = 0; i < len; ++i) {
3886 this[i] = capacity[i];
3887 }
3888 this._length = len;
3889 }
3890}
3891
3892Deque.prototype.toArray = function Deque$toArray() {
3893 var len = this._length;
3894 var ret = new Array(len);
3895 var front = this._front;
3896 var capacity = this._capacity;
3897 for (var j = 0; j < len; ++j) {
3898 ret[j] = this[(front + j) & (capacity - 1)];
3899 }
3900 return ret;
3901};
3902
3903Deque.prototype.push = function Deque$push(item) {
3904 var argsLength = arguments.length;
3905 var length = this._length;
3906 if (argsLength > 1) {
3907 var capacity = this._capacity;
3908 if (length + argsLength > capacity) {
3909 for (var i = 0; i < argsLength; ++i) {
3910 this._checkCapacity(length + 1);
3911 var j = (this._front + length) & (this._capacity - 1);
3912 this[j] = arguments[i];
3913 length++;
3914 this._length = length;
3915 }
3916 return length;
3917 }
3918 else {
3919 var j = this._front;
3920 for (var i = 0; i < argsLength; ++i) {
3921 this[(j + length) & (capacity - 1)] = arguments[i];
3922 j++;
3923 }
3924 this._length = length + argsLength;
3925 return length + argsLength;
3926 }
3927
3928 }
3929
3930 if (argsLength === 0) return length;
3931
3932 this._checkCapacity(length + 1);
3933 var i = (this._front + length) & (this._capacity - 1);
3934 this[i] = item;
3935 this._length = length + 1;
3936 return length + 1;
3937};
3938
3939Deque.prototype.pop = function Deque$pop() {
3940 var length = this._length;
3941 if (length === 0) {
3942 return void 0;
3943 }
3944 var i = (this._front + length - 1) & (this._capacity - 1);
3945 var ret = this[i];
3946 this[i] = void 0;
3947 this._length = length - 1;
3948 return ret;
3949};
3950
3951Deque.prototype.shift = function Deque$shift() {
3952 var length = this._length;
3953 if (length === 0) {
3954 return void 0;
3955 }
3956 var front = this._front;
3957 var ret = this[front];
3958 this[front] = void 0;
3959 this._front = (front + 1) & (this._capacity - 1);
3960 this._length = length - 1;
3961 return ret;
3962};
3963
3964Deque.prototype.unshift = function Deque$unshift(item) {
3965 var length = this._length;
3966 var argsLength = arguments.length;
3967
3968
3969 if (argsLength > 1) {
3970 var capacity = this._capacity;
3971 if (length + argsLength > capacity) {
3972 for (var i = argsLength - 1; i >= 0; i--) {
3973 this._checkCapacity(length + 1);
3974 var capacity = this._capacity;
3975 var j = (((( this._front - 1 ) &
3976 ( capacity - 1) ) ^ capacity ) - capacity );
3977 this[j] = arguments[i];
3978 length++;
3979 this._length = length;
3980 this._front = j;
3981 }
3982 return length;
3983 }
3984 else {
3985 var front = this._front;
3986 for (var i = argsLength - 1; i >= 0; i--) {
3987 var j = (((( front - 1 ) &
3988 ( capacity - 1) ) ^ capacity ) - capacity );
3989 this[j] = arguments[i];
3990 front = j;
3991 }
3992 this._front = front;
3993 this._length = length + argsLength;
3994 return length + argsLength;
3995 }
3996 }
3997
3998 if (argsLength === 0) return length;
3999
4000 this._checkCapacity(length + 1);
4001 var capacity = this._capacity;
4002 var i = (((( this._front - 1 ) &
4003 ( capacity - 1) ) ^ capacity ) - capacity );
4004 this[i] = item;
4005 this._length = length + 1;
4006 this._front = i;
4007 return length + 1;
4008};
4009
4010Deque.prototype.peekBack = function Deque$peekBack() {
4011 var length = this._length;
4012 if (length === 0) {
4013 return void 0;
4014 }
4015 var index = (this._front + length - 1) & (this._capacity - 1);
4016 return this[index];
4017};
4018
4019Deque.prototype.peekFront = function Deque$peekFront() {
4020 if (this._length === 0) {
4021 return void 0;
4022 }
4023 return this[this._front];
4024};
4025
4026Deque.prototype.get = function Deque$get(index) {
4027 var i = index;
4028 if ((i !== (i | 0))) {
4029 return void 0;
4030 }
4031 var len = this._length;
4032 if (i < 0) {
4033 i = i + len;
4034 }
4035 if (i < 0 || i >= len) {
4036 return void 0;
4037 }
4038 return this[(this._front + i) & (this._capacity - 1)];
4039};
4040
4041Deque.prototype.isEmpty = function Deque$isEmpty() {
4042 return this._length === 0;
4043};
4044
4045Deque.prototype.clear = function Deque$clear() {
4046 var len = this._length;
4047 var front = this._front;
4048 var capacity = this._capacity;
4049 for (var j = 0; j < len; ++j) {
4050 this[(front + j) & (capacity - 1)] = void 0;
4051 }
4052 this._length = 0;
4053 this._front = 0;
4054};
4055
4056Deque.prototype.toString = function Deque$toString() {
4057 return this.toArray().toString();
4058};
4059
4060Deque.prototype.valueOf = Deque.prototype.toString;
4061Deque.prototype.removeFront = Deque.prototype.shift;
4062Deque.prototype.removeBack = Deque.prototype.pop;
4063Deque.prototype.insertFront = Deque.prototype.unshift;
4064Deque.prototype.insertBack = Deque.prototype.push;
4065Deque.prototype.enqueue = Deque.prototype.push;
4066Deque.prototype.dequeue = Deque.prototype.shift;
4067Deque.prototype.toJSON = Deque.prototype.toArray;
4068
4069Object.defineProperty(Deque.prototype, "length", {
4070 get: function() {
4071 return this._length;
4072 },
4073 set: function() {
4074 throw new RangeError("");
4075 }
4076});
4077
4078Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
4079 if (this._capacity < size) {
4080 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
4081 }
4082};
4083
4084Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
4085 var oldCapacity = this._capacity;
4086 this._capacity = capacity;
4087 var front = this._front;
4088 var length = this._length;
4089 if (front + length > oldCapacity) {
4090 var moveItemsCount = (front + length) & (oldCapacity - 1);
4091 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4092 }
4093};
4094
4095
4096var isArray = Array.isArray;
4097
4098function arrayMove(src, srcIndex, dst, dstIndex, len) {
4099 for (var j = 0; j < len; ++j) {
4100 dst[j + dstIndex] = src[j + srcIndex];
4101 src[j + srcIndex] = void 0;
4102 }
4103}
4104
4105function pow2AtLeast(n) {
4106 n = n >>> 0;
4107 n = n - 1;
4108 n = n | (n >> 1);
4109 n = n | (n >> 2);
4110 n = n | (n >> 4);
4111 n = n | (n >> 8);
4112 n = n | (n >> 16);
4113 return n + 1;
4114}
4115
4116function getCapacity(capacity) {
4117 if (typeof capacity !== "number") {
4118 if (isArray(capacity)) {
4119 capacity = capacity.length;
4120 }
4121 else {
4122 return 16;
4123 }
4124 }
4125 return pow2AtLeast(
4126 Math.min(
4127 Math.max(16, capacity), 1073741824)
4128 );
4129}
4130
4131module.exports = Deque;
4132
4133},{}],19:[function(_dereq_,module,exports){
4134var prr = _dereq_(72)
4135
4136function init (type, message, cause) {
4137 if (!!message && typeof message != 'string') {
4138 message = message.message || message.name
4139 }
4140 prr(this, {
4141 type : type
4142 , name : type
4143 // can be passed just a 'cause'
4144 , cause : typeof message != 'string' ? message : cause
4145 , message : message
4146 }, 'ewr')
4147}
4148
4149// generic prototype, not intended to be actually used - helpful for `instanceof`
4150function CustomError (message, cause) {
4151 Error.call(this)
4152 if (Error.captureStackTrace)
4153 Error.captureStackTrace(this, this.constructor)
4154 init.call(this, 'CustomError', message, cause)
4155}
4156
4157CustomError.prototype = new Error()
4158
4159function createError (errno, type, proto) {
4160 var err = function (message, cause) {
4161 init.call(this, type, message, cause)
4162 //TODO: the specificity here is stupid, errno should be available everywhere
4163 if (type == 'FilesystemError') {
4164 this.code = this.cause.code
4165 this.path = this.cause.path
4166 this.errno = this.cause.errno
4167 this.message =
4168 (errno.errno[this.cause.errno]
4169 ? errno.errno[this.cause.errno].description
4170 : this.cause.message)
4171 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
4172 }
4173 Error.call(this)
4174 if (Error.captureStackTrace)
4175 Error.captureStackTrace(this, err)
4176 }
4177 err.prototype = !!proto ? new proto() : new CustomError()
4178 return err
4179}
4180
4181module.exports = function (errno) {
4182 var ce = function (type, proto) {
4183 return createError(errno, type, proto)
4184 }
4185 return {
4186 CustomError : CustomError
4187 , FilesystemError : ce('FilesystemError')
4188 , createError : ce
4189 }
4190}
4191
4192},{"72":72}],20:[function(_dereq_,module,exports){
4193var all = module.exports.all = [
4194 {
4195 errno: -2,
4196 code: 'ENOENT',
4197 description: 'no such file or directory'
4198 },
4199 {
4200 errno: -1,
4201 code: 'UNKNOWN',
4202 description: 'unknown error'
4203 },
4204 {
4205 errno: 0,
4206 code: 'OK',
4207 description: 'success'
4208 },
4209 {
4210 errno: 1,
4211 code: 'EOF',
4212 description: 'end of file'
4213 },
4214 {
4215 errno: 2,
4216 code: 'EADDRINFO',
4217 description: 'getaddrinfo error'
4218 },
4219 {
4220 errno: 3,
4221 code: 'EACCES',
4222 description: 'permission denied'
4223 },
4224 {
4225 errno: 4,
4226 code: 'EAGAIN',
4227 description: 'resource temporarily unavailable'
4228 },
4229 {
4230 errno: 5,
4231 code: 'EADDRINUSE',
4232 description: 'address already in use'
4233 },
4234 {
4235 errno: 6,
4236 code: 'EADDRNOTAVAIL',
4237 description: 'address not available'
4238 },
4239 {
4240 errno: 7,
4241 code: 'EAFNOSUPPORT',
4242 description: 'address family not supported'
4243 },
4244 {
4245 errno: 8,
4246 code: 'EALREADY',
4247 description: 'connection already in progress'
4248 },
4249 {
4250 errno: 9,
4251 code: 'EBADF',
4252 description: 'bad file descriptor'
4253 },
4254 {
4255 errno: 10,
4256 code: 'EBUSY',
4257 description: 'resource busy or locked'
4258 },
4259 {
4260 errno: 11,
4261 code: 'ECONNABORTED',
4262 description: 'software caused connection abort'
4263 },
4264 {
4265 errno: 12,
4266 code: 'ECONNREFUSED',
4267 description: 'connection refused'
4268 },
4269 {
4270 errno: 13,
4271 code: 'ECONNRESET',
4272 description: 'connection reset by peer'
4273 },
4274 {
4275 errno: 14,
4276 code: 'EDESTADDRREQ',
4277 description: 'destination address required'
4278 },
4279 {
4280 errno: 15,
4281 code: 'EFAULT',
4282 description: 'bad address in system call argument'
4283 },
4284 {
4285 errno: 16,
4286 code: 'EHOSTUNREACH',
4287 description: 'host is unreachable'
4288 },
4289 {
4290 errno: 17,
4291 code: 'EINTR',
4292 description: 'interrupted system call'
4293 },
4294 {
4295 errno: 18,
4296 code: 'EINVAL',
4297 description: 'invalid argument'
4298 },
4299 {
4300 errno: 19,
4301 code: 'EISCONN',
4302 description: 'socket is already connected'
4303 },
4304 {
4305 errno: 20,
4306 code: 'EMFILE',
4307 description: 'too many open files'
4308 },
4309 {
4310 errno: 21,
4311 code: 'EMSGSIZE',
4312 description: 'message too long'
4313 },
4314 {
4315 errno: 22,
4316 code: 'ENETDOWN',
4317 description: 'network is down'
4318 },
4319 {
4320 errno: 23,
4321 code: 'ENETUNREACH',
4322 description: 'network is unreachable'
4323 },
4324 {
4325 errno: 24,
4326 code: 'ENFILE',
4327 description: 'file table overflow'
4328 },
4329 {
4330 errno: 25,
4331 code: 'ENOBUFS',
4332 description: 'no buffer space available'
4333 },
4334 {
4335 errno: 26,
4336 code: 'ENOMEM',
4337 description: 'not enough memory'
4338 },
4339 {
4340 errno: 27,
4341 code: 'ENOTDIR',
4342 description: 'not a directory'
4343 },
4344 {
4345 errno: 28,
4346 code: 'EISDIR',
4347 description: 'illegal operation on a directory'
4348 },
4349 {
4350 errno: 29,
4351 code: 'ENONET',
4352 description: 'machine is not on the network'
4353 },
4354 {
4355 errno: 31,
4356 code: 'ENOTCONN',
4357 description: 'socket is not connected'
4358 },
4359 {
4360 errno: 32,
4361 code: 'ENOTSOCK',
4362 description: 'socket operation on non-socket'
4363 },
4364 {
4365 errno: 33,
4366 code: 'ENOTSUP',
4367 description: 'operation not supported on socket'
4368 },
4369 {
4370 errno: 34,
4371 code: 'ENOENT',
4372 description: 'no such file or directory'
4373 },
4374 {
4375 errno: 35,
4376 code: 'ENOSYS',
4377 description: 'function not implemented'
4378 },
4379 {
4380 errno: 36,
4381 code: 'EPIPE',
4382 description: 'broken pipe'
4383 },
4384 {
4385 errno: 37,
4386 code: 'EPROTO',
4387 description: 'protocol error'
4388 },
4389 {
4390 errno: 38,
4391 code: 'EPROTONOSUPPORT',
4392 description: 'protocol not supported'
4393 },
4394 {
4395 errno: 39,
4396 code: 'EPROTOTYPE',
4397 description: 'protocol wrong type for socket'
4398 },
4399 {
4400 errno: 40,
4401 code: 'ETIMEDOUT',
4402 description: 'connection timed out'
4403 },
4404 {
4405 errno: 41,
4406 code: 'ECHARSET',
4407 description: 'invalid Unicode character'
4408 },
4409 {
4410 errno: 42,
4411 code: 'EAIFAMNOSUPPORT',
4412 description: 'address family for hostname not supported'
4413 },
4414 {
4415 errno: 44,
4416 code: 'EAISERVICE',
4417 description: 'servname not supported for ai_socktype'
4418 },
4419 {
4420 errno: 45,
4421 code: 'EAISOCKTYPE',
4422 description: 'ai_socktype not supported'
4423 },
4424 {
4425 errno: 46,
4426 code: 'ESHUTDOWN',
4427 description: 'cannot send after transport endpoint shutdown'
4428 },
4429 {
4430 errno: 47,
4431 code: 'EEXIST',
4432 description: 'file already exists'
4433 },
4434 {
4435 errno: 48,
4436 code: 'ESRCH',
4437 description: 'no such process'
4438 },
4439 {
4440 errno: 49,
4441 code: 'ENAMETOOLONG',
4442 description: 'name too long'
4443 },
4444 {
4445 errno: 50,
4446 code: 'EPERM',
4447 description: 'operation not permitted'
4448 },
4449 {
4450 errno: 51,
4451 code: 'ELOOP',
4452 description: 'too many symbolic links encountered'
4453 },
4454 {
4455 errno: 52,
4456 code: 'EXDEV',
4457 description: 'cross-device link not permitted'
4458 },
4459 {
4460 errno: 53,
4461 code: 'ENOTEMPTY',
4462 description: 'directory not empty'
4463 },
4464 {
4465 errno: 54,
4466 code: 'ENOSPC',
4467 description: 'no space left on device'
4468 },
4469 {
4470 errno: 55,
4471 code: 'EIO',
4472 description: 'i/o error'
4473 },
4474 {
4475 errno: 56,
4476 code: 'EROFS',
4477 description: 'read-only file system'
4478 },
4479 {
4480 errno: 57,
4481 code: 'ENODEV',
4482 description: 'no such device'
4483 },
4484 {
4485 errno: 58,
4486 code: 'ESPIPE',
4487 description: 'invalid seek'
4488 },
4489 {
4490 errno: 59,
4491 code: 'ECANCELED',
4492 description: 'operation canceled'
4493 }
4494]
4495
4496module.exports.errno = {}
4497module.exports.code = {}
4498
4499all.forEach(function (error) {
4500 module.exports.errno[error.errno] = error
4501 module.exports.code[error.code] = error
4502})
4503
4504module.exports.custom = _dereq_(19)(module.exports)
4505module.exports.create = module.exports.custom.createError
4506
4507},{"19":19}],21:[function(_dereq_,module,exports){
4508// Copyright Joyent, Inc. and other Node contributors.
4509//
4510// Permission is hereby granted, free of charge, to any person obtaining a
4511// copy of this software and associated documentation files (the
4512// "Software"), to deal in the Software without restriction, including
4513// without limitation the rights to use, copy, modify, merge, publish,
4514// distribute, sublicense, and/or sell copies of the Software, and to permit
4515// persons to whom the Software is furnished to do so, subject to the
4516// following conditions:
4517//
4518// The above copyright notice and this permission notice shall be included
4519// in all copies or substantial portions of the Software.
4520//
4521// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4522// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4523// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4524// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4525// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4526// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4527// USE OR OTHER DEALINGS IN THE SOFTWARE.
4528
4529var objectCreate = Object.create || objectCreatePolyfill
4530var objectKeys = Object.keys || objectKeysPolyfill
4531var bind = Function.prototype.bind || functionBindPolyfill
4532
4533function EventEmitter() {
4534 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
4535 this._events = objectCreate(null);
4536 this._eventsCount = 0;
4537 }
4538
4539 this._maxListeners = this._maxListeners || undefined;
4540}
4541module.exports = EventEmitter;
4542
4543// Backwards-compat with node 0.10.x
4544EventEmitter.EventEmitter = EventEmitter;
4545
4546EventEmitter.prototype._events = undefined;
4547EventEmitter.prototype._maxListeners = undefined;
4548
4549// By default EventEmitters will print a warning if more than 10 listeners are
4550// added to it. This is a useful default which helps finding memory leaks.
4551var defaultMaxListeners = 10;
4552
4553var hasDefineProperty;
4554try {
4555 var o = {};
4556 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
4557 hasDefineProperty = o.x === 0;
4558} catch (err) { hasDefineProperty = false }
4559if (hasDefineProperty) {
4560 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
4561 enumerable: true,
4562 get: function() {
4563 return defaultMaxListeners;
4564 },
4565 set: function(arg) {
4566 // check whether the input is a positive number (whose value is zero or
4567 // greater and not a NaN).
4568 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
4569 throw new TypeError('"defaultMaxListeners" must be a positive number');
4570 defaultMaxListeners = arg;
4571 }
4572 });
4573} else {
4574 EventEmitter.defaultMaxListeners = defaultMaxListeners;
4575}
4576
4577// Obviously not all Emitters should be limited to 10. This function allows
4578// that to be increased. Set to zero for unlimited.
4579EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
4580 if (typeof n !== 'number' || n < 0 || isNaN(n))
4581 throw new TypeError('"n" argument must be a positive number');
4582 this._maxListeners = n;
4583 return this;
4584};
4585
4586function $getMaxListeners(that) {
4587 if (that._maxListeners === undefined)
4588 return EventEmitter.defaultMaxListeners;
4589 return that._maxListeners;
4590}
4591
4592EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
4593 return $getMaxListeners(this);
4594};
4595
4596// These standalone emit* functions are used to optimize calling of event
4597// handlers for fast cases because emit() itself often has a variable number of
4598// arguments and can be deoptimized because of that. These functions always have
4599// the same number of arguments and thus do not get deoptimized, so the code
4600// inside them can execute faster.
4601function emitNone(handler, isFn, self) {
4602 if (isFn)
4603 handler.call(self);
4604 else {
4605 var len = handler.length;
4606 var listeners = arrayClone(handler, len);
4607 for (var i = 0; i < len; ++i)
4608 listeners[i].call(self);
4609 }
4610}
4611function emitOne(handler, isFn, self, arg1) {
4612 if (isFn)
4613 handler.call(self, arg1);
4614 else {
4615 var len = handler.length;
4616 var listeners = arrayClone(handler, len);
4617 for (var i = 0; i < len; ++i)
4618 listeners[i].call(self, arg1);
4619 }
4620}
4621function emitTwo(handler, isFn, self, arg1, arg2) {
4622 if (isFn)
4623 handler.call(self, arg1, arg2);
4624 else {
4625 var len = handler.length;
4626 var listeners = arrayClone(handler, len);
4627 for (var i = 0; i < len; ++i)
4628 listeners[i].call(self, arg1, arg2);
4629 }
4630}
4631function emitThree(handler, isFn, self, arg1, arg2, arg3) {
4632 if (isFn)
4633 handler.call(self, arg1, arg2, arg3);
4634 else {
4635 var len = handler.length;
4636 var listeners = arrayClone(handler, len);
4637 for (var i = 0; i < len; ++i)
4638 listeners[i].call(self, arg1, arg2, arg3);
4639 }
4640}
4641
4642function emitMany(handler, isFn, self, args) {
4643 if (isFn)
4644 handler.apply(self, args);
4645 else {
4646 var len = handler.length;
4647 var listeners = arrayClone(handler, len);
4648 for (var i = 0; i < len; ++i)
4649 listeners[i].apply(self, args);
4650 }
4651}
4652
4653EventEmitter.prototype.emit = function emit(type) {
4654 var er, handler, len, args, i, events;
4655 var doError = (type === 'error');
4656
4657 events = this._events;
4658 if (events)
4659 doError = (doError && events.error == null);
4660 else if (!doError)
4661 return false;
4662
4663 // If there is no 'error' event listener then throw.
4664 if (doError) {
4665 if (arguments.length > 1)
4666 er = arguments[1];
4667 if (er instanceof Error) {
4668 throw er; // Unhandled 'error' event
4669 } else {
4670 // At least give some kind of context to the user
4671 var err = new Error('Unhandled "error" event. (' + er + ')');
4672 err.context = er;
4673 throw err;
4674 }
4675 return false;
4676 }
4677
4678 handler = events[type];
4679
4680 if (!handler)
4681 return false;
4682
4683 var isFn = typeof handler === 'function';
4684 len = arguments.length;
4685 switch (len) {
4686 // fast cases
4687 case 1:
4688 emitNone(handler, isFn, this);
4689 break;
4690 case 2:
4691 emitOne(handler, isFn, this, arguments[1]);
4692 break;
4693 case 3:
4694 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
4695 break;
4696 case 4:
4697 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
4698 break;
4699 // slower
4700 default:
4701 args = new Array(len - 1);
4702 for (i = 1; i < len; i++)
4703 args[i - 1] = arguments[i];
4704 emitMany(handler, isFn, this, args);
4705 }
4706
4707 return true;
4708};
4709
4710function _addListener(target, type, listener, prepend) {
4711 var m;
4712 var events;
4713 var existing;
4714
4715 if (typeof listener !== 'function')
4716 throw new TypeError('"listener" argument must be a function');
4717
4718 events = target._events;
4719 if (!events) {
4720 events = target._events = objectCreate(null);
4721 target._eventsCount = 0;
4722 } else {
4723 // To avoid recursion in the case that type === "newListener"! Before
4724 // adding it to the listeners, first emit "newListener".
4725 if (events.newListener) {
4726 target.emit('newListener', type,
4727 listener.listener ? listener.listener : listener);
4728
4729 // Re-assign `events` because a newListener handler could have caused the
4730 // this._events to be assigned to a new object
4731 events = target._events;
4732 }
4733 existing = events[type];
4734 }
4735
4736 if (!existing) {
4737 // Optimize the case of one listener. Don't need the extra array object.
4738 existing = events[type] = listener;
4739 ++target._eventsCount;
4740 } else {
4741 if (typeof existing === 'function') {
4742 // Adding the second element, need to change to array.
4743 existing = events[type] =
4744 prepend ? [listener, existing] : [existing, listener];
4745 } else {
4746 // If we've already got an array, just append.
4747 if (prepend) {
4748 existing.unshift(listener);
4749 } else {
4750 existing.push(listener);
4751 }
4752 }
4753
4754 // Check for listener leak
4755 if (!existing.warned) {
4756 m = $getMaxListeners(target);
4757 if (m && m > 0 && existing.length > m) {
4758 existing.warned = true;
4759 var w = new Error('Possible EventEmitter memory leak detected. ' +
4760 existing.length + ' "' + String(type) + '" listeners ' +
4761 'added. Use emitter.setMaxListeners() to ' +
4762 'increase limit.');
4763 w.name = 'MaxListenersExceededWarning';
4764 w.emitter = target;
4765 w.type = type;
4766 w.count = existing.length;
4767 if (typeof console === 'object' && console.warn) {
4768 console.warn('%s: %s', w.name, w.message);
4769 }
4770 }
4771 }
4772 }
4773
4774 return target;
4775}
4776
4777EventEmitter.prototype.addListener = function addListener(type, listener) {
4778 return _addListener(this, type, listener, false);
4779};
4780
4781EventEmitter.prototype.on = EventEmitter.prototype.addListener;
4782
4783EventEmitter.prototype.prependListener =
4784 function prependListener(type, listener) {
4785 return _addListener(this, type, listener, true);
4786 };
4787
4788function onceWrapper() {
4789 if (!this.fired) {
4790 this.target.removeListener(this.type, this.wrapFn);
4791 this.fired = true;
4792 switch (arguments.length) {
4793 case 0:
4794 return this.listener.call(this.target);
4795 case 1:
4796 return this.listener.call(this.target, arguments[0]);
4797 case 2:
4798 return this.listener.call(this.target, arguments[0], arguments[1]);
4799 case 3:
4800 return this.listener.call(this.target, arguments[0], arguments[1],
4801 arguments[2]);
4802 default:
4803 var args = new Array(arguments.length);
4804 for (var i = 0; i < args.length; ++i)
4805 args[i] = arguments[i];
4806 this.listener.apply(this.target, args);
4807 }
4808 }
4809}
4810
4811function _onceWrap(target, type, listener) {
4812 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
4813 var wrapped = bind.call(onceWrapper, state);
4814 wrapped.listener = listener;
4815 state.wrapFn = wrapped;
4816 return wrapped;
4817}
4818
4819EventEmitter.prototype.once = function once(type, listener) {
4820 if (typeof listener !== 'function')
4821 throw new TypeError('"listener" argument must be a function');
4822 this.on(type, _onceWrap(this, type, listener));
4823 return this;
4824};
4825
4826EventEmitter.prototype.prependOnceListener =
4827 function prependOnceListener(type, listener) {
4828 if (typeof listener !== 'function')
4829 throw new TypeError('"listener" argument must be a function');
4830 this.prependListener(type, _onceWrap(this, type, listener));
4831 return this;
4832 };
4833
4834// Emits a 'removeListener' event if and only if the listener was removed.
4835EventEmitter.prototype.removeListener =
4836 function removeListener(type, listener) {
4837 var list, events, position, i, originalListener;
4838
4839 if (typeof listener !== 'function')
4840 throw new TypeError('"listener" argument must be a function');
4841
4842 events = this._events;
4843 if (!events)
4844 return this;
4845
4846 list = events[type];
4847 if (!list)
4848 return this;
4849
4850 if (list === listener || list.listener === listener) {
4851 if (--this._eventsCount === 0)
4852 this._events = objectCreate(null);
4853 else {
4854 delete events[type];
4855 if (events.removeListener)
4856 this.emit('removeListener', type, list.listener || listener);
4857 }
4858 } else if (typeof list !== 'function') {
4859 position = -1;
4860
4861 for (i = list.length - 1; i >= 0; i--) {
4862 if (list[i] === listener || list[i].listener === listener) {
4863 originalListener = list[i].listener;
4864 position = i;
4865 break;
4866 }
4867 }
4868
4869 if (position < 0)
4870 return this;
4871
4872 if (position === 0)
4873 list.shift();
4874 else
4875 spliceOne(list, position);
4876
4877 if (list.length === 1)
4878 events[type] = list[0];
4879
4880 if (events.removeListener)
4881 this.emit('removeListener', type, originalListener || listener);
4882 }
4883
4884 return this;
4885 };
4886
4887EventEmitter.prototype.removeAllListeners =
4888 function removeAllListeners(type) {
4889 var listeners, events, i;
4890
4891 events = this._events;
4892 if (!events)
4893 return this;
4894
4895 // not listening for removeListener, no need to emit
4896 if (!events.removeListener) {
4897 if (arguments.length === 0) {
4898 this._events = objectCreate(null);
4899 this._eventsCount = 0;
4900 } else if (events[type]) {
4901 if (--this._eventsCount === 0)
4902 this._events = objectCreate(null);
4903 else
4904 delete events[type];
4905 }
4906 return this;
4907 }
4908
4909 // emit removeListener for all listeners on all events
4910 if (arguments.length === 0) {
4911 var keys = objectKeys(events);
4912 var key;
4913 for (i = 0; i < keys.length; ++i) {
4914 key = keys[i];
4915 if (key === 'removeListener') continue;
4916 this.removeAllListeners(key);
4917 }
4918 this.removeAllListeners('removeListener');
4919 this._events = objectCreate(null);
4920 this._eventsCount = 0;
4921 return this;
4922 }
4923
4924 listeners = events[type];
4925
4926 if (typeof listeners === 'function') {
4927 this.removeListener(type, listeners);
4928 } else if (listeners) {
4929 // LIFO order
4930 for (i = listeners.length - 1; i >= 0; i--) {
4931 this.removeListener(type, listeners[i]);
4932 }
4933 }
4934
4935 return this;
4936 };
4937
4938function _listeners(target, type, unwrap) {
4939 var events = target._events;
4940
4941 if (!events)
4942 return [];
4943
4944 var evlistener = events[type];
4945 if (!evlistener)
4946 return [];
4947
4948 if (typeof evlistener === 'function')
4949 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
4950
4951 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
4952}
4953
4954EventEmitter.prototype.listeners = function listeners(type) {
4955 return _listeners(this, type, true);
4956};
4957
4958EventEmitter.prototype.rawListeners = function rawListeners(type) {
4959 return _listeners(this, type, false);
4960};
4961
4962EventEmitter.listenerCount = function(emitter, type) {
4963 if (typeof emitter.listenerCount === 'function') {
4964 return emitter.listenerCount(type);
4965 } else {
4966 return listenerCount.call(emitter, type);
4967 }
4968};
4969
4970EventEmitter.prototype.listenerCount = listenerCount;
4971function listenerCount(type) {
4972 var events = this._events;
4973
4974 if (events) {
4975 var evlistener = events[type];
4976
4977 if (typeof evlistener === 'function') {
4978 return 1;
4979 } else if (evlistener) {
4980 return evlistener.length;
4981 }
4982 }
4983
4984 return 0;
4985}
4986
4987EventEmitter.prototype.eventNames = function eventNames() {
4988 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
4989};
4990
4991// About 1.5x faster than the two-arg version of Array#splice().
4992function spliceOne(list, index) {
4993 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
4994 list[i] = list[k];
4995 list.pop();
4996}
4997
4998function arrayClone(arr, n) {
4999 var copy = new Array(n);
5000 for (var i = 0; i < n; ++i)
5001 copy[i] = arr[i];
5002 return copy;
5003}
5004
5005function unwrapListeners(arr) {
5006 var ret = new Array(arr.length);
5007 for (var i = 0; i < ret.length; ++i) {
5008 ret[i] = arr[i].listener || arr[i];
5009 }
5010 return ret;
5011}
5012
5013function objectCreatePolyfill(proto) {
5014 var F = function() {};
5015 F.prototype = proto;
5016 return new F;
5017}
5018function objectKeysPolyfill(obj) {
5019 var keys = [];
5020 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
5021 keys.push(k);
5022 }
5023 return k;
5024}
5025function functionBindPolyfill(context) {
5026 var fn = this;
5027 return function () {
5028 return fn.apply(context, arguments);
5029 };
5030}
5031
5032},{}],22:[function(_dereq_,module,exports){
5033"use strict"
5034
5035module.exports = createRBTree
5036
5037var RED = 0
5038var BLACK = 1
5039
5040function RBNode(color, key, value, left, right, count) {
5041 this._color = color
5042 this.key = key
5043 this.value = value
5044 this.left = left
5045 this.right = right
5046 this._count = count
5047}
5048
5049function cloneNode(node) {
5050 return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
5051}
5052
5053function repaint(color, node) {
5054 return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
5055}
5056
5057function recount(node) {
5058 node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
5059}
5060
5061function RedBlackTree(compare, root) {
5062 this._compare = compare
5063 this.root = root
5064}
5065
5066var proto = RedBlackTree.prototype
5067
5068Object.defineProperty(proto, "keys", {
5069 get: function() {
5070 var result = []
5071 this.forEach(function(k,v) {
5072 result.push(k)
5073 })
5074 return result
5075 }
5076})
5077
5078Object.defineProperty(proto, "values", {
5079 get: function() {
5080 var result = []
5081 this.forEach(function(k,v) {
5082 result.push(v)
5083 })
5084 return result
5085 }
5086})
5087
5088//Returns the number of nodes in the tree
5089Object.defineProperty(proto, "length", {
5090 get: function() {
5091 if(this.root) {
5092 return this.root._count
5093 }
5094 return 0
5095 }
5096})
5097
5098//Insert a new item into the tree
5099proto.insert = function(key, value) {
5100 var cmp = this._compare
5101 //Find point to insert new node at
5102 var n = this.root
5103 var n_stack = []
5104 var d_stack = []
5105 while(n) {
5106 var d = cmp(key, n.key)
5107 n_stack.push(n)
5108 d_stack.push(d)
5109 if(d <= 0) {
5110 n = n.left
5111 } else {
5112 n = n.right
5113 }
5114 }
5115 //Rebuild path to leaf node
5116 n_stack.push(new RBNode(RED, key, value, null, null, 1))
5117 for(var s=n_stack.length-2; s>=0; --s) {
5118 var n = n_stack[s]
5119 if(d_stack[s] <= 0) {
5120 n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
5121 } else {
5122 n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
5123 }
5124 }
5125 //Rebalance tree using rotations
5126 //console.log("start insert", key, d_stack)
5127 for(var s=n_stack.length-1; s>1; --s) {
5128 var p = n_stack[s-1]
5129 var n = n_stack[s]
5130 if(p._color === BLACK || n._color === BLACK) {
5131 break
5132 }
5133 var pp = n_stack[s-2]
5134 if(pp.left === p) {
5135 if(p.left === n) {
5136 var y = pp.right
5137 if(y && y._color === RED) {
5138 //console.log("LLr")
5139 p._color = BLACK
5140 pp.right = repaint(BLACK, y)
5141 pp._color = RED
5142 s -= 1
5143 } else {
5144 //console.log("LLb")
5145 pp._color = RED
5146 pp.left = p.right
5147 p._color = BLACK
5148 p.right = pp
5149 n_stack[s-2] = p
5150 n_stack[s-1] = n
5151 recount(pp)
5152 recount(p)
5153 if(s >= 3) {
5154 var ppp = n_stack[s-3]
5155 if(ppp.left === pp) {
5156 ppp.left = p
5157 } else {
5158 ppp.right = p
5159 }
5160 }
5161 break
5162 }
5163 } else {
5164 var y = pp.right
5165 if(y && y._color === RED) {
5166 //console.log("LRr")
5167 p._color = BLACK
5168 pp.right = repaint(BLACK, y)
5169 pp._color = RED
5170 s -= 1
5171 } else {
5172 //console.log("LRb")
5173 p.right = n.left
5174 pp._color = RED
5175 pp.left = n.right
5176 n._color = BLACK
5177 n.left = p
5178 n.right = pp
5179 n_stack[s-2] = n
5180 n_stack[s-1] = p
5181 recount(pp)
5182 recount(p)
5183 recount(n)
5184 if(s >= 3) {
5185 var ppp = n_stack[s-3]
5186 if(ppp.left === pp) {
5187 ppp.left = n
5188 } else {
5189 ppp.right = n
5190 }
5191 }
5192 break
5193 }
5194 }
5195 } else {
5196 if(p.right === n) {
5197 var y = pp.left
5198 if(y && y._color === RED) {
5199 //console.log("RRr", y.key)
5200 p._color = BLACK
5201 pp.left = repaint(BLACK, y)
5202 pp._color = RED
5203 s -= 1
5204 } else {
5205 //console.log("RRb")
5206 pp._color = RED
5207 pp.right = p.left
5208 p._color = BLACK
5209 p.left = pp
5210 n_stack[s-2] = p
5211 n_stack[s-1] = n
5212 recount(pp)
5213 recount(p)
5214 if(s >= 3) {
5215 var ppp = n_stack[s-3]
5216 if(ppp.right === pp) {
5217 ppp.right = p
5218 } else {
5219 ppp.left = p
5220 }
5221 }
5222 break
5223 }
5224 } else {
5225 var y = pp.left
5226 if(y && y._color === RED) {
5227 //console.log("RLr")
5228 p._color = BLACK
5229 pp.left = repaint(BLACK, y)
5230 pp._color = RED
5231 s -= 1
5232 } else {
5233 //console.log("RLb")
5234 p.left = n.right
5235 pp._color = RED
5236 pp.right = n.left
5237 n._color = BLACK
5238 n.right = p
5239 n.left = pp
5240 n_stack[s-2] = n
5241 n_stack[s-1] = p
5242 recount(pp)
5243 recount(p)
5244 recount(n)
5245 if(s >= 3) {
5246 var ppp = n_stack[s-3]
5247 if(ppp.right === pp) {
5248 ppp.right = n
5249 } else {
5250 ppp.left = n
5251 }
5252 }
5253 break
5254 }
5255 }
5256 }
5257 }
5258 //Return new tree
5259 n_stack[0]._color = BLACK
5260 return new RedBlackTree(cmp, n_stack[0])
5261}
5262
5263
5264//Visit all nodes inorder
5265function doVisitFull(visit, node) {
5266 if(node.left) {
5267 var v = doVisitFull(visit, node.left)
5268 if(v) { return v }
5269 }
5270 var v = visit(node.key, node.value)
5271 if(v) { return v }
5272 if(node.right) {
5273 return doVisitFull(visit, node.right)
5274 }
5275}
5276
5277//Visit half nodes in order
5278function doVisitHalf(lo, compare, visit, node) {
5279 var l = compare(lo, node.key)
5280 if(l <= 0) {
5281 if(node.left) {
5282 var v = doVisitHalf(lo, compare, visit, node.left)
5283 if(v) { return v }
5284 }
5285 var v = visit(node.key, node.value)
5286 if(v) { return v }
5287 }
5288 if(node.right) {
5289 return doVisitHalf(lo, compare, visit, node.right)
5290 }
5291}
5292
5293//Visit all nodes within a range
5294function doVisit(lo, hi, compare, visit, node) {
5295 var l = compare(lo, node.key)
5296 var h = compare(hi, node.key)
5297 var v
5298 if(l <= 0) {
5299 if(node.left) {
5300 v = doVisit(lo, hi, compare, visit, node.left)
5301 if(v) { return v }
5302 }
5303 if(h > 0) {
5304 v = visit(node.key, node.value)
5305 if(v) { return v }
5306 }
5307 }
5308 if(h > 0 && node.right) {
5309 return doVisit(lo, hi, compare, visit, node.right)
5310 }
5311}
5312
5313
5314proto.forEach = function rbTreeForEach(visit, lo, hi) {
5315 if(!this.root) {
5316 return
5317 }
5318 switch(arguments.length) {
5319 case 1:
5320 return doVisitFull(visit, this.root)
5321 break
5322
5323 case 2:
5324 return doVisitHalf(lo, this._compare, visit, this.root)
5325 break
5326
5327 case 3:
5328 if(this._compare(lo, hi) >= 0) {
5329 return
5330 }
5331 return doVisit(lo, hi, this._compare, visit, this.root)
5332 break
5333 }
5334}
5335
5336//First item in list
5337Object.defineProperty(proto, "begin", {
5338 get: function() {
5339 var stack = []
5340 var n = this.root
5341 while(n) {
5342 stack.push(n)
5343 n = n.left
5344 }
5345 return new RedBlackTreeIterator(this, stack)
5346 }
5347})
5348
5349//Last item in list
5350Object.defineProperty(proto, "end", {
5351 get: function() {
5352 var stack = []
5353 var n = this.root
5354 while(n) {
5355 stack.push(n)
5356 n = n.right
5357 }
5358 return new RedBlackTreeIterator(this, stack)
5359 }
5360})
5361
5362//Find the ith item in the tree
5363proto.at = function(idx) {
5364 if(idx < 0) {
5365 return new RedBlackTreeIterator(this, [])
5366 }
5367 var n = this.root
5368 var stack = []
5369 while(true) {
5370 stack.push(n)
5371 if(n.left) {
5372 if(idx < n.left._count) {
5373 n = n.left
5374 continue
5375 }
5376 idx -= n.left._count
5377 }
5378 if(!idx) {
5379 return new RedBlackTreeIterator(this, stack)
5380 }
5381 idx -= 1
5382 if(n.right) {
5383 if(idx >= n.right._count) {
5384 break
5385 }
5386 n = n.right
5387 } else {
5388 break
5389 }
5390 }
5391 return new RedBlackTreeIterator(this, [])
5392}
5393
5394proto.ge = function(key) {
5395 var cmp = this._compare
5396 var n = this.root
5397 var stack = []
5398 var last_ptr = 0
5399 while(n) {
5400 var d = cmp(key, n.key)
5401 stack.push(n)
5402 if(d <= 0) {
5403 last_ptr = stack.length
5404 }
5405 if(d <= 0) {
5406 n = n.left
5407 } else {
5408 n = n.right
5409 }
5410 }
5411 stack.length = last_ptr
5412 return new RedBlackTreeIterator(this, stack)
5413}
5414
5415proto.gt = function(key) {
5416 var cmp = this._compare
5417 var n = this.root
5418 var stack = []
5419 var last_ptr = 0
5420 while(n) {
5421 var d = cmp(key, n.key)
5422 stack.push(n)
5423 if(d < 0) {
5424 last_ptr = stack.length
5425 }
5426 if(d < 0) {
5427 n = n.left
5428 } else {
5429 n = n.right
5430 }
5431 }
5432 stack.length = last_ptr
5433 return new RedBlackTreeIterator(this, stack)
5434}
5435
5436proto.lt = function(key) {
5437 var cmp = this._compare
5438 var n = this.root
5439 var stack = []
5440 var last_ptr = 0
5441 while(n) {
5442 var d = cmp(key, n.key)
5443 stack.push(n)
5444 if(d > 0) {
5445 last_ptr = stack.length
5446 }
5447 if(d <= 0) {
5448 n = n.left
5449 } else {
5450 n = n.right
5451 }
5452 }
5453 stack.length = last_ptr
5454 return new RedBlackTreeIterator(this, stack)
5455}
5456
5457proto.le = function(key) {
5458 var cmp = this._compare
5459 var n = this.root
5460 var stack = []
5461 var last_ptr = 0
5462 while(n) {
5463 var d = cmp(key, n.key)
5464 stack.push(n)
5465 if(d >= 0) {
5466 last_ptr = stack.length
5467 }
5468 if(d < 0) {
5469 n = n.left
5470 } else {
5471 n = n.right
5472 }
5473 }
5474 stack.length = last_ptr
5475 return new RedBlackTreeIterator(this, stack)
5476}
5477
5478//Finds the item with key if it exists
5479proto.find = function(key) {
5480 var cmp = this._compare
5481 var n = this.root
5482 var stack = []
5483 while(n) {
5484 var d = cmp(key, n.key)
5485 stack.push(n)
5486 if(d === 0) {
5487 return new RedBlackTreeIterator(this, stack)
5488 }
5489 if(d <= 0) {
5490 n = n.left
5491 } else {
5492 n = n.right
5493 }
5494 }
5495 return new RedBlackTreeIterator(this, [])
5496}
5497
5498//Removes item with key from tree
5499proto.remove = function(key) {
5500 var iter = this.find(key)
5501 if(iter) {
5502 return iter.remove()
5503 }
5504 return this
5505}
5506
5507//Returns the item at `key`
5508proto.get = function(key) {
5509 var cmp = this._compare
5510 var n = this.root
5511 while(n) {
5512 var d = cmp(key, n.key)
5513 if(d === 0) {
5514 return n.value
5515 }
5516 if(d <= 0) {
5517 n = n.left
5518 } else {
5519 n = n.right
5520 }
5521 }
5522 return
5523}
5524
5525//Iterator for red black tree
5526function RedBlackTreeIterator(tree, stack) {
5527 this.tree = tree
5528 this._stack = stack
5529}
5530
5531var iproto = RedBlackTreeIterator.prototype
5532
5533//Test if iterator is valid
5534Object.defineProperty(iproto, "valid", {
5535 get: function() {
5536 return this._stack.length > 0
5537 }
5538})
5539
5540//Node of the iterator
5541Object.defineProperty(iproto, "node", {
5542 get: function() {
5543 if(this._stack.length > 0) {
5544 return this._stack[this._stack.length-1]
5545 }
5546 return null
5547 },
5548 enumerable: true
5549})
5550
5551//Makes a copy of an iterator
5552iproto.clone = function() {
5553 return new RedBlackTreeIterator(this.tree, this._stack.slice())
5554}
5555
5556//Swaps two nodes
5557function swapNode(n, v) {
5558 n.key = v.key
5559 n.value = v.value
5560 n.left = v.left
5561 n.right = v.right
5562 n._color = v._color
5563 n._count = v._count
5564}
5565
5566//Fix up a double black node in a tree
5567function fixDoubleBlack(stack) {
5568 var n, p, s, z
5569 for(var i=stack.length-1; i>=0; --i) {
5570 n = stack[i]
5571 if(i === 0) {
5572 n._color = BLACK
5573 return
5574 }
5575 //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
5576 p = stack[i-1]
5577 if(p.left === n) {
5578 //console.log("left child")
5579 s = p.right
5580 if(s.right && s.right._color === RED) {
5581 //console.log("case 1: right sibling child red")
5582 s = p.right = cloneNode(s)
5583 z = s.right = cloneNode(s.right)
5584 p.right = s.left
5585 s.left = p
5586 s.right = z
5587 s._color = p._color
5588 n._color = BLACK
5589 p._color = BLACK
5590 z._color = BLACK
5591 recount(p)
5592 recount(s)
5593 if(i > 1) {
5594 var pp = stack[i-2]
5595 if(pp.left === p) {
5596 pp.left = s
5597 } else {
5598 pp.right = s
5599 }
5600 }
5601 stack[i-1] = s
5602 return
5603 } else if(s.left && s.left._color === RED) {
5604 //console.log("case 1: left sibling child red")
5605 s = p.right = cloneNode(s)
5606 z = s.left = cloneNode(s.left)
5607 p.right = z.left
5608 s.left = z.right
5609 z.left = p
5610 z.right = s
5611 z._color = p._color
5612 p._color = BLACK
5613 s._color = BLACK
5614 n._color = BLACK
5615 recount(p)
5616 recount(s)
5617 recount(z)
5618 if(i > 1) {
5619 var pp = stack[i-2]
5620 if(pp.left === p) {
5621 pp.left = z
5622 } else {
5623 pp.right = z
5624 }
5625 }
5626 stack[i-1] = z
5627 return
5628 }
5629 if(s._color === BLACK) {
5630 if(p._color === RED) {
5631 //console.log("case 2: black sibling, red parent", p.right.value)
5632 p._color = BLACK
5633 p.right = repaint(RED, s)
5634 return
5635 } else {
5636 //console.log("case 2: black sibling, black parent", p.right.value)
5637 p.right = repaint(RED, s)
5638 continue
5639 }
5640 } else {
5641 //console.log("case 3: red sibling")
5642 s = cloneNode(s)
5643 p.right = s.left
5644 s.left = p
5645 s._color = p._color
5646 p._color = RED
5647 recount(p)
5648 recount(s)
5649 if(i > 1) {
5650 var pp = stack[i-2]
5651 if(pp.left === p) {
5652 pp.left = s
5653 } else {
5654 pp.right = s
5655 }
5656 }
5657 stack[i-1] = s
5658 stack[i] = p
5659 if(i+1 < stack.length) {
5660 stack[i+1] = n
5661 } else {
5662 stack.push(n)
5663 }
5664 i = i+2
5665 }
5666 } else {
5667 //console.log("right child")
5668 s = p.left
5669 if(s.left && s.left._color === RED) {
5670 //console.log("case 1: left sibling child red", p.value, p._color)
5671 s = p.left = cloneNode(s)
5672 z = s.left = cloneNode(s.left)
5673 p.left = s.right
5674 s.right = p
5675 s.left = z
5676 s._color = p._color
5677 n._color = BLACK
5678 p._color = BLACK
5679 z._color = BLACK
5680 recount(p)
5681 recount(s)
5682 if(i > 1) {
5683 var pp = stack[i-2]
5684 if(pp.right === p) {
5685 pp.right = s
5686 } else {
5687 pp.left = s
5688 }
5689 }
5690 stack[i-1] = s
5691 return
5692 } else if(s.right && s.right._color === RED) {
5693 //console.log("case 1: right sibling child red")
5694 s = p.left = cloneNode(s)
5695 z = s.right = cloneNode(s.right)
5696 p.left = z.right
5697 s.right = z.left
5698 z.right = p
5699 z.left = s
5700 z._color = p._color
5701 p._color = BLACK
5702 s._color = BLACK
5703 n._color = BLACK
5704 recount(p)
5705 recount(s)
5706 recount(z)
5707 if(i > 1) {
5708 var pp = stack[i-2]
5709 if(pp.right === p) {
5710 pp.right = z
5711 } else {
5712 pp.left = z
5713 }
5714 }
5715 stack[i-1] = z
5716 return
5717 }
5718 if(s._color === BLACK) {
5719 if(p._color === RED) {
5720 //console.log("case 2: black sibling, red parent")
5721 p._color = BLACK
5722 p.left = repaint(RED, s)
5723 return
5724 } else {
5725 //console.log("case 2: black sibling, black parent")
5726 p.left = repaint(RED, s)
5727 continue
5728 }
5729 } else {
5730 //console.log("case 3: red sibling")
5731 s = cloneNode(s)
5732 p.left = s.right
5733 s.right = p
5734 s._color = p._color
5735 p._color = RED
5736 recount(p)
5737 recount(s)
5738 if(i > 1) {
5739 var pp = stack[i-2]
5740 if(pp.right === p) {
5741 pp.right = s
5742 } else {
5743 pp.left = s
5744 }
5745 }
5746 stack[i-1] = s
5747 stack[i] = p
5748 if(i+1 < stack.length) {
5749 stack[i+1] = n
5750 } else {
5751 stack.push(n)
5752 }
5753 i = i+2
5754 }
5755 }
5756 }
5757}
5758
5759//Removes item at iterator from tree
5760iproto.remove = function() {
5761 var stack = this._stack
5762 if(stack.length === 0) {
5763 return this.tree
5764 }
5765 //First copy path to node
5766 var cstack = new Array(stack.length)
5767 var n = stack[stack.length-1]
5768 cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
5769 for(var i=stack.length-2; i>=0; --i) {
5770 var n = stack[i]
5771 if(n.left === stack[i+1]) {
5772 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5773 } else {
5774 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5775 }
5776 }
5777
5778 //Get node
5779 n = cstack[cstack.length-1]
5780 //console.log("start remove: ", n.value)
5781
5782 //If not leaf, then swap with previous node
5783 if(n.left && n.right) {
5784 //console.log("moving to leaf")
5785
5786 //First walk to previous leaf
5787 var split = cstack.length
5788 n = n.left
5789 while(n.right) {
5790 cstack.push(n)
5791 n = n.right
5792 }
5793 //Copy path to leaf
5794 var v = cstack[split-1]
5795 cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
5796 cstack[split-1].key = n.key
5797 cstack[split-1].value = n.value
5798
5799 //Fix up stack
5800 for(var i=cstack.length-2; i>=split; --i) {
5801 n = cstack[i]
5802 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5803 }
5804 cstack[split-1].left = cstack[split]
5805 }
5806 //console.log("stack=", cstack.map(function(v) { return v.value }))
5807
5808 //Remove leaf node
5809 n = cstack[cstack.length-1]
5810 if(n._color === RED) {
5811 //Easy case: removing red leaf
5812 //console.log("RED leaf")
5813 var p = cstack[cstack.length-2]
5814 if(p.left === n) {
5815 p.left = null
5816 } else if(p.right === n) {
5817 p.right = null
5818 }
5819 cstack.pop()
5820 for(var i=0; i<cstack.length; ++i) {
5821 cstack[i]._count--
5822 }
5823 return new RedBlackTree(this.tree._compare, cstack[0])
5824 } else {
5825 if(n.left || n.right) {
5826 //Second easy case: Single child black parent
5827 //console.log("BLACK single child")
5828 if(n.left) {
5829 swapNode(n, n.left)
5830 } else if(n.right) {
5831 swapNode(n, n.right)
5832 }
5833 //Child must be red, so repaint it black to balance color
5834 n._color = BLACK
5835 for(var i=0; i<cstack.length-1; ++i) {
5836 cstack[i]._count--
5837 }
5838 return new RedBlackTree(this.tree._compare, cstack[0])
5839 } else if(cstack.length === 1) {
5840 //Third easy case: root
5841 //console.log("ROOT")
5842 return new RedBlackTree(this.tree._compare, null)
5843 } else {
5844 //Hard case: Repaint n, and then do some nasty stuff
5845 //console.log("BLACK leaf no children")
5846 for(var i=0; i<cstack.length; ++i) {
5847 cstack[i]._count--
5848 }
5849 var parent = cstack[cstack.length-2]
5850 fixDoubleBlack(cstack)
5851 //Fix up links
5852 if(parent.left === n) {
5853 parent.left = null
5854 } else {
5855 parent.right = null
5856 }
5857 }
5858 }
5859 return new RedBlackTree(this.tree._compare, cstack[0])
5860}
5861
5862//Returns key
5863Object.defineProperty(iproto, "key", {
5864 get: function() {
5865 if(this._stack.length > 0) {
5866 return this._stack[this._stack.length-1].key
5867 }
5868 return
5869 },
5870 enumerable: true
5871})
5872
5873//Returns value
5874Object.defineProperty(iproto, "value", {
5875 get: function() {
5876 if(this._stack.length > 0) {
5877 return this._stack[this._stack.length-1].value
5878 }
5879 return
5880 },
5881 enumerable: true
5882})
5883
5884
5885//Returns the position of this iterator in the sorted list
5886Object.defineProperty(iproto, "index", {
5887 get: function() {
5888 var idx = 0
5889 var stack = this._stack
5890 if(stack.length === 0) {
5891 var r = this.tree.root
5892 if(r) {
5893 return r._count
5894 }
5895 return 0
5896 } else if(stack[stack.length-1].left) {
5897 idx = stack[stack.length-1].left._count
5898 }
5899 for(var s=stack.length-2; s>=0; --s) {
5900 if(stack[s+1] === stack[s].right) {
5901 ++idx
5902 if(stack[s].left) {
5903 idx += stack[s].left._count
5904 }
5905 }
5906 }
5907 return idx
5908 },
5909 enumerable: true
5910})
5911
5912//Advances iterator to next element in list
5913iproto.next = function() {
5914 var stack = this._stack
5915 if(stack.length === 0) {
5916 return
5917 }
5918 var n = stack[stack.length-1]
5919 if(n.right) {
5920 n = n.right
5921 while(n) {
5922 stack.push(n)
5923 n = n.left
5924 }
5925 } else {
5926 stack.pop()
5927 while(stack.length > 0 && stack[stack.length-1].right === n) {
5928 n = stack[stack.length-1]
5929 stack.pop()
5930 }
5931 }
5932}
5933
5934//Checks if iterator is at end of tree
5935Object.defineProperty(iproto, "hasNext", {
5936 get: function() {
5937 var stack = this._stack
5938 if(stack.length === 0) {
5939 return false
5940 }
5941 if(stack[stack.length-1].right) {
5942 return true
5943 }
5944 for(var s=stack.length-1; s>0; --s) {
5945 if(stack[s-1].left === stack[s]) {
5946 return true
5947 }
5948 }
5949 return false
5950 }
5951})
5952
5953//Update value
5954iproto.update = function(value) {
5955 var stack = this._stack
5956 if(stack.length === 0) {
5957 throw new Error("Can't update empty node!")
5958 }
5959 var cstack = new Array(stack.length)
5960 var n = stack[stack.length-1]
5961 cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
5962 for(var i=stack.length-2; i>=0; --i) {
5963 n = stack[i]
5964 if(n.left === stack[i+1]) {
5965 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5966 } else {
5967 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5968 }
5969 }
5970 return new RedBlackTree(this.tree._compare, cstack[0])
5971}
5972
5973//Moves iterator backward one element
5974iproto.prev = function() {
5975 var stack = this._stack
5976 if(stack.length === 0) {
5977 return
5978 }
5979 var n = stack[stack.length-1]
5980 if(n.left) {
5981 n = n.left
5982 while(n) {
5983 stack.push(n)
5984 n = n.right
5985 }
5986 } else {
5987 stack.pop()
5988 while(stack.length > 0 && stack[stack.length-1].left === n) {
5989 n = stack[stack.length-1]
5990 stack.pop()
5991 }
5992 }
5993}
5994
5995//Checks if iterator is at start of tree
5996Object.defineProperty(iproto, "hasPrev", {
5997 get: function() {
5998 var stack = this._stack
5999 if(stack.length === 0) {
6000 return false
6001 }
6002 if(stack[stack.length-1].left) {
6003 return true
6004 }
6005 for(var s=stack.length-1; s>0; --s) {
6006 if(stack[s-1].right === stack[s]) {
6007 return true
6008 }
6009 }
6010 return false
6011 }
6012})
6013
6014//Default comparison function
6015function defaultCompare(a, b) {
6016 if(a < b) {
6017 return -1
6018 }
6019 if(a > b) {
6020 return 1
6021 }
6022 return 0
6023}
6024
6025//Build a tree
6026function createRBTree(compare) {
6027 return new RedBlackTree(compare || defaultCompare, null)
6028}
6029},{}],23:[function(_dereq_,module,exports){
6030exports.read = function (buffer, offset, isLE, mLen, nBytes) {
6031 var e, m
6032 var eLen = (nBytes * 8) - mLen - 1
6033 var eMax = (1 << eLen) - 1
6034 var eBias = eMax >> 1
6035 var nBits = -7
6036 var i = isLE ? (nBytes - 1) : 0
6037 var d = isLE ? -1 : 1
6038 var s = buffer[offset + i]
6039
6040 i += d
6041
6042 e = s & ((1 << (-nBits)) - 1)
6043 s >>= (-nBits)
6044 nBits += eLen
6045 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6046
6047 m = e & ((1 << (-nBits)) - 1)
6048 e >>= (-nBits)
6049 nBits += mLen
6050 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6051
6052 if (e === 0) {
6053 e = 1 - eBias
6054 } else if (e === eMax) {
6055 return m ? NaN : ((s ? -1 : 1) * Infinity)
6056 } else {
6057 m = m + Math.pow(2, mLen)
6058 e = e - eBias
6059 }
6060 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
6061}
6062
6063exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
6064 var e, m, c
6065 var eLen = (nBytes * 8) - mLen - 1
6066 var eMax = (1 << eLen) - 1
6067 var eBias = eMax >> 1
6068 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
6069 var i = isLE ? 0 : (nBytes - 1)
6070 var d = isLE ? 1 : -1
6071 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
6072
6073 value = Math.abs(value)
6074
6075 if (isNaN(value) || value === Infinity) {
6076 m = isNaN(value) ? 1 : 0
6077 e = eMax
6078 } else {
6079 e = Math.floor(Math.log(value) / Math.LN2)
6080 if (value * (c = Math.pow(2, -e)) < 1) {
6081 e--
6082 c *= 2
6083 }
6084 if (e + eBias >= 1) {
6085 value += rt / c
6086 } else {
6087 value += rt * Math.pow(2, 1 - eBias)
6088 }
6089 if (value * c >= 2) {
6090 e++
6091 c /= 2
6092 }
6093
6094 if (e + eBias >= eMax) {
6095 m = 0
6096 e = eMax
6097 } else if (e + eBias >= 1) {
6098 m = ((value * c) - 1) * Math.pow(2, mLen)
6099 e = e + eBias
6100 } else {
6101 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
6102 e = 0
6103 }
6104 }
6105
6106 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
6107
6108 e = (e << mLen) | m
6109 eLen += mLen
6110 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
6111
6112 buffer[offset + i - d] |= s * 128
6113}
6114
6115},{}],24:[function(_dereq_,module,exports){
6116(function (global){
6117'use strict';
6118var Mutation = global.MutationObserver || global.WebKitMutationObserver;
6119
6120var scheduleDrain;
6121
6122{
6123 if (Mutation) {
6124 var called = 0;
6125 var observer = new Mutation(nextTick);
6126 var element = global.document.createTextNode('');
6127 observer.observe(element, {
6128 characterData: true
6129 });
6130 scheduleDrain = function () {
6131 element.data = (called = ++called % 2);
6132 };
6133 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
6134 var channel = new global.MessageChannel();
6135 channel.port1.onmessage = nextTick;
6136 scheduleDrain = function () {
6137 channel.port2.postMessage(0);
6138 };
6139 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
6140 scheduleDrain = function () {
6141
6142 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
6143 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
6144 var scriptEl = global.document.createElement('script');
6145 scriptEl.onreadystatechange = function () {
6146 nextTick();
6147
6148 scriptEl.onreadystatechange = null;
6149 scriptEl.parentNode.removeChild(scriptEl);
6150 scriptEl = null;
6151 };
6152 global.document.documentElement.appendChild(scriptEl);
6153 };
6154 } else {
6155 scheduleDrain = function () {
6156 setTimeout(nextTick, 0);
6157 };
6158 }
6159}
6160
6161var draining;
6162var queue = [];
6163//named nextTick for less confusing stack traces
6164function nextTick() {
6165 draining = true;
6166 var i, oldQueue;
6167 var len = queue.length;
6168 while (len) {
6169 oldQueue = queue;
6170 queue = [];
6171 i = -1;
6172 while (++i < len) {
6173 oldQueue[i]();
6174 }
6175 len = queue.length;
6176 }
6177 draining = false;
6178}
6179
6180module.exports = immediate;
6181function immediate(task) {
6182 if (queue.push(task) === 1 && !draining) {
6183 scheduleDrain();
6184 }
6185}
6186
6187}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6188},{}],25:[function(_dereq_,module,exports){
6189arguments[4][3][0].apply(exports,arguments)
6190},{"3":3}],26:[function(_dereq_,module,exports){
6191/*!
6192 * Determine if an object is a Buffer
6193 *
6194 * @author Feross Aboukhadijeh <https://feross.org>
6195 * @license MIT
6196 */
6197
6198// The _isBuffer check is for Safari 5-7 support, because it's missing
6199// Object.prototype.constructor. Remove this eventually
6200module.exports = function (obj) {
6201 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
6202}
6203
6204function isBuffer (obj) {
6205 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
6206}
6207
6208// For Node v0.10 support. Remove this eventually.
6209function isSlowBuffer (obj) {
6210 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
6211}
6212
6213},{}],27:[function(_dereq_,module,exports){
6214module.exports = Array.isArray || function (arr) {
6215 return Object.prototype.toString.call(arr) == '[object Array]';
6216};
6217
6218},{}],28:[function(_dereq_,module,exports){
6219var encodings = _dereq_(29)
6220
6221module.exports = Codec
6222
6223function Codec (opts) {
6224 if (!(this instanceof Codec)) {
6225 return new Codec(opts)
6226 }
6227 this.opts = opts || {}
6228 this.encodings = encodings
6229}
6230
6231Codec.prototype._encoding = function (encoding) {
6232 if (typeof encoding === 'string') encoding = encodings[encoding]
6233 if (!encoding) encoding = encodings.id
6234 return encoding
6235}
6236
6237Codec.prototype._keyEncoding = function (opts, batchOpts) {
6238 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
6239 (opts && opts.keyEncoding) ||
6240 this.opts.keyEncoding)
6241}
6242
6243Codec.prototype._valueEncoding = function (opts, batchOpts) {
6244 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
6245 (opts && (opts.valueEncoding || opts.encoding)) ||
6246 (this.opts.valueEncoding || this.opts.encoding))
6247}
6248
6249Codec.prototype.encodeKey = function (key, opts, batchOpts) {
6250 return this._keyEncoding(opts, batchOpts).encode(key)
6251}
6252
6253Codec.prototype.encodeValue = function (value, opts, batchOpts) {
6254 return this._valueEncoding(opts, batchOpts).encode(value)
6255}
6256
6257Codec.prototype.decodeKey = function (key, opts) {
6258 return this._keyEncoding(opts).decode(key)
6259}
6260
6261Codec.prototype.decodeValue = function (value, opts) {
6262 return this._valueEncoding(opts).decode(value)
6263}
6264
6265Codec.prototype.encodeBatch = function (ops, opts) {
6266 var self = this
6267
6268 return ops.map(function (_op) {
6269 var op = {
6270 type: _op.type,
6271 key: self.encodeKey(_op.key, opts, _op)
6272 }
6273 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
6274 if (_op.prefix) op.prefix = _op.prefix
6275 if ('value' in _op) {
6276 op.value = self.encodeValue(_op.value, opts, _op)
6277 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
6278 }
6279 return op
6280 })
6281}
6282
6283var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
6284
6285Codec.prototype.encodeLtgt = function (ltgt) {
6286 var self = this
6287 var ret = {}
6288 Object.keys(ltgt).forEach(function (key) {
6289 ret[key] = ltgtKeys.indexOf(key) > -1
6290 ? self.encodeKey(ltgt[key], ltgt)
6291 : ltgt[key]
6292 })
6293 return ret
6294}
6295
6296Codec.prototype.createStreamDecoder = function (opts) {
6297 var self = this
6298
6299 if (opts.keys && opts.values) {
6300 return function (key, value) {
6301 return {
6302 key: self.decodeKey(key, opts),
6303 value: self.decodeValue(value, opts)
6304 }
6305 }
6306 } else if (opts.keys) {
6307 return function (key) {
6308 return self.decodeKey(key, opts)
6309 }
6310 } else if (opts.values) {
6311 return function (_, value) {
6312 return self.decodeValue(value, opts)
6313 }
6314 } else {
6315 return function () {}
6316 }
6317}
6318
6319Codec.prototype.keyAsBuffer = function (opts) {
6320 return this._keyEncoding(opts).buffer
6321}
6322
6323Codec.prototype.valueAsBuffer = function (opts) {
6324 return this._valueEncoding(opts).buffer
6325}
6326
6327},{"29":29}],29:[function(_dereq_,module,exports){
6328(function (Buffer){
6329exports.utf8 = exports['utf-8'] = {
6330 encode: function (data) {
6331 return isBinary(data) ? data : String(data)
6332 },
6333 decode: identity,
6334 buffer: false,
6335 type: 'utf8'
6336}
6337
6338exports.json = {
6339 encode: JSON.stringify,
6340 decode: JSON.parse,
6341 buffer: false,
6342 type: 'json'
6343}
6344
6345exports.binary = {
6346 encode: function (data) {
6347 return isBinary(data) ? data : Buffer.from(data)
6348 },
6349 decode: identity,
6350 buffer: true,
6351 type: 'binary'
6352}
6353
6354exports.none = {
6355 encode: identity,
6356 decode: identity,
6357 buffer: false,
6358 type: 'id'
6359}
6360
6361exports.id = exports.none
6362
6363var bufferEncodings = [
6364 'hex',
6365 'ascii',
6366 'base64',
6367 'ucs2',
6368 'ucs-2',
6369 'utf16le',
6370 'utf-16le'
6371]
6372
6373bufferEncodings.forEach(function (type) {
6374 exports[type] = {
6375 encode: function (data) {
6376 return isBinary(data) ? data : Buffer.from(data, type)
6377 },
6378 decode: function (buffer) {
6379 return buffer.toString(type)
6380 },
6381 buffer: true,
6382 type: type
6383 }
6384})
6385
6386function identity (value) {
6387 return value
6388}
6389
6390function isBinary (data) {
6391 return data === undefined || data === null || Buffer.isBuffer(data)
6392}
6393
6394}).call(this,_dereq_(9).Buffer)
6395},{"9":9}],30:[function(_dereq_,module,exports){
6396var createError = _dereq_(20).create
6397var LevelUPError = createError('LevelUPError')
6398var NotFoundError = createError('NotFoundError', LevelUPError)
6399
6400NotFoundError.prototype.notFound = true
6401NotFoundError.prototype.status = 404
6402
6403module.exports = {
6404 LevelUPError: LevelUPError,
6405 InitializationError: createError('InitializationError', LevelUPError),
6406 OpenError: createError('OpenError', LevelUPError),
6407 ReadError: createError('ReadError', LevelUPError),
6408 WriteError: createError('WriteError', LevelUPError),
6409 NotFoundError: NotFoundError,
6410 EncodingError: createError('EncodingError', LevelUPError)
6411}
6412
6413},{"20":20}],31:[function(_dereq_,module,exports){
6414var inherits = _dereq_(25)
6415var Readable = _dereq_(46).Readable
6416var extend = _dereq_(47)
6417
6418module.exports = ReadStream
6419inherits(ReadStream, Readable)
6420
6421function ReadStream (iterator, options) {
6422 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
6423 options = options || {}
6424 Readable.call(this, extend(options, {
6425 objectMode: true
6426 }))
6427 this._iterator = iterator
6428 this._options = options
6429 this.on('end', this.destroy.bind(this, null, null))
6430}
6431
6432ReadStream.prototype._read = function () {
6433 var self = this
6434 var options = this._options
6435 if (this.destroyed) return
6436
6437 this._iterator.next(function (err, key, value) {
6438 if (self.destroyed) return
6439 if (err) return self.destroy(err)
6440
6441 if (key === undefined && value === undefined) {
6442 self.push(null)
6443 } else if (options.keys !== false && options.values === false) {
6444 self.push(key)
6445 } else if (options.keys === false && options.values !== false) {
6446 self.push(value)
6447 } else {
6448 self.push({ key: key, value: value })
6449 }
6450 })
6451}
6452
6453ReadStream.prototype._destroy = function (err, callback) {
6454 this._iterator.end(function (err2) {
6455 callback(err || err2)
6456 })
6457}
6458
6459},{"25":25,"46":46,"47":47}],32:[function(_dereq_,module,exports){
6460'use strict';
6461
6462function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
6463
6464var codes = {};
6465
6466function createErrorType(code, message, Base) {
6467 if (!Base) {
6468 Base = Error;
6469 }
6470
6471 function getMessage(arg1, arg2, arg3) {
6472 if (typeof message === 'string') {
6473 return message;
6474 } else {
6475 return message(arg1, arg2, arg3);
6476 }
6477 }
6478
6479 var NodeError =
6480 /*#__PURE__*/
6481 function (_Base) {
6482 _inheritsLoose(NodeError, _Base);
6483
6484 function NodeError(arg1, arg2, arg3) {
6485 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
6486 }
6487
6488 return NodeError;
6489 }(Base);
6490
6491 NodeError.prototype.name = Base.name;
6492 NodeError.prototype.code = code;
6493 codes[code] = NodeError;
6494} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
6495
6496
6497function oneOf(expected, thing) {
6498 if (Array.isArray(expected)) {
6499 var len = expected.length;
6500 expected = expected.map(function (i) {
6501 return String(i);
6502 });
6503
6504 if (len > 2) {
6505 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
6506 } else if (len === 2) {
6507 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
6508 } else {
6509 return "of ".concat(thing, " ").concat(expected[0]);
6510 }
6511 } else {
6512 return "of ".concat(thing, " ").concat(String(expected));
6513 }
6514} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
6515
6516
6517function startsWith(str, search, pos) {
6518 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
6519} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
6520
6521
6522function endsWith(str, search, this_len) {
6523 if (this_len === undefined || this_len > str.length) {
6524 this_len = str.length;
6525 }
6526
6527 return str.substring(this_len - search.length, this_len) === search;
6528} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
6529
6530
6531function includes(str, search, start) {
6532 if (typeof start !== 'number') {
6533 start = 0;
6534 }
6535
6536 if (start + search.length > str.length) {
6537 return false;
6538 } else {
6539 return str.indexOf(search, start) !== -1;
6540 }
6541}
6542
6543createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
6544 return 'The value "' + value + '" is invalid for option "' + name + '"';
6545}, TypeError);
6546createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
6547 // determiner: 'must be' or 'must not be'
6548 var determiner;
6549
6550 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
6551 determiner = 'must not be';
6552 expected = expected.replace(/^not /, '');
6553 } else {
6554 determiner = 'must be';
6555 }
6556
6557 var msg;
6558
6559 if (endsWith(name, ' argument')) {
6560 // For cases like 'first argument'
6561 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6562 } else {
6563 var type = includes(name, '.') ? 'property' : 'argument';
6564 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6565 }
6566
6567 msg += ". Received type ".concat(typeof actual);
6568 return msg;
6569}, TypeError);
6570createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
6571createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
6572 return 'The ' + name + ' method is not implemented';
6573});
6574createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
6575createErrorType('ERR_STREAM_DESTROYED', function (name) {
6576 return 'Cannot call ' + name + ' after a stream was destroyed';
6577});
6578createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
6579createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
6580createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
6581createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
6582createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
6583 return 'Unknown encoding: ' + arg;
6584}, TypeError);
6585createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
6586module.exports.codes = codes;
6587
6588},{}],33:[function(_dereq_,module,exports){
6589(function (process){
6590'use strict'
6591
6592var experimentalWarnings = new Set();
6593
6594function emitExperimentalWarning(feature) {
6595 if (experimentalWarnings.has(feature)) return;
6596 var msg = feature + ' is an experimental feature. This feature could ' +
6597 'change at any time';
6598 experimentalWarnings.add(feature);
6599 process.emitWarning(msg, 'ExperimentalWarning');
6600}
6601
6602function noop() {}
6603
6604module.exports.emitExperimentalWarning = process.emitWarning
6605 ? emitExperimentalWarning
6606 : noop;
6607
6608}).call(this,_dereq_(71))
6609},{"71":71}],34:[function(_dereq_,module,exports){
6610(function (process){
6611// Copyright Joyent, Inc. and other Node contributors.
6612//
6613// Permission is hereby granted, free of charge, to any person obtaining a
6614// copy of this software and associated documentation files (the
6615// "Software"), to deal in the Software without restriction, including
6616// without limitation the rights to use, copy, modify, merge, publish,
6617// distribute, sublicense, and/or sell copies of the Software, and to permit
6618// persons to whom the Software is furnished to do so, subject to the
6619// following conditions:
6620//
6621// The above copyright notice and this permission notice shall be included
6622// in all copies or substantial portions of the Software.
6623//
6624// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6625// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6626// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6627// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6628// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6629// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6630// USE OR OTHER DEALINGS IN THE SOFTWARE.
6631// a duplex stream is just a stream that is both readable and writable.
6632// Since JS doesn't have multiple prototypal inheritance, this class
6633// prototypally inherits from Readable, and then parasitically from
6634// Writable.
6635'use strict';
6636/*<replacement>*/
6637
6638var objectKeys = Object.keys || function (obj) {
6639 var keys = [];
6640
6641 for (var key in obj) {
6642 keys.push(key);
6643 }
6644
6645 return keys;
6646};
6647/*</replacement>*/
6648
6649
6650module.exports = Duplex;
6651
6652var Readable = _dereq_(36);
6653
6654var Writable = _dereq_(38);
6655
6656_dereq_(25)(Duplex, Readable);
6657
6658{
6659 // Allow the keys array to be GC'ed.
6660 var keys = objectKeys(Writable.prototype);
6661
6662 for (var v = 0; v < keys.length; v++) {
6663 var method = keys[v];
6664 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
6665 }
6666}
6667
6668function Duplex(options) {
6669 if (!(this instanceof Duplex)) return new Duplex(options);
6670 Readable.call(this, options);
6671 Writable.call(this, options);
6672 this.allowHalfOpen = true;
6673
6674 if (options) {
6675 if (options.readable === false) this.readable = false;
6676 if (options.writable === false) this.writable = false;
6677
6678 if (options.allowHalfOpen === false) {
6679 this.allowHalfOpen = false;
6680 this.once('end', onend);
6681 }
6682 }
6683}
6684
6685Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
6686 // making it explicit this property is not enumerable
6687 // because otherwise some prototype manipulation in
6688 // userland will fail
6689 enumerable: false,
6690 get: function get() {
6691 return this._writableState.highWaterMark;
6692 }
6693});
6694Object.defineProperty(Duplex.prototype, 'writableBuffer', {
6695 // making it explicit this property is not enumerable
6696 // because otherwise some prototype manipulation in
6697 // userland will fail
6698 enumerable: false,
6699 get: function get() {
6700 return this._writableState && this._writableState.getBuffer();
6701 }
6702});
6703Object.defineProperty(Duplex.prototype, 'writableLength', {
6704 // making it explicit this property is not enumerable
6705 // because otherwise some prototype manipulation in
6706 // userland will fail
6707 enumerable: false,
6708 get: function get() {
6709 return this._writableState.length;
6710 }
6711}); // the no-half-open enforcer
6712
6713function onend() {
6714 // If the writable side ended, then we're ok.
6715 if (this._writableState.ended) return; // no more data can be written.
6716 // But allow more writes to happen in this tick.
6717
6718 process.nextTick(onEndNT, this);
6719}
6720
6721function onEndNT(self) {
6722 self.end();
6723}
6724
6725Object.defineProperty(Duplex.prototype, 'destroyed', {
6726 // making it explicit this property is not enumerable
6727 // because otherwise some prototype manipulation in
6728 // userland will fail
6729 enumerable: false,
6730 get: function get() {
6731 if (this._readableState === undefined || this._writableState === undefined) {
6732 return false;
6733 }
6734
6735 return this._readableState.destroyed && this._writableState.destroyed;
6736 },
6737 set: function set(value) {
6738 // we ignore the value if the stream
6739 // has not been initialized yet
6740 if (this._readableState === undefined || this._writableState === undefined) {
6741 return;
6742 } // backward compatibility, the user is explicitly
6743 // managing destroyed
6744
6745
6746 this._readableState.destroyed = value;
6747 this._writableState.destroyed = value;
6748 }
6749});
6750}).call(this,_dereq_(71))
6751},{"25":25,"36":36,"38":38,"71":71}],35:[function(_dereq_,module,exports){
6752// Copyright Joyent, Inc. and other Node contributors.
6753//
6754// Permission is hereby granted, free of charge, to any person obtaining a
6755// copy of this software and associated documentation files (the
6756// "Software"), to deal in the Software without restriction, including
6757// without limitation the rights to use, copy, modify, merge, publish,
6758// distribute, sublicense, and/or sell copies of the Software, and to permit
6759// persons to whom the Software is furnished to do so, subject to the
6760// following conditions:
6761//
6762// The above copyright notice and this permission notice shall be included
6763// in all copies or substantial portions of the Software.
6764//
6765// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6766// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6767// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6768// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6769// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6770// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6771// USE OR OTHER DEALINGS IN THE SOFTWARE.
6772// a passthrough stream.
6773// basically just the most minimal sort of Transform stream.
6774// Every written chunk gets output as-is.
6775'use strict';
6776
6777module.exports = PassThrough;
6778
6779var Transform = _dereq_(37);
6780
6781_dereq_(25)(PassThrough, Transform);
6782
6783function PassThrough(options) {
6784 if (!(this instanceof PassThrough)) return new PassThrough(options);
6785 Transform.call(this, options);
6786}
6787
6788PassThrough.prototype._transform = function (chunk, encoding, cb) {
6789 cb(null, chunk);
6790};
6791},{"25":25,"37":37}],36:[function(_dereq_,module,exports){
6792(function (process,global){
6793// Copyright Joyent, Inc. and other Node contributors.
6794//
6795// Permission is hereby granted, free of charge, to any person obtaining a
6796// copy of this software and associated documentation files (the
6797// "Software"), to deal in the Software without restriction, including
6798// without limitation the rights to use, copy, modify, merge, publish,
6799// distribute, sublicense, and/or sell copies of the Software, and to permit
6800// persons to whom the Software is furnished to do so, subject to the
6801// following conditions:
6802//
6803// The above copyright notice and this permission notice shall be included
6804// in all copies or substantial portions of the Software.
6805//
6806// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6807// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6808// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6809// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6810// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6811// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6812// USE OR OTHER DEALINGS IN THE SOFTWARE.
6813'use strict';
6814
6815module.exports = Readable;
6816/*<replacement>*/
6817
6818var Duplex;
6819/*</replacement>*/
6820
6821Readable.ReadableState = ReadableState;
6822/*<replacement>*/
6823
6824var EE = _dereq_(21).EventEmitter;
6825
6826var EElistenerCount = function EElistenerCount(emitter, type) {
6827 return emitter.listeners(type).length;
6828};
6829/*</replacement>*/
6830
6831/*<replacement>*/
6832
6833
6834var Stream = _dereq_(45);
6835/*</replacement>*/
6836
6837
6838var Buffer = _dereq_(9).Buffer;
6839
6840var OurUint8Array = global.Uint8Array || function () {};
6841
6842function _uint8ArrayToBuffer(chunk) {
6843 return Buffer.from(chunk);
6844}
6845
6846function _isUint8Array(obj) {
6847 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
6848}
6849/*<replacement>*/
6850
6851
6852var debugUtil = _dereq_(7);
6853
6854var debug;
6855
6856if (debugUtil && debugUtil.debuglog) {
6857 debug = debugUtil.debuglog('stream');
6858} else {
6859 debug = function debug() {};
6860}
6861/*</replacement>*/
6862
6863
6864var BufferList = _dereq_(40);
6865
6866var destroyImpl = _dereq_(41);
6867
6868var _require = _dereq_(44),
6869 getHighWaterMark = _require.getHighWaterMark;
6870
6871var _require$codes = _dereq_(32).codes,
6872 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
6873 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
6874 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
6875 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
6876
6877var _require2 = _dereq_(33),
6878 emitExperimentalWarning = _require2.emitExperimentalWarning; // Lazy loaded to improve the startup performance.
6879
6880
6881var StringDecoder;
6882var createReadableStreamAsyncIterator;
6883
6884_dereq_(25)(Readable, Stream);
6885
6886var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
6887
6888function prependListener(emitter, event, fn) {
6889 // Sadly this is not cacheable as some libraries bundle their own
6890 // event emitter implementation with them.
6891 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
6892 // userland ones. NEVER DO THIS. This is here only because this code needs
6893 // to continue to work with older versions of Node.js that do not include
6894 // the prependListener() method. The goal is to eventually remove this hack.
6895
6896 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]];
6897}
6898
6899function ReadableState(options, stream, isDuplex) {
6900 Duplex = Duplex || _dereq_(34);
6901 options = options || {}; // Duplex streams are both readable and writable, but share
6902 // the same options object.
6903 // However, some cases require setting options to different
6904 // values for the readable and the writable sides of the duplex stream.
6905 // These options can be provided separately as readableXXX and writableXXX.
6906
6907 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
6908 // make all the buffer merging and length checks go away
6909
6910 this.objectMode = !!options.objectMode;
6911 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
6912 // Note: 0 is a valid value, means "don't call _read preemptively ever"
6913
6914 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
6915 // linked list can remove elements from the beginning faster than
6916 // array.shift()
6917
6918 this.buffer = new BufferList();
6919 this.length = 0;
6920 this.pipes = null;
6921 this.pipesCount = 0;
6922 this.flowing = null;
6923 this.ended = false;
6924 this.endEmitted = false;
6925 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
6926 // immediately, or on a later tick. We set this to true at first, because
6927 // any actions that shouldn't happen until "later" should generally also
6928 // not happen before the first read call.
6929
6930 this.sync = true; // whenever we return null, then we set a flag to say
6931 // that we're awaiting a 'readable' event emission.
6932
6933 this.needReadable = false;
6934 this.emittedReadable = false;
6935 this.readableListening = false;
6936 this.resumeScheduled = false;
6937 this.paused = true; // Should close be emitted on destroy. Defaults to true.
6938
6939 this.emitClose = options.emitClose !== false; // has it been destroyed
6940
6941 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
6942 // encoding is 'binary' so we have to make this configurable.
6943 // Everything else in the universe uses 'utf8', though.
6944
6945 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
6946
6947 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
6948
6949 this.readingMore = false;
6950 this.decoder = null;
6951 this.encoding = null;
6952
6953 if (options.encoding) {
6954 if (!StringDecoder) StringDecoder = _dereq_(98).StringDecoder;
6955 this.decoder = new StringDecoder(options.encoding);
6956 this.encoding = options.encoding;
6957 }
6958}
6959
6960function Readable(options) {
6961 Duplex = Duplex || _dereq_(34);
6962 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
6963 // the ReadableState constructor, at least with V8 6.5
6964
6965 var isDuplex = this instanceof Duplex;
6966 this._readableState = new ReadableState(options, this, isDuplex); // legacy
6967
6968 this.readable = true;
6969
6970 if (options) {
6971 if (typeof options.read === 'function') this._read = options.read;
6972 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6973 }
6974
6975 Stream.call(this);
6976}
6977
6978Object.defineProperty(Readable.prototype, 'destroyed', {
6979 // making it explicit this property is not enumerable
6980 // because otherwise some prototype manipulation in
6981 // userland will fail
6982 enumerable: false,
6983 get: function get() {
6984 if (this._readableState === undefined) {
6985 return false;
6986 }
6987
6988 return this._readableState.destroyed;
6989 },
6990 set: function set(value) {
6991 // we ignore the value if the stream
6992 // has not been initialized yet
6993 if (!this._readableState) {
6994 return;
6995 } // backward compatibility, the user is explicitly
6996 // managing destroyed
6997
6998
6999 this._readableState.destroyed = value;
7000 }
7001});
7002Readable.prototype.destroy = destroyImpl.destroy;
7003Readable.prototype._undestroy = destroyImpl.undestroy;
7004
7005Readable.prototype._destroy = function (err, cb) {
7006 cb(err);
7007}; // Manually shove something into the read() buffer.
7008// This returns true if the highWaterMark has not been hit yet,
7009// similar to how Writable.write() returns true if you should
7010// write() some more.
7011
7012
7013Readable.prototype.push = function (chunk, encoding) {
7014 var state = this._readableState;
7015 var skipChunkCheck;
7016
7017 if (!state.objectMode) {
7018 if (typeof chunk === 'string') {
7019 encoding = encoding || state.defaultEncoding;
7020
7021 if (encoding !== state.encoding) {
7022 chunk = Buffer.from(chunk, encoding);
7023 encoding = '';
7024 }
7025
7026 skipChunkCheck = true;
7027 }
7028 } else {
7029 skipChunkCheck = true;
7030 }
7031
7032 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
7033}; // Unshift should *always* be something directly out of read()
7034
7035
7036Readable.prototype.unshift = function (chunk) {
7037 return readableAddChunk(this, chunk, null, true, false);
7038};
7039
7040function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
7041 debug('readableAddChunk', chunk);
7042 var state = stream._readableState;
7043
7044 if (chunk === null) {
7045 state.reading = false;
7046 onEofChunk(stream, state);
7047 } else {
7048 var er;
7049 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
7050
7051 if (er) {
7052 stream.emit('error', er);
7053 } else if (state.objectMode || chunk && chunk.length > 0) {
7054 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
7055 chunk = _uint8ArrayToBuffer(chunk);
7056 }
7057
7058 if (addToFront) {
7059 if (state.endEmitted) stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
7060 } else if (state.ended) {
7061 stream.emit('error', new ERR_STREAM_PUSH_AFTER_EOF());
7062 } else if (state.destroyed) {
7063 return false;
7064 } else {
7065 state.reading = false;
7066
7067 if (state.decoder && !encoding) {
7068 chunk = state.decoder.write(chunk);
7069 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
7070 } else {
7071 addChunk(stream, state, chunk, false);
7072 }
7073 }
7074 } else if (!addToFront) {
7075 state.reading = false;
7076 maybeReadMore(stream, state);
7077 }
7078 } // We can push more data if we are below the highWaterMark.
7079 // Also, if we have no data yet, we can stand some more bytes.
7080 // This is to work around cases where hwm=0, such as the repl.
7081
7082
7083 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
7084}
7085
7086function addChunk(stream, state, chunk, addToFront) {
7087 if (state.flowing && state.length === 0 && !state.sync) {
7088 state.awaitDrain = 0;
7089 stream.emit('data', chunk);
7090 } else {
7091 // update the buffer info.
7092 state.length += state.objectMode ? 1 : chunk.length;
7093 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
7094 if (state.needReadable) emitReadable(stream);
7095 }
7096
7097 maybeReadMore(stream, state);
7098}
7099
7100function chunkInvalid(state, chunk) {
7101 var er;
7102
7103 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
7104 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
7105 }
7106
7107 return er;
7108}
7109
7110Readable.prototype.isPaused = function () {
7111 return this._readableState.flowing === false;
7112}; // backwards compatibility.
7113
7114
7115Readable.prototype.setEncoding = function (enc) {
7116 if (!StringDecoder) StringDecoder = _dereq_(98).StringDecoder;
7117 this._readableState.decoder = new StringDecoder(enc); // if setEncoding(null), decoder.encoding equals utf8
7118
7119 this._readableState.encoding = this._readableState.decoder.encoding;
7120 return this;
7121}; // Don't raise the hwm > 8MB
7122
7123
7124var MAX_HWM = 0x800000;
7125
7126function computeNewHighWaterMark(n) {
7127 if (n >= MAX_HWM) {
7128 n = MAX_HWM;
7129 } else {
7130 // Get the next highest power of 2 to prevent increasing hwm excessively in
7131 // tiny amounts
7132 n--;
7133 n |= n >>> 1;
7134 n |= n >>> 2;
7135 n |= n >>> 4;
7136 n |= n >>> 8;
7137 n |= n >>> 16;
7138 n++;
7139 }
7140
7141 return n;
7142} // This function is designed to be inlinable, so please take care when making
7143// changes to the function body.
7144
7145
7146function howMuchToRead(n, state) {
7147 if (n <= 0 || state.length === 0 && state.ended) return 0;
7148 if (state.objectMode) return 1;
7149
7150 if (n !== n) {
7151 // Only flow one buffer at a time
7152 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
7153 } // If we're asking for more than the current hwm, then raise the hwm.
7154
7155
7156 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
7157 if (n <= state.length) return n; // Don't have enough
7158
7159 if (!state.ended) {
7160 state.needReadable = true;
7161 return 0;
7162 }
7163
7164 return state.length;
7165} // you can override either this method, or the async _read(n) below.
7166
7167
7168Readable.prototype.read = function (n) {
7169 debug('read', n);
7170 n = parseInt(n, 10);
7171 var state = this._readableState;
7172 var nOrig = n;
7173 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
7174 // already have a bunch of data in the buffer, then just trigger
7175 // the 'readable' event and move on.
7176
7177 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
7178 debug('read: emitReadable', state.length, state.ended);
7179 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
7180 return null;
7181 }
7182
7183 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
7184
7185 if (n === 0 && state.ended) {
7186 if (state.length === 0) endReadable(this);
7187 return null;
7188 } // All the actual chunk generation logic needs to be
7189 // *below* the call to _read. The reason is that in certain
7190 // synthetic stream cases, such as passthrough streams, _read
7191 // may be a completely synchronous operation which may change
7192 // the state of the read buffer, providing enough data when
7193 // before there was *not* enough.
7194 //
7195 // So, the steps are:
7196 // 1. Figure out what the state of things will be after we do
7197 // a read from the buffer.
7198 //
7199 // 2. If that resulting state will trigger a _read, then call _read.
7200 // Note that this may be asynchronous, or synchronous. Yes, it is
7201 // deeply ugly to write APIs this way, but that still doesn't mean
7202 // that the Readable class should behave improperly, as streams are
7203 // designed to be sync/async agnostic.
7204 // Take note if the _read call is sync or async (ie, if the read call
7205 // has returned yet), so that we know whether or not it's safe to emit
7206 // 'readable' etc.
7207 //
7208 // 3. Actually pull the requested chunks out of the buffer and return.
7209 // if we need a readable event, then we need to do some reading.
7210
7211
7212 var doRead = state.needReadable;
7213 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
7214
7215 if (state.length === 0 || state.length - n < state.highWaterMark) {
7216 doRead = true;
7217 debug('length less than watermark', doRead);
7218 } // however, if we've ended, then there's no point, and if we're already
7219 // reading, then it's unnecessary.
7220
7221
7222 if (state.ended || state.reading) {
7223 doRead = false;
7224 debug('reading or ended', doRead);
7225 } else if (doRead) {
7226 debug('do read');
7227 state.reading = true;
7228 state.sync = true; // if the length is currently zero, then we *need* a readable event.
7229
7230 if (state.length === 0) state.needReadable = true; // call internal read method
7231
7232 this._read(state.highWaterMark);
7233
7234 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
7235 // and we need to re-evaluate how much data we can return to the user.
7236
7237 if (!state.reading) n = howMuchToRead(nOrig, state);
7238 }
7239
7240 var ret;
7241 if (n > 0) ret = fromList(n, state);else ret = null;
7242
7243 if (ret === null) {
7244 state.needReadable = true;
7245 n = 0;
7246 } else {
7247 state.length -= n;
7248 state.awaitDrain = 0;
7249 }
7250
7251 if (state.length === 0) {
7252 // If we have nothing in the buffer, then we want to know
7253 // as soon as we *do* get something into the buffer.
7254 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
7255
7256 if (nOrig !== n && state.ended) endReadable(this);
7257 }
7258
7259 if (ret !== null) this.emit('data', ret);
7260 return ret;
7261};
7262
7263function onEofChunk(stream, state) {
7264 if (state.ended) return;
7265
7266 if (state.decoder) {
7267 var chunk = state.decoder.end();
7268
7269 if (chunk && chunk.length) {
7270 state.buffer.push(chunk);
7271 state.length += state.objectMode ? 1 : chunk.length;
7272 }
7273 }
7274
7275 state.ended = true;
7276
7277 if (state.sync) {
7278 // if we are sync, wait until next tick to emit the data.
7279 // Otherwise we risk emitting data in the flow()
7280 // the readable code triggers during a read() call
7281 emitReadable(stream);
7282 } else {
7283 // emit 'readable' now to make sure it gets picked up.
7284 state.needReadable = false;
7285
7286 if (!state.emittedReadable) {
7287 state.emittedReadable = true;
7288 emitReadable_(stream);
7289 }
7290 }
7291} // Don't emit readable right away in sync mode, because this can trigger
7292// another read() call => stack overflow. This way, it might trigger
7293// a nextTick recursion warning, but that's not so bad.
7294
7295
7296function emitReadable(stream) {
7297 var state = stream._readableState;
7298 state.needReadable = false;
7299
7300 if (!state.emittedReadable) {
7301 debug('emitReadable', state.flowing);
7302 state.emittedReadable = true;
7303 process.nextTick(emitReadable_, stream);
7304 }
7305}
7306
7307function emitReadable_(stream) {
7308 var state = stream._readableState;
7309 debug('emitReadable_', state.destroyed, state.length, state.ended);
7310
7311 if (!state.destroyed && (state.length || state.ended)) {
7312 stream.emit('readable');
7313 } // The stream needs another readable event if
7314 // 1. It is not flowing, as the flow mechanism will take
7315 // care of it.
7316 // 2. It is not ended.
7317 // 3. It is below the highWaterMark, so we can schedule
7318 // another readable later.
7319
7320
7321 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
7322 flow(stream);
7323} // at this point, the user has presumably seen the 'readable' event,
7324// and called read() to consume some data. that may have triggered
7325// in turn another _read(n) call, in which case reading = true if
7326// it's in progress.
7327// However, if we're not ended, or reading, and the length < hwm,
7328// then go ahead and try to read some more preemptively.
7329
7330
7331function maybeReadMore(stream, state) {
7332 if (!state.readingMore) {
7333 state.readingMore = true;
7334 process.nextTick(maybeReadMore_, stream, state);
7335 }
7336}
7337
7338function maybeReadMore_(stream, state) {
7339 // Attempt to read more data if we should.
7340 //
7341 // The conditions for reading more data are (one of):
7342 // - Not enough data buffered (state.length < state.highWaterMark). The loop
7343 // is responsible for filling the buffer with enough data if such data
7344 // is available. If highWaterMark is 0 and we are not in the flowing mode
7345 // we should _not_ attempt to buffer any extra data. We'll get more data
7346 // when the stream consumer calls read() instead.
7347 // - No data in the buffer, and the stream is in flowing mode. In this mode
7348 // the loop below is responsible for ensuring read() is called. Failing to
7349 // call read here would abort the flow and there's no other mechanism for
7350 // continuing the flow if the stream consumer has just subscribed to the
7351 // 'data' event.
7352 //
7353 // In addition to the above conditions to keep reading data, the following
7354 // conditions prevent the data from being read:
7355 // - The stream has ended (state.ended).
7356 // - There is already a pending 'read' operation (state.reading). This is a
7357 // case where the the stream has called the implementation defined _read()
7358 // method, but they are processing the call asynchronously and have _not_
7359 // called push() with new data. In this case we skip performing more
7360 // read()s. The execution ends in this method again after the _read() ends
7361 // up calling push() with more data.
7362 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
7363 var len = state.length;
7364 debug('maybeReadMore read 0');
7365 stream.read(0);
7366 if (len === state.length) // didn't get any data, stop spinning.
7367 break;
7368 }
7369
7370 state.readingMore = false;
7371} // abstract method. to be overridden in specific implementation classes.
7372// call cb(er, data) where data is <= n in length.
7373// for virtual (non-string, non-buffer) streams, "length" is somewhat
7374// arbitrary, and perhaps not very meaningful.
7375
7376
7377Readable.prototype._read = function (n) {
7378 this.emit('error', new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
7379};
7380
7381Readable.prototype.pipe = function (dest, pipeOpts) {
7382 var src = this;
7383 var state = this._readableState;
7384
7385 switch (state.pipesCount) {
7386 case 0:
7387 state.pipes = dest;
7388 break;
7389
7390 case 1:
7391 state.pipes = [state.pipes, dest];
7392 break;
7393
7394 default:
7395 state.pipes.push(dest);
7396 break;
7397 }
7398
7399 state.pipesCount += 1;
7400 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
7401 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
7402 var endFn = doEnd ? onend : unpipe;
7403 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
7404 dest.on('unpipe', onunpipe);
7405
7406 function onunpipe(readable, unpipeInfo) {
7407 debug('onunpipe');
7408
7409 if (readable === src) {
7410 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
7411 unpipeInfo.hasUnpiped = true;
7412 cleanup();
7413 }
7414 }
7415 }
7416
7417 function onend() {
7418 debug('onend');
7419 dest.end();
7420 } // when the dest drains, it reduces the awaitDrain counter
7421 // on the source. This would be more elegant with a .once()
7422 // handler in flow(), but adding and removing repeatedly is
7423 // too slow.
7424
7425
7426 var ondrain = pipeOnDrain(src);
7427 dest.on('drain', ondrain);
7428 var cleanedUp = false;
7429
7430 function cleanup() {
7431 debug('cleanup'); // cleanup event handlers once the pipe is broken
7432
7433 dest.removeListener('close', onclose);
7434 dest.removeListener('finish', onfinish);
7435 dest.removeListener('drain', ondrain);
7436 dest.removeListener('error', onerror);
7437 dest.removeListener('unpipe', onunpipe);
7438 src.removeListener('end', onend);
7439 src.removeListener('end', unpipe);
7440 src.removeListener('data', ondata);
7441 cleanedUp = true; // if the reader is waiting for a drain event from this
7442 // specific writer, then it would cause it to never start
7443 // flowing again.
7444 // So, if this is awaiting a drain, then we just call it now.
7445 // If we don't know, then assume that we are waiting for one.
7446
7447 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
7448 }
7449
7450 src.on('data', ondata);
7451
7452 function ondata(chunk) {
7453 debug('ondata');
7454 var ret = dest.write(chunk);
7455 debug('dest.write', ret);
7456
7457 if (ret === false) {
7458 // If the user unpiped during `dest.write()`, it is possible
7459 // to get stuck in a permanently paused state if that write
7460 // also returned false.
7461 // => Check whether `dest` is still a piping destination.
7462 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
7463 debug('false write response, pause', state.awaitDrain);
7464 state.awaitDrain++;
7465 }
7466
7467 src.pause();
7468 }
7469 } // if the dest has an error, then stop piping into it.
7470 // however, don't suppress the throwing behavior for this.
7471
7472
7473 function onerror(er) {
7474 debug('onerror', er);
7475 unpipe();
7476 dest.removeListener('error', onerror);
7477 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
7478 } // Make sure our error handler is attached before userland ones.
7479
7480
7481 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
7482
7483 function onclose() {
7484 dest.removeListener('finish', onfinish);
7485 unpipe();
7486 }
7487
7488 dest.once('close', onclose);
7489
7490 function onfinish() {
7491 debug('onfinish');
7492 dest.removeListener('close', onclose);
7493 unpipe();
7494 }
7495
7496 dest.once('finish', onfinish);
7497
7498 function unpipe() {
7499 debug('unpipe');
7500 src.unpipe(dest);
7501 } // tell the dest that it's being piped to
7502
7503
7504 dest.emit('pipe', src); // start the flow if it hasn't been started already.
7505
7506 if (!state.flowing) {
7507 debug('pipe resume');
7508 src.resume();
7509 }
7510
7511 return dest;
7512};
7513
7514function pipeOnDrain(src) {
7515 return function pipeOnDrainFunctionResult() {
7516 var state = src._readableState;
7517 debug('pipeOnDrain', state.awaitDrain);
7518 if (state.awaitDrain) state.awaitDrain--;
7519
7520 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
7521 state.flowing = true;
7522 flow(src);
7523 }
7524 };
7525}
7526
7527Readable.prototype.unpipe = function (dest) {
7528 var state = this._readableState;
7529 var unpipeInfo = {
7530 hasUnpiped: false
7531 }; // if we're not piping anywhere, then do nothing.
7532
7533 if (state.pipesCount === 0) return this; // just one destination. most common case.
7534
7535 if (state.pipesCount === 1) {
7536 // passed in one, but it's not the right one.
7537 if (dest && dest !== state.pipes) return this;
7538 if (!dest) dest = state.pipes; // got a match.
7539
7540 state.pipes = null;
7541 state.pipesCount = 0;
7542 state.flowing = false;
7543 if (dest) dest.emit('unpipe', this, unpipeInfo);
7544 return this;
7545 } // slow case. multiple pipe destinations.
7546
7547
7548 if (!dest) {
7549 // remove all.
7550 var dests = state.pipes;
7551 var len = state.pipesCount;
7552 state.pipes = null;
7553 state.pipesCount = 0;
7554 state.flowing = false;
7555
7556 for (var i = 0; i < len; i++) {
7557 dests[i].emit('unpipe', this, {
7558 hasUnpiped: false
7559 });
7560 }
7561
7562 return this;
7563 } // try to find the right one.
7564
7565
7566 var index = indexOf(state.pipes, dest);
7567 if (index === -1) return this;
7568 state.pipes.splice(index, 1);
7569 state.pipesCount -= 1;
7570 if (state.pipesCount === 1) state.pipes = state.pipes[0];
7571 dest.emit('unpipe', this, unpipeInfo);
7572 return this;
7573}; // set up data events if they are asked for
7574// Ensure readable listeners eventually get something
7575
7576
7577Readable.prototype.on = function (ev, fn) {
7578 var res = Stream.prototype.on.call(this, ev, fn);
7579 var state = this._readableState;
7580
7581 if (ev === 'data') {
7582 // update readableListening so that resume() may be a no-op
7583 // a few lines down. This is needed to support once('readable').
7584 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
7585
7586 if (state.flowing !== false) this.resume();
7587 } else if (ev === 'readable') {
7588 if (!state.endEmitted && !state.readableListening) {
7589 state.readableListening = state.needReadable = true;
7590 state.flowing = false;
7591 state.emittedReadable = false;
7592 debug('on readable', state.length, state.reading);
7593
7594 if (state.length) {
7595 emitReadable(this);
7596 } else if (!state.reading) {
7597 process.nextTick(nReadingNextTick, this);
7598 }
7599 }
7600 }
7601
7602 return res;
7603};
7604
7605Readable.prototype.addListener = Readable.prototype.on;
7606
7607Readable.prototype.removeListener = function (ev, fn) {
7608 var res = Stream.prototype.removeListener.call(this, ev, fn);
7609
7610 if (ev === 'readable') {
7611 // We need to check if there is someone still listening to
7612 // readable and reset the state. However this needs to happen
7613 // after readable has been emitted but before I/O (nextTick) to
7614 // support once('readable', fn) cycles. This means that calling
7615 // resume within the same tick will have no
7616 // effect.
7617 process.nextTick(updateReadableListening, this);
7618 }
7619
7620 return res;
7621};
7622
7623Readable.prototype.removeAllListeners = function (ev) {
7624 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
7625
7626 if (ev === 'readable' || ev === undefined) {
7627 // We need to check if there is someone still listening to
7628 // readable and reset the state. However this needs to happen
7629 // after readable has been emitted but before I/O (nextTick) to
7630 // support once('readable', fn) cycles. This means that calling
7631 // resume within the same tick will have no
7632 // effect.
7633 process.nextTick(updateReadableListening, this);
7634 }
7635
7636 return res;
7637};
7638
7639function updateReadableListening(self) {
7640 var state = self._readableState;
7641 state.readableListening = self.listenerCount('readable') > 0;
7642
7643 if (state.resumeScheduled && !state.paused) {
7644 // flowing needs to be set to true now, otherwise
7645 // the upcoming resume will not flow.
7646 state.flowing = true; // crude way to check if we should resume
7647 } else if (self.listenerCount('data') > 0) {
7648 self.resume();
7649 }
7650}
7651
7652function nReadingNextTick(self) {
7653 debug('readable nexttick read 0');
7654 self.read(0);
7655} // pause() and resume() are remnants of the legacy readable stream API
7656// If the user uses them, then switch into old mode.
7657
7658
7659Readable.prototype.resume = function () {
7660 var state = this._readableState;
7661
7662 if (!state.flowing) {
7663 debug('resume'); // we flow only if there is no one listening
7664 // for readable, but we still have to call
7665 // resume()
7666
7667 state.flowing = !state.readableListening;
7668 resume(this, state);
7669 }
7670
7671 state.paused = false;
7672 return this;
7673};
7674
7675function resume(stream, state) {
7676 if (!state.resumeScheduled) {
7677 state.resumeScheduled = true;
7678 process.nextTick(resume_, stream, state);
7679 }
7680}
7681
7682function resume_(stream, state) {
7683 debug('resume', state.reading);
7684
7685 if (!state.reading) {
7686 stream.read(0);
7687 }
7688
7689 state.resumeScheduled = false;
7690 stream.emit('resume');
7691 flow(stream);
7692 if (state.flowing && !state.reading) stream.read(0);
7693}
7694
7695Readable.prototype.pause = function () {
7696 debug('call pause flowing=%j', this._readableState.flowing);
7697
7698 if (this._readableState.flowing !== false) {
7699 debug('pause');
7700 this._readableState.flowing = false;
7701 this.emit('pause');
7702 }
7703
7704 this._readableState.paused = true;
7705 return this;
7706};
7707
7708function flow(stream) {
7709 var state = stream._readableState;
7710 debug('flow', state.flowing);
7711
7712 while (state.flowing && stream.read() !== null) {
7713 ;
7714 }
7715} // wrap an old-style stream as the async data source.
7716// This is *not* part of the readable stream interface.
7717// It is an ugly unfortunate mess of history.
7718
7719
7720Readable.prototype.wrap = function (stream) {
7721 var _this = this;
7722
7723 var state = this._readableState;
7724 var paused = false;
7725 stream.on('end', function () {
7726 debug('wrapped end');
7727
7728 if (state.decoder && !state.ended) {
7729 var chunk = state.decoder.end();
7730 if (chunk && chunk.length) _this.push(chunk);
7731 }
7732
7733 _this.push(null);
7734 });
7735 stream.on('data', function (chunk) {
7736 debug('wrapped data');
7737 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
7738
7739 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
7740
7741 var ret = _this.push(chunk);
7742
7743 if (!ret) {
7744 paused = true;
7745 stream.pause();
7746 }
7747 }); // proxy all the other methods.
7748 // important when wrapping filters and duplexes.
7749
7750 for (var i in stream) {
7751 if (this[i] === undefined && typeof stream[i] === 'function') {
7752 this[i] = function methodWrap(method) {
7753 return function methodWrapReturnFunction() {
7754 return stream[method].apply(stream, arguments);
7755 };
7756 }(i);
7757 }
7758 } // proxy certain important events.
7759
7760
7761 for (var n = 0; n < kProxyEvents.length; n++) {
7762 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
7763 } // when we try to consume some more bytes, simply unpause the
7764 // underlying stream.
7765
7766
7767 this._read = function (n) {
7768 debug('wrapped _read', n);
7769
7770 if (paused) {
7771 paused = false;
7772 stream.resume();
7773 }
7774 };
7775
7776 return this;
7777};
7778
7779if (typeof Symbol === 'function') {
7780 Readable.prototype[Symbol.asyncIterator] = function () {
7781 emitExperimentalWarning('Readable[Symbol.asyncIterator]');
7782
7783 if (createReadableStreamAsyncIterator === undefined) {
7784 createReadableStreamAsyncIterator = _dereq_(39);
7785 }
7786
7787 return createReadableStreamAsyncIterator(this);
7788 };
7789}
7790
7791Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
7792 // making it explicit this property is not enumerable
7793 // because otherwise some prototype manipulation in
7794 // userland will fail
7795 enumerable: false,
7796 get: function get() {
7797 return this._readableState.highWaterMark;
7798 }
7799});
7800Object.defineProperty(Readable.prototype, 'readableBuffer', {
7801 // making it explicit this property is not enumerable
7802 // because otherwise some prototype manipulation in
7803 // userland will fail
7804 enumerable: false,
7805 get: function get() {
7806 return this._readableState && this._readableState.buffer;
7807 }
7808});
7809Object.defineProperty(Readable.prototype, 'readableFlowing', {
7810 // making it explicit this property is not enumerable
7811 // because otherwise some prototype manipulation in
7812 // userland will fail
7813 enumerable: false,
7814 get: function get() {
7815 return this._readableState.flowing;
7816 },
7817 set: function set(state) {
7818 if (this._readableState) {
7819 this._readableState.flowing = state;
7820 }
7821 }
7822}); // exposed for testing purposes only.
7823
7824Readable._fromList = fromList;
7825Object.defineProperty(Readable.prototype, 'readableLength', {
7826 // making it explicit this property is not enumerable
7827 // because otherwise some prototype manipulation in
7828 // userland will fail
7829 enumerable: false,
7830 get: function get() {
7831 return this._readableState.length;
7832 }
7833}); // Pluck off n bytes from an array of buffers.
7834// Length is the combined lengths of all the buffers in the list.
7835// This function is designed to be inlinable, so please take care when making
7836// changes to the function body.
7837
7838function fromList(n, state) {
7839 // nothing buffered
7840 if (state.length === 0) return null;
7841 var ret;
7842 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
7843 // read it all, truncate the list
7844 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
7845 state.buffer.clear();
7846 } else {
7847 // read part of list
7848 ret = state.buffer.consume(n, state.decoder);
7849 }
7850 return ret;
7851}
7852
7853function endReadable(stream) {
7854 var state = stream._readableState;
7855 debug('endReadable', state.endEmitted);
7856
7857 if (!state.endEmitted) {
7858 state.ended = true;
7859 process.nextTick(endReadableNT, state, stream);
7860 }
7861}
7862
7863function endReadableNT(state, stream) {
7864 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
7865
7866 if (!state.endEmitted && state.length === 0) {
7867 state.endEmitted = true;
7868 stream.readable = false;
7869 stream.emit('end');
7870 }
7871}
7872
7873function indexOf(xs, x) {
7874 for (var i = 0, l = xs.length; i < l; i++) {
7875 if (xs[i] === x) return i;
7876 }
7877
7878 return -1;
7879}
7880}).call(this,_dereq_(71),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7881},{"21":21,"25":25,"32":32,"33":33,"34":34,"39":39,"40":40,"41":41,"44":44,"45":45,"7":7,"71":71,"9":9,"98":98}],37:[function(_dereq_,module,exports){
7882// Copyright Joyent, Inc. and other Node contributors.
7883//
7884// Permission is hereby granted, free of charge, to any person obtaining a
7885// copy of this software and associated documentation files (the
7886// "Software"), to deal in the Software without restriction, including
7887// without limitation the rights to use, copy, modify, merge, publish,
7888// distribute, sublicense, and/or sell copies of the Software, and to permit
7889// persons to whom the Software is furnished to do so, subject to the
7890// following conditions:
7891//
7892// The above copyright notice and this permission notice shall be included
7893// in all copies or substantial portions of the Software.
7894//
7895// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7896// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7897// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7898// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7899// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7900// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7901// USE OR OTHER DEALINGS IN THE SOFTWARE.
7902// a transform stream is a readable/writable stream where you do
7903// something with the data. Sometimes it's called a "filter",
7904// but that's not a great name for it, since that implies a thing where
7905// some bits pass through, and others are simply ignored. (That would
7906// be a valid example of a transform, of course.)
7907//
7908// While the output is causally related to the input, it's not a
7909// necessarily symmetric or synchronous transformation. For example,
7910// a zlib stream might take multiple plain-text writes(), and then
7911// emit a single compressed chunk some time in the future.
7912//
7913// Here's how this works:
7914//
7915// The Transform stream has all the aspects of the readable and writable
7916// stream classes. When you write(chunk), that calls _write(chunk,cb)
7917// internally, and returns false if there's a lot of pending writes
7918// buffered up. When you call read(), that calls _read(n) until
7919// there's enough pending readable data buffered up.
7920//
7921// In a transform stream, the written data is placed in a buffer. When
7922// _read(n) is called, it transforms the queued up data, calling the
7923// buffered _write cb's as it consumes chunks. If consuming a single
7924// written chunk would result in multiple output chunks, then the first
7925// outputted bit calls the readcb, and subsequent chunks just go into
7926// the read buffer, and will cause it to emit 'readable' if necessary.
7927//
7928// This way, back-pressure is actually determined by the reading side,
7929// since _read has to be called to start processing a new chunk. However,
7930// a pathological inflate type of transform can cause excessive buffering
7931// here. For example, imagine a stream where every byte of input is
7932// interpreted as an integer from 0-255, and then results in that many
7933// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
7934// 1kb of data being output. In this case, you could write a very small
7935// amount of input, and end up with a very large amount of output. In
7936// such a pathological inflating mechanism, there'd be no way to tell
7937// the system to stop doing the transform. A single 4MB write could
7938// cause the system to run out of memory.
7939//
7940// However, even in such a pathological case, only a single written chunk
7941// would be consumed, and then the rest would wait (un-transformed) until
7942// the results of the previous transformed chunk were consumed.
7943'use strict';
7944
7945module.exports = Transform;
7946
7947var _require$codes = _dereq_(32).codes,
7948 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7949 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
7950 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
7951 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
7952
7953var Duplex = _dereq_(34);
7954
7955_dereq_(25)(Transform, Duplex);
7956
7957function afterTransform(er, data) {
7958 var ts = this._transformState;
7959 ts.transforming = false;
7960 var cb = ts.writecb;
7961
7962 if (cb === null) {
7963 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
7964 }
7965
7966 ts.writechunk = null;
7967 ts.writecb = null;
7968 if (data != null) // single equals check for both `null` and `undefined`
7969 this.push(data);
7970 cb(er);
7971 var rs = this._readableState;
7972 rs.reading = false;
7973
7974 if (rs.needReadable || rs.length < rs.highWaterMark) {
7975 this._read(rs.highWaterMark);
7976 }
7977}
7978
7979function Transform(options) {
7980 if (!(this instanceof Transform)) return new Transform(options);
7981 Duplex.call(this, options);
7982 this._transformState = {
7983 afterTransform: afterTransform.bind(this),
7984 needTransform: false,
7985 transforming: false,
7986 writecb: null,
7987 writechunk: null,
7988 writeencoding: null
7989 }; // start out asking for a readable event once data is transformed.
7990
7991 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
7992 // that Readable wants before the first _read call, so unset the
7993 // sync guard flag.
7994
7995 this._readableState.sync = false;
7996
7997 if (options) {
7998 if (typeof options.transform === 'function') this._transform = options.transform;
7999 if (typeof options.flush === 'function') this._flush = options.flush;
8000 } // When the writable side finishes, then flush out anything remaining.
8001
8002
8003 this.on('prefinish', prefinish);
8004}
8005
8006function prefinish() {
8007 var _this = this;
8008
8009 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
8010 this._flush(function (er, data) {
8011 done(_this, er, data);
8012 });
8013 } else {
8014 done(this, null, null);
8015 }
8016}
8017
8018Transform.prototype.push = function (chunk, encoding) {
8019 this._transformState.needTransform = false;
8020 return Duplex.prototype.push.call(this, chunk, encoding);
8021}; // This is the part where you do stuff!
8022// override this function in implementation classes.
8023// 'chunk' is an input chunk.
8024//
8025// Call `push(newChunk)` to pass along transformed output
8026// to the readable side. You may call 'push' zero or more times.
8027//
8028// Call `cb(err)` when you are done with this chunk. If you pass
8029// an error, then that'll put the hurt on the whole operation. If you
8030// never call cb(), then you'll never get another chunk.
8031
8032
8033Transform.prototype._transform = function (chunk, encoding, cb) {
8034 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
8035};
8036
8037Transform.prototype._write = function (chunk, encoding, cb) {
8038 var ts = this._transformState;
8039 ts.writecb = cb;
8040 ts.writechunk = chunk;
8041 ts.writeencoding = encoding;
8042
8043 if (!ts.transforming) {
8044 var rs = this._readableState;
8045 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
8046 }
8047}; // Doesn't matter what the args are here.
8048// _transform does all the work.
8049// That we got here means that the readable side wants more data.
8050
8051
8052Transform.prototype._read = function (n) {
8053 var ts = this._transformState;
8054
8055 if (ts.writechunk !== null && !ts.transforming) {
8056 ts.transforming = true;
8057
8058 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
8059 } else {
8060 // mark that we need a transform, so that any data that comes in
8061 // will get processed, now that we've asked for it.
8062 ts.needTransform = true;
8063 }
8064};
8065
8066Transform.prototype._destroy = function (err, cb) {
8067 Duplex.prototype._destroy.call(this, err, function (err2) {
8068 cb(err2);
8069 });
8070};
8071
8072function done(stream, er, data) {
8073 if (er) return stream.emit('error', er);
8074 if (data != null) // single equals check for both `null` and `undefined`
8075 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
8076 // if there's nothing in the write buffer, then that means
8077 // that nothing more will ever be provided
8078
8079 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
8080 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
8081 return stream.push(null);
8082}
8083},{"25":25,"32":32,"34":34}],38:[function(_dereq_,module,exports){
8084(function (process,global){
8085// Copyright Joyent, Inc. and other Node contributors.
8086//
8087// Permission is hereby granted, free of charge, to any person obtaining a
8088// copy of this software and associated documentation files (the
8089// "Software"), to deal in the Software without restriction, including
8090// without limitation the rights to use, copy, modify, merge, publish,
8091// distribute, sublicense, and/or sell copies of the Software, and to permit
8092// persons to whom the Software is furnished to do so, subject to the
8093// following conditions:
8094//
8095// The above copyright notice and this permission notice shall be included
8096// in all copies or substantial portions of the Software.
8097//
8098// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8099// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8100// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8101// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8102// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8103// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8104// USE OR OTHER DEALINGS IN THE SOFTWARE.
8105// A bit simpler than readable streams.
8106// Implement an async ._write(chunk, encoding, cb), and it'll handle all
8107// the drain event emission and buffering.
8108'use strict';
8109
8110module.exports = Writable;
8111/* <replacement> */
8112
8113function WriteReq(chunk, encoding, cb) {
8114 this.chunk = chunk;
8115 this.encoding = encoding;
8116 this.callback = cb;
8117 this.next = null;
8118} // It seems a linked list but it is not
8119// there will be only 2 of these for each stream
8120
8121
8122function CorkedRequest(state) {
8123 var _this = this;
8124
8125 this.next = null;
8126 this.entry = null;
8127
8128 this.finish = function () {
8129 onCorkedFinish(_this, state);
8130 };
8131}
8132/* </replacement> */
8133
8134/*<replacement>*/
8135
8136
8137var Duplex;
8138/*</replacement>*/
8139
8140Writable.WritableState = WritableState;
8141/*<replacement>*/
8142
8143var internalUtil = {
8144 deprecate: _dereq_(116)
8145};
8146/*</replacement>*/
8147
8148/*<replacement>*/
8149
8150var Stream = _dereq_(45);
8151/*</replacement>*/
8152
8153
8154var Buffer = _dereq_(9).Buffer;
8155
8156var OurUint8Array = global.Uint8Array || function () {};
8157
8158function _uint8ArrayToBuffer(chunk) {
8159 return Buffer.from(chunk);
8160}
8161
8162function _isUint8Array(obj) {
8163 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
8164}
8165
8166var destroyImpl = _dereq_(41);
8167
8168var _require = _dereq_(44),
8169 getHighWaterMark = _require.getHighWaterMark;
8170
8171var _require$codes = _dereq_(32).codes,
8172 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
8173 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
8174 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
8175 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
8176 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
8177 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
8178 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
8179 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
8180
8181_dereq_(25)(Writable, Stream);
8182
8183function nop() {}
8184
8185function WritableState(options, stream, isDuplex) {
8186 Duplex = Duplex || _dereq_(34);
8187 options = options || {}; // Duplex streams are both readable and writable, but share
8188 // the same options object.
8189 // However, some cases require setting options to different
8190 // values for the readable and the writable sides of the duplex stream,
8191 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
8192
8193 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
8194 // contains buffers or objects.
8195
8196 this.objectMode = !!options.objectMode;
8197 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
8198 // Note: 0 is a valid value, means that we always return false if
8199 // the entire buffer is not flushed immediately on write()
8200
8201 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
8202
8203 this.finalCalled = false; // drain event flag.
8204
8205 this.needDrain = false; // at the start of calling end()
8206
8207 this.ending = false; // when end() has been called, and returned
8208
8209 this.ended = false; // when 'finish' is emitted
8210
8211 this.finished = false; // has it been destroyed
8212
8213 this.destroyed = false; // should we decode strings into buffers before passing to _write?
8214 // this is here so that some node-core streams can optimize string
8215 // handling at a lower level.
8216
8217 var noDecode = options.decodeStrings === false;
8218 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
8219 // encoding is 'binary' so we have to make this configurable.
8220 // Everything else in the universe uses 'utf8', though.
8221
8222 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
8223 // of how much we're waiting to get pushed to some underlying
8224 // socket or file.
8225
8226 this.length = 0; // a flag to see when we're in the middle of a write.
8227
8228 this.writing = false; // when true all writes will be buffered until .uncork() call
8229
8230 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
8231 // or on a later tick. We set this to true at first, because any
8232 // actions that shouldn't happen until "later" should generally also
8233 // not happen before the first write call.
8234
8235 this.sync = true; // a flag to know if we're processing previously buffered items, which
8236 // may call the _write() callback in the same tick, so that we don't
8237 // end up in an overlapped onwrite situation.
8238
8239 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
8240
8241 this.onwrite = function (er) {
8242 onwrite(stream, er);
8243 }; // the callback that the user supplies to write(chunk,encoding,cb)
8244
8245
8246 this.writecb = null; // the amount that is being written when _write is called.
8247
8248 this.writelen = 0;
8249 this.bufferedRequest = null;
8250 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
8251 // this must be 0 before 'finish' can be emitted
8252
8253 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
8254 // This is relevant for synchronous Transform streams
8255
8256 this.prefinished = false; // True if the error was already emitted and should not be thrown again
8257
8258 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
8259
8260 this.emitClose = options.emitClose !== false; // count buffered requests
8261
8262 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
8263 // one allocated and free to use, and we maintain at most two
8264
8265 this.corkedRequestsFree = new CorkedRequest(this);
8266}
8267
8268WritableState.prototype.getBuffer = function getBuffer() {
8269 var current = this.bufferedRequest;
8270 var out = [];
8271
8272 while (current) {
8273 out.push(current);
8274 current = current.next;
8275 }
8276
8277 return out;
8278};
8279
8280(function () {
8281 try {
8282 Object.defineProperty(WritableState.prototype, 'buffer', {
8283 get: internalUtil.deprecate(function writableStateBufferGetter() {
8284 return this.getBuffer();
8285 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
8286 });
8287 } catch (_) {}
8288})(); // Test _writableState for inheritance to account for Duplex streams,
8289// whose prototype chain only points to Readable.
8290
8291
8292var realHasInstance;
8293
8294if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
8295 realHasInstance = Function.prototype[Symbol.hasInstance];
8296 Object.defineProperty(Writable, Symbol.hasInstance, {
8297 value: function value(object) {
8298 if (realHasInstance.call(this, object)) return true;
8299 if (this !== Writable) return false;
8300 return object && object._writableState instanceof WritableState;
8301 }
8302 });
8303} else {
8304 realHasInstance = function realHasInstance(object) {
8305 return object instanceof this;
8306 };
8307}
8308
8309function Writable(options) {
8310 Duplex = Duplex || _dereq_(34); // Writable ctor is applied to Duplexes, too.
8311 // `realHasInstance` is necessary because using plain `instanceof`
8312 // would return false, as no `_writableState` property is attached.
8313 // Trying to use the custom `instanceof` for Writable here will also break the
8314 // Node.js LazyTransform implementation, which has a non-trivial getter for
8315 // `_writableState` that would lead to infinite recursion.
8316 // Checking for a Stream.Duplex instance is faster here instead of inside
8317 // the WritableState constructor, at least with V8 6.5
8318
8319 var isDuplex = this instanceof Duplex;
8320 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
8321 this._writableState = new WritableState(options, this, isDuplex); // legacy.
8322
8323 this.writable = true;
8324
8325 if (options) {
8326 if (typeof options.write === 'function') this._write = options.write;
8327 if (typeof options.writev === 'function') this._writev = options.writev;
8328 if (typeof options.destroy === 'function') this._destroy = options.destroy;
8329 if (typeof options.final === 'function') this._final = options.final;
8330 }
8331
8332 Stream.call(this);
8333} // Otherwise people can pipe Writable streams, which is just wrong.
8334
8335
8336Writable.prototype.pipe = function () {
8337 this.emit('error', new ERR_STREAM_CANNOT_PIPE());
8338};
8339
8340function writeAfterEnd(stream, cb) {
8341 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
8342
8343 stream.emit('error', er);
8344 process.nextTick(cb, er);
8345} // Checks that a user-supplied chunk is valid, especially for the particular
8346// mode the stream is in. Currently this means that `null` is never accepted
8347// and undefined/non-string values are only allowed in object mode.
8348
8349
8350function validChunk(stream, state, chunk, cb) {
8351 var er;
8352
8353 if (chunk === null) {
8354 er = new ERR_STREAM_NULL_VALUES();
8355 } else if (typeof chunk !== 'string' && !state.objectMode) {
8356 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
8357 }
8358
8359 if (er) {
8360 stream.emit('error', er);
8361 process.nextTick(cb, er);
8362 return false;
8363 }
8364
8365 return true;
8366}
8367
8368Writable.prototype.write = function (chunk, encoding, cb) {
8369 var state = this._writableState;
8370 var ret = false;
8371
8372 var isBuf = !state.objectMode && _isUint8Array(chunk);
8373
8374 if (isBuf && !Buffer.isBuffer(chunk)) {
8375 chunk = _uint8ArrayToBuffer(chunk);
8376 }
8377
8378 if (typeof encoding === 'function') {
8379 cb = encoding;
8380 encoding = null;
8381 }
8382
8383 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
8384 if (typeof cb !== 'function') cb = nop;
8385 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
8386 state.pendingcb++;
8387 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
8388 }
8389 return ret;
8390};
8391
8392Writable.prototype.cork = function () {
8393 this._writableState.corked++;
8394};
8395
8396Writable.prototype.uncork = function () {
8397 var state = this._writableState;
8398
8399 if (state.corked) {
8400 state.corked--;
8401 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
8402 }
8403};
8404
8405Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
8406 // node::ParseEncoding() requires lower case.
8407 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
8408 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);
8409 this._writableState.defaultEncoding = encoding;
8410 return this;
8411};
8412
8413Object.defineProperty(Writable.prototype, 'writableBuffer', {
8414 // making it explicit this property is not enumerable
8415 // because otherwise some prototype manipulation in
8416 // userland will fail
8417 enumerable: false,
8418 get: function get() {
8419 return this._writableState && this._writableState.getBuffer();
8420 }
8421});
8422
8423function decodeChunk(state, chunk, encoding) {
8424 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
8425 chunk = Buffer.from(chunk, encoding);
8426 }
8427
8428 return chunk;
8429}
8430
8431Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
8432 // making it explicit this property is not enumerable
8433 // because otherwise some prototype manipulation in
8434 // userland will fail
8435 enumerable: false,
8436 get: function get() {
8437 return this._writableState.highWaterMark;
8438 }
8439}); // if we're already writing something, then just put this
8440// in the queue, and wait our turn. Otherwise, call _write
8441// If we return false, then we need a drain event, so set that flag.
8442
8443function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
8444 if (!isBuf) {
8445 var newChunk = decodeChunk(state, chunk, encoding);
8446
8447 if (chunk !== newChunk) {
8448 isBuf = true;
8449 encoding = 'buffer';
8450 chunk = newChunk;
8451 }
8452 }
8453
8454 var len = state.objectMode ? 1 : chunk.length;
8455 state.length += len;
8456 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
8457
8458 if (!ret) state.needDrain = true;
8459
8460 if (state.writing || state.corked) {
8461 var last = state.lastBufferedRequest;
8462 state.lastBufferedRequest = {
8463 chunk: chunk,
8464 encoding: encoding,
8465 isBuf: isBuf,
8466 callback: cb,
8467 next: null
8468 };
8469
8470 if (last) {
8471 last.next = state.lastBufferedRequest;
8472 } else {
8473 state.bufferedRequest = state.lastBufferedRequest;
8474 }
8475
8476 state.bufferedRequestCount += 1;
8477 } else {
8478 doWrite(stream, state, false, len, chunk, encoding, cb);
8479 }
8480
8481 return ret;
8482}
8483
8484function doWrite(stream, state, writev, len, chunk, encoding, cb) {
8485 state.writelen = len;
8486 state.writecb = cb;
8487 state.writing = true;
8488 state.sync = true;
8489 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);
8490 state.sync = false;
8491}
8492
8493function onwriteError(stream, state, sync, er, cb) {
8494 --state.pendingcb;
8495
8496 if (sync) {
8497 // defer the callback if we are being called synchronously
8498 // to avoid piling up things on the stack
8499 process.nextTick(cb, er); // this can emit finish, and it will always happen
8500 // after error
8501
8502 process.nextTick(finishMaybe, stream, state);
8503 stream._writableState.errorEmitted = true;
8504 stream.emit('error', er);
8505 } else {
8506 // the caller expect this to happen before if
8507 // it is async
8508 cb(er);
8509 stream._writableState.errorEmitted = true;
8510 stream.emit('error', er); // this can emit finish, but finish must
8511 // always follow error
8512
8513 finishMaybe(stream, state);
8514 }
8515}
8516
8517function onwriteStateUpdate(state) {
8518 state.writing = false;
8519 state.writecb = null;
8520 state.length -= state.writelen;
8521 state.writelen = 0;
8522}
8523
8524function onwrite(stream, er) {
8525 var state = stream._writableState;
8526 var sync = state.sync;
8527 var cb = state.writecb;
8528 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
8529 onwriteStateUpdate(state);
8530 if (er) onwriteError(stream, state, sync, er, cb);else {
8531 // Check if we're actually ready to finish, but don't emit yet
8532 var finished = needFinish(state) || stream.destroyed;
8533
8534 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
8535 clearBuffer(stream, state);
8536 }
8537
8538 if (sync) {
8539 process.nextTick(afterWrite, stream, state, finished, cb);
8540 } else {
8541 afterWrite(stream, state, finished, cb);
8542 }
8543 }
8544}
8545
8546function afterWrite(stream, state, finished, cb) {
8547 if (!finished) onwriteDrain(stream, state);
8548 state.pendingcb--;
8549 cb();
8550 finishMaybe(stream, state);
8551} // Must force callback to be called on nextTick, so that we don't
8552// emit 'drain' before the write() consumer gets the 'false' return
8553// value, and has a chance to attach a 'drain' listener.
8554
8555
8556function onwriteDrain(stream, state) {
8557 if (state.length === 0 && state.needDrain) {
8558 state.needDrain = false;
8559 stream.emit('drain');
8560 }
8561} // if there's something in the buffer waiting, then process it
8562
8563
8564function clearBuffer(stream, state) {
8565 state.bufferProcessing = true;
8566 var entry = state.bufferedRequest;
8567
8568 if (stream._writev && entry && entry.next) {
8569 // Fast case, write everything using _writev()
8570 var l = state.bufferedRequestCount;
8571 var buffer = new Array(l);
8572 var holder = state.corkedRequestsFree;
8573 holder.entry = entry;
8574 var count = 0;
8575 var allBuffers = true;
8576
8577 while (entry) {
8578 buffer[count] = entry;
8579 if (!entry.isBuf) allBuffers = false;
8580 entry = entry.next;
8581 count += 1;
8582 }
8583
8584 buffer.allBuffers = allBuffers;
8585 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
8586 // as the hot path ends with doWrite
8587
8588 state.pendingcb++;
8589 state.lastBufferedRequest = null;
8590
8591 if (holder.next) {
8592 state.corkedRequestsFree = holder.next;
8593 holder.next = null;
8594 } else {
8595 state.corkedRequestsFree = new CorkedRequest(state);
8596 }
8597
8598 state.bufferedRequestCount = 0;
8599 } else {
8600 // Slow case, write chunks one-by-one
8601 while (entry) {
8602 var chunk = entry.chunk;
8603 var encoding = entry.encoding;
8604 var cb = entry.callback;
8605 var len = state.objectMode ? 1 : chunk.length;
8606 doWrite(stream, state, false, len, chunk, encoding, cb);
8607 entry = entry.next;
8608 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
8609 // it means that we need to wait until it does.
8610 // also, that means that the chunk and cb are currently
8611 // being processed, so move the buffer counter past them.
8612
8613 if (state.writing) {
8614 break;
8615 }
8616 }
8617
8618 if (entry === null) state.lastBufferedRequest = null;
8619 }
8620
8621 state.bufferedRequest = entry;
8622 state.bufferProcessing = false;
8623}
8624
8625Writable.prototype._write = function (chunk, encoding, cb) {
8626 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
8627};
8628
8629Writable.prototype._writev = null;
8630
8631Writable.prototype.end = function (chunk, encoding, cb) {
8632 var state = this._writableState;
8633
8634 if (typeof chunk === 'function') {
8635 cb = chunk;
8636 chunk = null;
8637 encoding = null;
8638 } else if (typeof encoding === 'function') {
8639 cb = encoding;
8640 encoding = null;
8641 }
8642
8643 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
8644
8645 if (state.corked) {
8646 state.corked = 1;
8647 this.uncork();
8648 } // ignore unnecessary end() calls.
8649
8650
8651 if (!state.ending) endWritable(this, state, cb);
8652 return this;
8653};
8654
8655Object.defineProperty(Writable.prototype, 'writableLength', {
8656 // making it explicit this property is not enumerable
8657 // because otherwise some prototype manipulation in
8658 // userland will fail
8659 enumerable: false,
8660 get: function get() {
8661 return this._writableState.length;
8662 }
8663});
8664
8665function needFinish(state) {
8666 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
8667}
8668
8669function callFinal(stream, state) {
8670 stream._final(function (err) {
8671 state.pendingcb--;
8672
8673 if (err) {
8674 stream.emit('error', err);
8675 }
8676
8677 state.prefinished = true;
8678 stream.emit('prefinish');
8679 finishMaybe(stream, state);
8680 });
8681}
8682
8683function prefinish(stream, state) {
8684 if (!state.prefinished && !state.finalCalled) {
8685 if (typeof stream._final === 'function' && !state.destroyed) {
8686 state.pendingcb++;
8687 state.finalCalled = true;
8688 process.nextTick(callFinal, stream, state);
8689 } else {
8690 state.prefinished = true;
8691 stream.emit('prefinish');
8692 }
8693 }
8694}
8695
8696function finishMaybe(stream, state) {
8697 var need = needFinish(state);
8698
8699 if (need) {
8700 prefinish(stream, state);
8701
8702 if (state.pendingcb === 0) {
8703 state.finished = true;
8704 stream.emit('finish');
8705 }
8706 }
8707
8708 return need;
8709}
8710
8711function endWritable(stream, state, cb) {
8712 state.ending = true;
8713 finishMaybe(stream, state);
8714
8715 if (cb) {
8716 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
8717 }
8718
8719 state.ended = true;
8720 stream.writable = false;
8721}
8722
8723function onCorkedFinish(corkReq, state, err) {
8724 var entry = corkReq.entry;
8725 corkReq.entry = null;
8726
8727 while (entry) {
8728 var cb = entry.callback;
8729 state.pendingcb--;
8730 cb(err);
8731 entry = entry.next;
8732 } // reuse the free corkReq.
8733
8734
8735 state.corkedRequestsFree.next = corkReq;
8736}
8737
8738Object.defineProperty(Writable.prototype, 'destroyed', {
8739 // making it explicit this property is not enumerable
8740 // because otherwise some prototype manipulation in
8741 // userland will fail
8742 enumerable: false,
8743 get: function get() {
8744 if (this._writableState === undefined) {
8745 return false;
8746 }
8747
8748 return this._writableState.destroyed;
8749 },
8750 set: function set(value) {
8751 // we ignore the value if the stream
8752 // has not been initialized yet
8753 if (!this._writableState) {
8754 return;
8755 } // backward compatibility, the user is explicitly
8756 // managing destroyed
8757
8758
8759 this._writableState.destroyed = value;
8760 }
8761});
8762Writable.prototype.destroy = destroyImpl.destroy;
8763Writable.prototype._undestroy = destroyImpl.undestroy;
8764
8765Writable.prototype._destroy = function (err, cb) {
8766 cb(err);
8767};
8768}).call(this,_dereq_(71),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8769},{"116":116,"25":25,"32":32,"34":34,"41":41,"44":44,"45":45,"71":71,"9":9}],39:[function(_dereq_,module,exports){
8770(function (process){
8771'use strict';
8772
8773var _Object$setPrototypeO;
8774
8775function _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; }
8776
8777var finished = _dereq_(42);
8778
8779var kLastResolve = Symbol('lastResolve');
8780var kLastReject = Symbol('lastReject');
8781var kError = Symbol('error');
8782var kEnded = Symbol('ended');
8783var kLastPromise = Symbol('lastPromise');
8784var kHandlePromise = Symbol('handlePromise');
8785var kStream = Symbol('stream');
8786
8787function createIterResult(value, done) {
8788 return {
8789 value: value,
8790 done: done
8791 };
8792}
8793
8794function readAndResolve(iter) {
8795 var resolve = iter[kLastResolve];
8796
8797 if (resolve !== null) {
8798 var data = iter[kStream].read(); // we defer if data is null
8799 // we can be expecting either 'end' or
8800 // 'error'
8801
8802 if (data !== null) {
8803 iter[kLastPromise] = null;
8804 iter[kLastResolve] = null;
8805 iter[kLastReject] = null;
8806 resolve(createIterResult(data, false));
8807 }
8808 }
8809}
8810
8811function onReadable(iter) {
8812 // we wait for the next tick, because it might
8813 // emit an error with process.nextTick
8814 process.nextTick(readAndResolve, iter);
8815}
8816
8817function wrapForNext(lastPromise, iter) {
8818 return function (resolve, reject) {
8819 lastPromise.then(function () {
8820 if (iter[kEnded]) {
8821 resolve(createIterResult(undefined, true));
8822 return;
8823 }
8824
8825 iter[kHandlePromise](resolve, reject);
8826 }, reject);
8827 };
8828}
8829
8830var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
8831var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
8832 get stream() {
8833 return this[kStream];
8834 },
8835
8836 next: function next() {
8837 var _this = this;
8838
8839 // if we have detected an error in the meanwhile
8840 // reject straight away
8841 var error = this[kError];
8842
8843 if (error !== null) {
8844 return Promise.reject(error);
8845 }
8846
8847 if (this[kEnded]) {
8848 return Promise.resolve(createIterResult(undefined, true));
8849 }
8850
8851 if (this[kStream].destroyed) {
8852 // We need to defer via nextTick because if .destroy(err) is
8853 // called, the error will be emitted via nextTick, and
8854 // we cannot guarantee that there is no error lingering around
8855 // waiting to be emitted.
8856 return new Promise(function (resolve, reject) {
8857 process.nextTick(function () {
8858 if (_this[kError]) {
8859 reject(_this[kError]);
8860 } else {
8861 resolve(createIterResult(undefined, true));
8862 }
8863 });
8864 });
8865 } // if we have multiple next() calls
8866 // we will wait for the previous Promise to finish
8867 // this logic is optimized to support for await loops,
8868 // where next() is only called once at a time
8869
8870
8871 var lastPromise = this[kLastPromise];
8872 var promise;
8873
8874 if (lastPromise) {
8875 promise = new Promise(wrapForNext(lastPromise, this));
8876 } else {
8877 // fast path needed to support multiple this.push()
8878 // without triggering the next() queue
8879 var data = this[kStream].read();
8880
8881 if (data !== null) {
8882 return Promise.resolve(createIterResult(data, false));
8883 }
8884
8885 promise = new Promise(this[kHandlePromise]);
8886 }
8887
8888 this[kLastPromise] = promise;
8889 return promise;
8890 }
8891}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
8892 return this;
8893}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
8894 var _this2 = this;
8895
8896 // destroy(err, cb) is a private API
8897 // we can guarantee we have that here, because we control the
8898 // Readable class this is attached to
8899 return new Promise(function (resolve, reject) {
8900 _this2[kStream].destroy(null, function (err) {
8901 if (err) {
8902 reject(err);
8903 return;
8904 }
8905
8906 resolve(createIterResult(undefined, true));
8907 });
8908 });
8909}), _Object$setPrototypeO), AsyncIteratorPrototype);
8910
8911var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
8912 var _Object$create;
8913
8914 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
8915 value: stream,
8916 writable: true
8917 }), _defineProperty(_Object$create, kLastResolve, {
8918 value: null,
8919 writable: true
8920 }), _defineProperty(_Object$create, kLastReject, {
8921 value: null,
8922 writable: true
8923 }), _defineProperty(_Object$create, kError, {
8924 value: null,
8925 writable: true
8926 }), _defineProperty(_Object$create, kEnded, {
8927 value: stream._readableState.endEmitted,
8928 writable: true
8929 }), _defineProperty(_Object$create, kHandlePromise, {
8930 value: function value(resolve, reject) {
8931 var data = iterator[kStream].read();
8932
8933 if (data) {
8934 iterator[kLastPromise] = null;
8935 iterator[kLastResolve] = null;
8936 iterator[kLastReject] = null;
8937 resolve(createIterResult(data, false));
8938 } else {
8939 iterator[kLastResolve] = resolve;
8940 iterator[kLastReject] = reject;
8941 }
8942 },
8943 writable: true
8944 }), _Object$create));
8945 iterator[kLastPromise] = null;
8946 finished(stream, function (err) {
8947 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
8948 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
8949 // returned by next() and store the error
8950
8951 if (reject !== null) {
8952 iterator[kLastPromise] = null;
8953 iterator[kLastResolve] = null;
8954 iterator[kLastReject] = null;
8955 reject(err);
8956 }
8957
8958 iterator[kError] = err;
8959 return;
8960 }
8961
8962 var resolve = iterator[kLastResolve];
8963
8964 if (resolve !== null) {
8965 iterator[kLastPromise] = null;
8966 iterator[kLastResolve] = null;
8967 iterator[kLastReject] = null;
8968 resolve(createIterResult(undefined, true));
8969 }
8970
8971 iterator[kEnded] = true;
8972 });
8973 stream.on('readable', onReadable.bind(null, iterator));
8974 return iterator;
8975};
8976
8977module.exports = createReadableStreamAsyncIterator;
8978}).call(this,_dereq_(71))
8979},{"42":42,"71":71}],40:[function(_dereq_,module,exports){
8980'use strict';
8981
8982function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
8983
8984function _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; }
8985
8986var _require = _dereq_(9),
8987 Buffer = _require.Buffer;
8988
8989var _require2 = _dereq_(7),
8990 inspect = _require2.inspect;
8991
8992var custom = inspect && inspect.custom || 'inspect';
8993
8994function copyBuffer(src, target, offset) {
8995 Buffer.prototype.copy.call(src, target, offset);
8996}
8997
8998module.exports =
8999/*#__PURE__*/
9000function () {
9001 function BufferList() {
9002 this.head = null;
9003 this.tail = null;
9004 this.length = 0;
9005 }
9006
9007 var _proto = BufferList.prototype;
9008
9009 _proto.push = function push(v) {
9010 var entry = {
9011 data: v,
9012 next: null
9013 };
9014 if (this.length > 0) this.tail.next = entry;else this.head = entry;
9015 this.tail = entry;
9016 ++this.length;
9017 };
9018
9019 _proto.unshift = function unshift(v) {
9020 var entry = {
9021 data: v,
9022 next: this.head
9023 };
9024 if (this.length === 0) this.tail = entry;
9025 this.head = entry;
9026 ++this.length;
9027 };
9028
9029 _proto.shift = function shift() {
9030 if (this.length === 0) return;
9031 var ret = this.head.data;
9032 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
9033 --this.length;
9034 return ret;
9035 };
9036
9037 _proto.clear = function clear() {
9038 this.head = this.tail = null;
9039 this.length = 0;
9040 };
9041
9042 _proto.join = function join(s) {
9043 if (this.length === 0) return '';
9044 var p = this.head;
9045 var ret = '' + p.data;
9046
9047 while (p = p.next) {
9048 ret += s + p.data;
9049 }
9050
9051 return ret;
9052 };
9053
9054 _proto.concat = function concat(n) {
9055 if (this.length === 0) return Buffer.alloc(0);
9056 var ret = Buffer.allocUnsafe(n >>> 0);
9057 var p = this.head;
9058 var i = 0;
9059
9060 while (p) {
9061 copyBuffer(p.data, ret, i);
9062 i += p.data.length;
9063 p = p.next;
9064 }
9065
9066 return ret;
9067 } // Consumes a specified amount of bytes or characters from the buffered data.
9068 ;
9069
9070 _proto.consume = function consume(n, hasStrings) {
9071 var ret;
9072
9073 if (n < this.head.data.length) {
9074 // `slice` is the same for buffers and strings.
9075 ret = this.head.data.slice(0, n);
9076 this.head.data = this.head.data.slice(n);
9077 } else if (n === this.head.data.length) {
9078 // First chunk is a perfect match.
9079 ret = this.shift();
9080 } else {
9081 // Result spans more than one buffer.
9082 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
9083 }
9084
9085 return ret;
9086 };
9087
9088 _proto.first = function first() {
9089 return this.head.data;
9090 } // Consumes a specified amount of characters from the buffered data.
9091 ;
9092
9093 _proto._getString = function _getString(n) {
9094 var p = this.head;
9095 var c = 1;
9096 var ret = p.data;
9097 n -= ret.length;
9098
9099 while (p = p.next) {
9100 var str = p.data;
9101 var nb = n > str.length ? str.length : n;
9102 if (nb === str.length) ret += str;else ret += str.slice(0, n);
9103 n -= nb;
9104
9105 if (n === 0) {
9106 if (nb === str.length) {
9107 ++c;
9108 if (p.next) this.head = p.next;else this.head = this.tail = null;
9109 } else {
9110 this.head = p;
9111 p.data = str.slice(nb);
9112 }
9113
9114 break;
9115 }
9116
9117 ++c;
9118 }
9119
9120 this.length -= c;
9121 return ret;
9122 } // Consumes a specified amount of bytes from the buffered data.
9123 ;
9124
9125 _proto._getBuffer = function _getBuffer(n) {
9126 var ret = Buffer.allocUnsafe(n);
9127 var p = this.head;
9128 var c = 1;
9129 p.data.copy(ret);
9130 n -= p.data.length;
9131
9132 while (p = p.next) {
9133 var buf = p.data;
9134 var nb = n > buf.length ? buf.length : n;
9135 buf.copy(ret, ret.length - n, 0, nb);
9136 n -= nb;
9137
9138 if (n === 0) {
9139 if (nb === buf.length) {
9140 ++c;
9141 if (p.next) this.head = p.next;else this.head = this.tail = null;
9142 } else {
9143 this.head = p;
9144 p.data = buf.slice(nb);
9145 }
9146
9147 break;
9148 }
9149
9150 ++c;
9151 }
9152
9153 this.length -= c;
9154 return ret;
9155 } // Make sure the linked list only shows the minimal necessary information.
9156 ;
9157
9158 _proto[custom] = function (_, options) {
9159 return inspect(this, _objectSpread({}, options, {
9160 // Only inspect one level.
9161 depth: 0,
9162 // It should not recurse.
9163 customInspect: false
9164 }));
9165 };
9166
9167 return BufferList;
9168}();
9169},{"7":7,"9":9}],41:[function(_dereq_,module,exports){
9170(function (process){
9171'use strict'; // undocumented cb() API, needed for core, not for public API
9172
9173function destroy(err, cb) {
9174 var _this = this;
9175
9176 var readableDestroyed = this._readableState && this._readableState.destroyed;
9177 var writableDestroyed = this._writableState && this._writableState.destroyed;
9178
9179 if (readableDestroyed || writableDestroyed) {
9180 if (cb) {
9181 cb(err);
9182 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
9183 process.nextTick(emitErrorNT, this, err);
9184 }
9185
9186 return this;
9187 } // we set destroyed to true before firing error callbacks in order
9188 // to make it re-entrance safe in case destroy() is called within callbacks
9189
9190
9191 if (this._readableState) {
9192 this._readableState.destroyed = true;
9193 } // if this is a duplex stream mark the writable part as destroyed as well
9194
9195
9196 if (this._writableState) {
9197 this._writableState.destroyed = true;
9198 }
9199
9200 this._destroy(err || null, function (err) {
9201 if (!cb && err) {
9202 process.nextTick(emitErrorAndCloseNT, _this, err);
9203
9204 if (_this._writableState) {
9205 _this._writableState.errorEmitted = true;
9206 }
9207 } else if (cb) {
9208 process.nextTick(emitCloseNT, _this);
9209 cb(err);
9210 } else {
9211 process.nextTick(emitCloseNT, _this);
9212 }
9213 });
9214
9215 return this;
9216}
9217
9218function emitErrorAndCloseNT(self, err) {
9219 emitErrorNT(self, err);
9220 emitCloseNT(self);
9221}
9222
9223function emitCloseNT(self) {
9224 if (self._writableState && !self._writableState.emitClose) return;
9225 if (self._readableState && !self._readableState.emitClose) return;
9226 self.emit('close');
9227}
9228
9229function undestroy() {
9230 if (this._readableState) {
9231 this._readableState.destroyed = false;
9232 this._readableState.reading = false;
9233 this._readableState.ended = false;
9234 this._readableState.endEmitted = false;
9235 }
9236
9237 if (this._writableState) {
9238 this._writableState.destroyed = false;
9239 this._writableState.ended = false;
9240 this._writableState.ending = false;
9241 this._writableState.finalCalled = false;
9242 this._writableState.prefinished = false;
9243 this._writableState.finished = false;
9244 this._writableState.errorEmitted = false;
9245 }
9246}
9247
9248function emitErrorNT(self, err) {
9249 self.emit('error', err);
9250}
9251
9252module.exports = {
9253 destroy: destroy,
9254 undestroy: undestroy
9255};
9256}).call(this,_dereq_(71))
9257},{"71":71}],42:[function(_dereq_,module,exports){
9258// Ported from https://github.com/mafintosh/end-of-stream with
9259// permission from the author, Mathias Buus (@mafintosh).
9260'use strict';
9261
9262var ERR_STREAM_PREMATURE_CLOSE = _dereq_(32).codes.ERR_STREAM_PREMATURE_CLOSE;
9263
9264function once(callback) {
9265 var called = false;
9266 return function () {
9267 if (called) return;
9268 called = true;
9269
9270 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9271 args[_key] = arguments[_key];
9272 }
9273
9274 callback.apply(this, args);
9275 };
9276}
9277
9278function noop() {}
9279
9280function isRequest(stream) {
9281 return stream.setHeader && typeof stream.abort === 'function';
9282}
9283
9284function eos(stream, opts, callback) {
9285 if (typeof opts === 'function') return eos(stream, null, opts);
9286 if (!opts) opts = {};
9287 callback = once(callback || noop);
9288 var readable = opts.readable || opts.readable !== false && stream.readable;
9289 var writable = opts.writable || opts.writable !== false && stream.writable;
9290
9291 var onlegacyfinish = function onlegacyfinish() {
9292 if (!stream.writable) onfinish();
9293 };
9294
9295 var writableEnded = stream._writableState && stream._writableState.finished;
9296
9297 var onfinish = function onfinish() {
9298 writable = false;
9299 writableEnded = true;
9300 if (!readable) callback.call(stream);
9301 };
9302
9303 var readableEnded = stream._readableState && stream._readableState.endEmitted;
9304
9305 var onend = function onend() {
9306 readable = false;
9307 readableEnded = true;
9308 if (!writable) callback.call(stream);
9309 };
9310
9311 var onerror = function onerror(err) {
9312 callback.call(stream, err);
9313 };
9314
9315 var onclose = function onclose() {
9316 var err;
9317
9318 if (readable && !readableEnded) {
9319 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9320 return callback.call(stream, err);
9321 }
9322
9323 if (writable && !writableEnded) {
9324 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9325 return callback.call(stream, err);
9326 }
9327 };
9328
9329 var onrequest = function onrequest() {
9330 stream.req.on('finish', onfinish);
9331 };
9332
9333 if (isRequest(stream)) {
9334 stream.on('complete', onfinish);
9335 stream.on('abort', onclose);
9336 if (stream.req) onrequest();else stream.on('request', onrequest);
9337 } else if (writable && !stream._writableState) {
9338 // legacy streams
9339 stream.on('end', onlegacyfinish);
9340 stream.on('close', onlegacyfinish);
9341 }
9342
9343 stream.on('end', onend);
9344 stream.on('finish', onfinish);
9345 if (opts.error !== false) stream.on('error', onerror);
9346 stream.on('close', onclose);
9347 return function () {
9348 stream.removeListener('complete', onfinish);
9349 stream.removeListener('abort', onclose);
9350 stream.removeListener('request', onrequest);
9351 if (stream.req) stream.req.removeListener('finish', onfinish);
9352 stream.removeListener('end', onlegacyfinish);
9353 stream.removeListener('close', onlegacyfinish);
9354 stream.removeListener('finish', onfinish);
9355 stream.removeListener('end', onend);
9356 stream.removeListener('error', onerror);
9357 stream.removeListener('close', onclose);
9358 };
9359}
9360
9361module.exports = eos;
9362},{"32":32}],43:[function(_dereq_,module,exports){
9363// Ported from https://github.com/mafintosh/pump with
9364// permission from the author, Mathias Buus (@mafintosh).
9365'use strict';
9366
9367var eos;
9368
9369function once(callback) {
9370 var called = false;
9371 return function () {
9372 if (called) return;
9373 called = true;
9374 callback.apply(void 0, arguments);
9375 };
9376}
9377
9378var _require$codes = _dereq_(32).codes,
9379 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
9380 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
9381
9382function noop(err) {
9383 // Rethrow the error if it exists to avoid swallowing it
9384 if (err) throw err;
9385}
9386
9387function isRequest(stream) {
9388 return stream.setHeader && typeof stream.abort === 'function';
9389}
9390
9391function destroyer(stream, reading, writing, callback) {
9392 callback = once(callback);
9393 var closed = false;
9394 stream.on('close', function () {
9395 closed = true;
9396 });
9397 if (eos === undefined) eos = _dereq_(42);
9398 eos(stream, {
9399 readable: reading,
9400 writable: writing
9401 }, function (err) {
9402 if (err) return callback(err);
9403 closed = true;
9404 callback();
9405 });
9406 var destroyed = false;
9407 return function (err) {
9408 if (closed) return;
9409 if (destroyed) return;
9410 destroyed = true; // request.destroy just do .end - .abort is what we want
9411
9412 if (isRequest(stream)) return stream.abort();
9413 if (typeof stream.destroy === 'function') return stream.destroy();
9414 callback(err || new ERR_STREAM_DESTROYED('pipe'));
9415 };
9416}
9417
9418function call(fn) {
9419 fn();
9420}
9421
9422function pipe(from, to) {
9423 return from.pipe(to);
9424}
9425
9426function popCallback(streams) {
9427 if (!streams.length) return noop;
9428 if (typeof streams[streams.length - 1] !== 'function') return noop;
9429 return streams.pop();
9430}
9431
9432function pipeline() {
9433 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
9434 streams[_key] = arguments[_key];
9435 }
9436
9437 var callback = popCallback(streams);
9438 if (Array.isArray(streams[0])) streams = streams[0];
9439
9440 if (streams.length < 2) {
9441 throw new ERR_MISSING_ARGS('streams');
9442 }
9443
9444 var error;
9445 var destroys = streams.map(function (stream, i) {
9446 var reading = i < streams.length - 1;
9447 var writing = i > 0;
9448 return destroyer(stream, reading, writing, function (err) {
9449 if (!error) error = err;
9450 if (err) destroys.forEach(call);
9451 if (reading) return;
9452 destroys.forEach(call);
9453 callback(error);
9454 });
9455 });
9456 return streams.reduce(pipe);
9457}
9458
9459module.exports = pipeline;
9460},{"32":32,"42":42}],44:[function(_dereq_,module,exports){
9461'use strict';
9462
9463var ERR_INVALID_OPT_VALUE = _dereq_(32).codes.ERR_INVALID_OPT_VALUE;
9464
9465function highWaterMarkFrom(options, isDuplex, duplexKey) {
9466 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
9467}
9468
9469function getHighWaterMark(state, options, duplexKey, isDuplex) {
9470 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
9471
9472 if (hwm != null) {
9473 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
9474 var name = isDuplex ? duplexKey : 'highWaterMark';
9475 throw new ERR_INVALID_OPT_VALUE(name, hwm);
9476 }
9477
9478 return Math.floor(hwm);
9479 } // Default value
9480
9481
9482 return state.objectMode ? 16 : 16 * 1024;
9483}
9484
9485module.exports = {
9486 getHighWaterMark: getHighWaterMark
9487};
9488},{"32":32}],45:[function(_dereq_,module,exports){
9489module.exports = _dereq_(21).EventEmitter;
9490
9491},{"21":21}],46:[function(_dereq_,module,exports){
9492exports = module.exports = _dereq_(36);
9493exports.Stream = exports;
9494exports.Readable = exports;
9495exports.Writable = _dereq_(38);
9496exports.Duplex = _dereq_(34);
9497exports.Transform = _dereq_(37);
9498exports.PassThrough = _dereq_(35);
9499exports.finished = _dereq_(42);
9500exports.pipeline = _dereq_(43);
9501
9502},{"34":34,"35":35,"36":36,"37":37,"38":38,"42":42,"43":43}],47:[function(_dereq_,module,exports){
9503arguments[4][17][0].apply(exports,arguments)
9504},{"17":17}],48:[function(_dereq_,module,exports){
9505var WriteError = _dereq_(30).WriteError
9506var promisify = _dereq_(51)
9507var getCallback = _dereq_(49).getCallback
9508var getOptions = _dereq_(49).getOptions
9509
9510function Batch (levelup) {
9511 this._levelup = levelup
9512 this.batch = levelup.db.batch()
9513 this.ops = []
9514 this.length = 0
9515}
9516
9517Batch.prototype.put = function (key, value) {
9518 try {
9519 this.batch.put(key, value)
9520 } catch (e) {
9521 throw new WriteError(e)
9522 }
9523
9524 this.ops.push({ type: 'put', key: key, value: value })
9525 this.length++
9526
9527 return this
9528}
9529
9530Batch.prototype.del = function (key) {
9531 try {
9532 this.batch.del(key)
9533 } catch (err) {
9534 throw new WriteError(err)
9535 }
9536
9537 this.ops.push({ type: 'del', key: key })
9538 this.length++
9539
9540 return this
9541}
9542
9543Batch.prototype.clear = function () {
9544 try {
9545 this.batch.clear()
9546 } catch (err) {
9547 throw new WriteError(err)
9548 }
9549
9550 this.ops = []
9551 this.length = 0
9552
9553 return this
9554}
9555
9556Batch.prototype.write = function (options, callback) {
9557 var levelup = this._levelup
9558 var ops = this.ops
9559 var promise
9560
9561 callback = getCallback(options, callback)
9562
9563 if (!callback) {
9564 callback = promisify()
9565 promise = callback.promise
9566 }
9567
9568 options = getOptions(options)
9569
9570 try {
9571 this.batch.write(options, function (err) {
9572 if (err) { return callback(new WriteError(err)) }
9573 levelup.emit('batch', ops)
9574 callback()
9575 })
9576 } catch (err) {
9577 throw new WriteError(err)
9578 }
9579
9580 return promise
9581}
9582
9583module.exports = Batch
9584
9585},{"30":30,"49":49,"51":51}],49:[function(_dereq_,module,exports){
9586exports.getCallback = function (options, callback) {
9587 return typeof options === 'function' ? options : callback
9588}
9589
9590exports.getOptions = function (options) {
9591 return typeof options === 'object' && options !== null ? options : {}
9592}
9593
9594},{}],50:[function(_dereq_,module,exports){
9595(function (process){
9596var EventEmitter = _dereq_(21).EventEmitter
9597var inherits = _dereq_(118).inherits
9598var extend = _dereq_(52)
9599var DeferredLevelDOWN = _dereq_(12)
9600var IteratorStream = _dereq_(31)
9601var Batch = _dereq_(48)
9602var errors = _dereq_(30)
9603var assert = _dereq_(2)
9604var promisify = _dereq_(51)
9605var getCallback = _dereq_(49).getCallback
9606var getOptions = _dereq_(49).getOptions
9607
9608var WriteError = errors.WriteError
9609var ReadError = errors.ReadError
9610var NotFoundError = errors.NotFoundError
9611var OpenError = errors.OpenError
9612var InitializationError = errors.InitializationError
9613
9614// Possible AbstractLevelDOWN#status values:
9615// - 'new' - newly created, not opened or closed
9616// - 'opening' - waiting for the database to be opened, post open()
9617// - 'open' - successfully opened the database, available for use
9618// - 'closing' - waiting for the database to be closed, post close()
9619// - 'closed' - database has been successfully closed, should not be
9620// used except for another open() operation
9621
9622function LevelUP (db, options, callback) {
9623 if (!(this instanceof LevelUP)) {
9624 return new LevelUP(db, options, callback)
9625 }
9626
9627 var error
9628
9629 EventEmitter.call(this)
9630 this.setMaxListeners(Infinity)
9631
9632 if (typeof options === 'function') {
9633 callback = options
9634 options = {}
9635 }
9636
9637 options = options || {}
9638
9639 if (!db || typeof db !== 'object') {
9640 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
9641 if (typeof callback === 'function') {
9642 return process.nextTick(callback, error)
9643 }
9644 throw error
9645 }
9646
9647 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
9648
9649 this.options = getOptions(options)
9650 this._db = db
9651 this.db = new DeferredLevelDOWN(db)
9652 this.open(callback)
9653}
9654
9655LevelUP.prototype.emit = EventEmitter.prototype.emit
9656LevelUP.prototype.once = EventEmitter.prototype.once
9657inherits(LevelUP, EventEmitter)
9658
9659LevelUP.prototype.open = function (callback) {
9660 var self = this
9661 var promise
9662
9663 if (!callback) {
9664 callback = promisify()
9665 promise = callback.promise
9666 }
9667
9668 if (this.isOpen()) {
9669 process.nextTick(callback, null, self)
9670 return promise
9671 }
9672
9673 if (this._isOpening()) {
9674 this.once('open', function () { callback(null, self) })
9675 return promise
9676 }
9677
9678 this.emit('opening')
9679
9680 this.db.open(this.options, function (err) {
9681 if (err) {
9682 return callback(new OpenError(err))
9683 }
9684 self.db = self._db
9685 callback(null, self)
9686 self.emit('open')
9687 self.emit('ready')
9688 })
9689
9690 return promise
9691}
9692
9693LevelUP.prototype.close = function (callback) {
9694 var self = this
9695 var promise
9696
9697 if (!callback) {
9698 callback = promisify()
9699 promise = callback.promise
9700 }
9701
9702 if (this.isOpen()) {
9703 this.db.close(function () {
9704 self.emit('closed')
9705 callback.apply(null, arguments)
9706 })
9707 this.emit('closing')
9708 this.db = new DeferredLevelDOWN(this._db)
9709 } else if (this.isClosed()) {
9710 process.nextTick(callback)
9711 } else if (this.db.status === 'closing') {
9712 this.once('closed', callback)
9713 } else if (this._isOpening()) {
9714 this.once('open', function () {
9715 self.close(callback)
9716 })
9717 }
9718
9719 return promise
9720}
9721
9722LevelUP.prototype.isOpen = function () {
9723 return this.db.status === 'open'
9724}
9725
9726LevelUP.prototype._isOpening = function () {
9727 return this.db.status === 'opening'
9728}
9729
9730LevelUP.prototype.isClosed = function () {
9731 return (/^clos|new/).test(this.db.status)
9732}
9733
9734LevelUP.prototype.get = function (key, options, callback) {
9735 if (key === null || key === undefined) {
9736 throw new ReadError('get() requires a key argument')
9737 }
9738
9739 var promise
9740
9741 callback = getCallback(options, callback)
9742
9743 if (!callback) {
9744 callback = promisify()
9745 promise = callback.promise
9746 }
9747
9748 if (maybeError(this, callback)) { return promise }
9749
9750 options = getOptions(options)
9751
9752 this.db.get(key, options, function (err, value) {
9753 if (err) {
9754 if ((/notfound/i).test(err) || err.notFound) {
9755 err = new NotFoundError('Key not found in database [' + key + ']', err)
9756 } else {
9757 err = new ReadError(err)
9758 }
9759 return callback(err)
9760 }
9761 callback(null, value)
9762 })
9763
9764 return promise
9765}
9766
9767LevelUP.prototype.put = function (key, value, options, callback) {
9768 if (key === null || key === undefined) {
9769 throw new WriteError('put() requires a key argument')
9770 }
9771
9772 var self = this
9773 var promise
9774
9775 callback = getCallback(options, callback)
9776
9777 if (!callback) {
9778 callback = promisify()
9779 promise = callback.promise
9780 }
9781
9782 if (maybeError(this, callback)) { return promise }
9783
9784 options = getOptions(options)
9785
9786 this.db.put(key, value, options, function (err) {
9787 if (err) {
9788 return callback(new WriteError(err))
9789 }
9790 self.emit('put', key, value)
9791 callback()
9792 })
9793
9794 return promise
9795}
9796
9797LevelUP.prototype.del = function (key, options, callback) {
9798 if (key === null || key === undefined) {
9799 throw new WriteError('del() requires a key argument')
9800 }
9801
9802 var self = this
9803 var promise
9804
9805 callback = getCallback(options, callback)
9806
9807 if (!callback) {
9808 callback = promisify()
9809 promise = callback.promise
9810 }
9811
9812 if (maybeError(this, callback)) { return promise }
9813
9814 options = getOptions(options)
9815
9816 this.db.del(key, options, function (err) {
9817 if (err) {
9818 return callback(new WriteError(err))
9819 }
9820 self.emit('del', key)
9821 callback()
9822 })
9823
9824 return promise
9825}
9826
9827LevelUP.prototype.batch = function (arr, options, callback) {
9828 if (!arguments.length) {
9829 return new Batch(this)
9830 }
9831
9832 if (!Array.isArray(arr)) {
9833 throw new WriteError('batch() requires an array argument')
9834 }
9835
9836 var self = this
9837 var promise
9838
9839 callback = getCallback(options, callback)
9840
9841 if (!callback) {
9842 callback = promisify()
9843 promise = callback.promise
9844 }
9845
9846 if (maybeError(this, callback)) { return promise }
9847
9848 options = getOptions(options)
9849
9850 this.db.batch(arr, options, function (err) {
9851 if (err) {
9852 return callback(new WriteError(err))
9853 }
9854 self.emit('batch', arr)
9855 callback()
9856 })
9857
9858 return promise
9859}
9860
9861LevelUP.prototype.iterator = function (options) {
9862 return this.db.iterator(options)
9863}
9864
9865LevelUP.prototype.readStream =
9866LevelUP.prototype.createReadStream = function (options) {
9867 options = extend({ keys: true, values: true }, options)
9868 if (typeof options.limit !== 'number') { options.limit = -1 }
9869 return new IteratorStream(this.db.iterator(options), options)
9870}
9871
9872LevelUP.prototype.keyStream =
9873LevelUP.prototype.createKeyStream = function (options) {
9874 return this.createReadStream(extend(options, { keys: true, values: false }))
9875}
9876
9877LevelUP.prototype.valueStream =
9878LevelUP.prototype.createValueStream = function (options) {
9879 return this.createReadStream(extend(options, { keys: false, values: true }))
9880}
9881
9882LevelUP.prototype.toString = function () {
9883 return 'LevelUP'
9884}
9885
9886function maybeError (db, callback) {
9887 if (!db._isOpening() && !db.isOpen()) {
9888 process.nextTick(callback, new ReadError('Database is not open'))
9889 return true
9890 }
9891}
9892
9893LevelUP.errors = errors
9894module.exports = LevelUP.default = LevelUP
9895
9896}).call(this,_dereq_(71))
9897},{"118":118,"12":12,"2":2,"21":21,"30":30,"31":31,"48":48,"49":49,"51":51,"52":52,"71":71}],51:[function(_dereq_,module,exports){
9898function promisify () {
9899 var callback
9900 var promise = new Promise(function (resolve, reject) {
9901 callback = function callback (err, value) {
9902 if (err) reject(err)
9903 else resolve(value)
9904 }
9905 })
9906 callback.promise = promise
9907 return callback
9908}
9909
9910module.exports = promisify
9911
9912},{}],52:[function(_dereq_,module,exports){
9913arguments[4][17][0].apply(exports,arguments)
9914},{"17":17}],53:[function(_dereq_,module,exports){
9915(function (Buffer){
9916
9917exports.compare = function (a, b) {
9918
9919 if(Buffer.isBuffer(a)) {
9920 var l = Math.min(a.length, b.length)
9921 for(var i = 0; i < l; i++) {
9922 var cmp = a[i] - b[i]
9923 if(cmp) return cmp
9924 }
9925 return a.length - b.length
9926 }
9927
9928 return a < b ? -1 : a > b ? 1 : 0
9929}
9930
9931// to be compatible with the current abstract-leveldown tests
9932// nullish or empty strings.
9933// I could use !!val but I want to permit numbers and booleans,
9934// if possible.
9935
9936function isDef (val) {
9937 return val !== undefined && val !== ''
9938}
9939
9940function has (range, name) {
9941 return Object.hasOwnProperty.call(range, name)
9942}
9943
9944function hasKey(range, name) {
9945 return Object.hasOwnProperty.call(range, name) && name
9946}
9947
9948var lowerBoundKey = exports.lowerBoundKey = function (range) {
9949 return (
9950 hasKey(range, 'gt')
9951 || hasKey(range, 'gte')
9952 || hasKey(range, 'min')
9953 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
9954 || undefined
9955 )
9956}
9957
9958var lowerBound = exports.lowerBound = function (range, def) {
9959 var k = lowerBoundKey(range)
9960 return k ? range[k] : def
9961}
9962
9963var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
9964 return has(range, 'gt') ? false : true
9965}
9966
9967var upperBoundInclusive = exports.upperBoundInclusive =
9968 function (range) {
9969 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
9970 }
9971
9972var lowerBoundExclusive = exports.lowerBoundExclusive =
9973 function (range) {
9974 return !lowerBoundInclusive(range)
9975 }
9976
9977var upperBoundExclusive = exports.upperBoundExclusive =
9978 function (range) {
9979 return !upperBoundInclusive(range)
9980 }
9981
9982var upperBoundKey = exports.upperBoundKey = function (range) {
9983 return (
9984 hasKey(range, 'lt')
9985 || hasKey(range, 'lte')
9986 || hasKey(range, 'max')
9987 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
9988 || undefined
9989 )
9990}
9991
9992var upperBound = exports.upperBound = function (range, def) {
9993 var k = upperBoundKey(range)
9994 return k ? range[k] : def
9995}
9996
9997exports.start = function (range, def) {
9998 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
9999}
10000exports.end = function (range, def) {
10001 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10002}
10003exports.startInclusive = function (range) {
10004 return (
10005 range.reverse
10006 ? upperBoundInclusive(range)
10007 : lowerBoundInclusive(range)
10008 )
10009}
10010exports.endInclusive = function (range) {
10011 return (
10012 range.reverse
10013 ? lowerBoundInclusive(range)
10014 : upperBoundInclusive(range)
10015 )
10016}
10017
10018function id (e) { return e }
10019
10020exports.toLtgt = function (range, _range, map, lower, upper) {
10021 _range = _range || {}
10022 map = map || id
10023 var defaults = arguments.length > 3
10024 var lb = exports.lowerBoundKey(range)
10025 var ub = exports.upperBoundKey(range)
10026 if(lb) {
10027 if(lb === 'gt') _range.gt = map(range.gt, false)
10028 else _range.gte = map(range[lb], false)
10029 }
10030 else if(defaults)
10031 _range.gte = map(lower, false)
10032
10033 if(ub) {
10034 if(ub === 'lt') _range.lt = map(range.lt, true)
10035 else _range.lte = map(range[ub], true)
10036 }
10037 else if(defaults)
10038 _range.lte = map(upper, true)
10039
10040 if(range.reverse != null)
10041 _range.reverse = !!range.reverse
10042
10043 //if range was used mutably
10044 //(in level-sublevel it's part of an options object
10045 //that has more properties on it.)
10046 if(has(_range, 'max')) delete _range.max
10047 if(has(_range, 'min')) delete _range.min
10048 if(has(_range, 'start')) delete _range.start
10049 if(has(_range, 'end')) delete _range.end
10050
10051 return _range
10052}
10053
10054exports.contains = function (range, key, compare) {
10055 compare = compare || exports.compare
10056
10057 var lb = lowerBound(range)
10058 if(isDef(lb)) {
10059 var cmp = compare(key, lb)
10060 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10061 return false
10062 }
10063
10064 var ub = upperBound(range)
10065 if(isDef(ub)) {
10066 var cmp = compare(key, ub)
10067 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10068 return false
10069 }
10070
10071 return true
10072}
10073
10074exports.filter = function (range, compare) {
10075 return function (key) {
10076 return exports.contains(range, key, compare)
10077 }
10078}
10079
10080
10081
10082}).call(this,{"isBuffer":_dereq_(26)})
10083},{"26":26}],54:[function(_dereq_,module,exports){
10084module.exports = _dereq_(61)
10085
10086},{"61":61}],55:[function(_dereq_,module,exports){
10087(function (Buffer){
10088var inherits = _dereq_(25)
10089 , AbstractLevelDOWN = _dereq_(59).AbstractLevelDOWN
10090 , AbstractIterator = _dereq_(59).AbstractIterator
10091 , ltgt = _dereq_(67)
10092 , createRBT = _dereq_(22)
10093 , globalStore = {}
10094
10095// In Node, use global.setImmediate. In the browser, use a consistent
10096// microtask library to give consistent microtask experience to all browsers
10097var setImmediate = _dereq_(54)
10098
10099function gt(value) {
10100 return ltgt.compare(value, this._end) > 0
10101}
10102
10103function gte(value) {
10104 return ltgt.compare(value, this._end) >= 0
10105}
10106
10107function lt(value) {
10108 return ltgt.compare(value, this._end) < 0
10109}
10110
10111function lte(value) {
10112 return ltgt.compare(value, this._end) <= 0
10113}
10114
10115
10116function MemIterator (db, options) {
10117 AbstractIterator.call(this, db)
10118 this._limit = options.limit
10119
10120 if (this._limit === -1)
10121 this._limit = Infinity
10122
10123 var tree = db._store[db._location]
10124
10125 this.keyAsBuffer = options.keyAsBuffer !== false
10126 this.valueAsBuffer = options.valueAsBuffer !== false
10127 this._reverse = options.reverse
10128 this._options = options
10129 this._done = 0
10130
10131 if (!this._reverse) {
10132 this._incr = 'next'
10133 this._start = ltgt.lowerBound(options)
10134 this._end = ltgt.upperBound(options)
10135
10136 if (typeof this._start === 'undefined')
10137 this._tree = tree.begin
10138 else if (ltgt.lowerBoundInclusive(options))
10139 this._tree = tree.ge(this._start)
10140 else
10141 this._tree = tree.gt(this._start)
10142
10143 if (this._end) {
10144 if (ltgt.upperBoundInclusive(options))
10145 this._test = lte
10146 else
10147 this._test = lt
10148 }
10149
10150 } else {
10151 this._incr = 'prev'
10152 this._start = ltgt.upperBound(options)
10153 this._end = ltgt.lowerBound(options)
10154
10155 if (typeof this._start === 'undefined')
10156 this._tree = tree.end
10157 else if (ltgt.upperBoundInclusive(options))
10158 this._tree = tree.le(this._start)
10159 else
10160 this._tree = tree.lt(this._start)
10161
10162 if (this._end) {
10163 if (ltgt.lowerBoundInclusive(options))
10164 this._test = gte
10165 else
10166 this._test = gt
10167 }
10168
10169 }
10170
10171}
10172
10173inherits(MemIterator, AbstractIterator)
10174
10175MemIterator.prototype._next = function (callback) {
10176 var key
10177 , value
10178
10179 if (this._done++ >= this._limit)
10180 return setImmediate(callback)
10181
10182 if (!this._tree.valid)
10183 return setImmediate(callback)
10184
10185 key = this._tree.key
10186 value = this._tree.value
10187
10188 if (!this._test(key))
10189 return setImmediate(callback)
10190
10191 if (this.keyAsBuffer)
10192 key = new Buffer(key)
10193
10194 if (this.valueAsBuffer)
10195 value = new Buffer(value)
10196
10197 this._tree[this._incr]()
10198
10199 setImmediate(function callNext() {
10200 callback(null, key, value)
10201 })
10202}
10203
10204MemIterator.prototype._test = function () {return true}
10205
10206function MemDOWN (location) {
10207 if (!(this instanceof MemDOWN))
10208 return new MemDOWN(location)
10209
10210 AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '')
10211
10212 this._location = this.location ? ('$' + this.location) : '_tree'
10213 this._store = this.location ? globalStore: this
10214 this._store[this._location] = this._store[this._location] || createRBT(ltgt.compare)
10215}
10216
10217MemDOWN.clearGlobalStore = function (strict) {
10218 if (strict) {
10219 Object.keys(globalStore).forEach(function (key) {
10220 delete globalStore[key]
10221 })
10222 } else {
10223 globalStore = {}
10224 }
10225}
10226
10227inherits(MemDOWN, AbstractLevelDOWN)
10228
10229MemDOWN.prototype._open = function (options, callback) {
10230 var self = this
10231 setImmediate(function callNext() { callback(null, self) })
10232}
10233
10234MemDOWN.prototype._put = function (key, value, options, callback) {
10235 if (typeof value === 'undefined' || value === null) value = ''
10236
10237 var iter = this._store[this._location].find(key)
10238
10239 if (iter.valid) {
10240 this._store[this._location] = iter.update(value)
10241 } else {
10242 this._store[this._location] = this._store[this._location].insert(key, value)
10243 }
10244
10245 setImmediate(callback)
10246}
10247
10248MemDOWN.prototype._get = function (key, options, callback) {
10249 var value = this._store[this._location].get(key)
10250
10251 if (typeof value === 'undefined') {
10252 // 'NotFound' error, consistent with LevelDOWN API
10253 return setImmediate(function callNext() { callback(new Error('NotFound')) })
10254 }
10255
10256 if (options.asBuffer !== false && !this._isBuffer(value))
10257 value = new Buffer(String(value))
10258
10259 setImmediate(function callNext () {
10260 callback(null, value)
10261 })
10262
10263}
10264
10265MemDOWN.prototype._del = function (key, options, callback) {
10266 this._store[this._location] = this._store[this._location].remove(key)
10267 setImmediate(callback)
10268}
10269
10270MemDOWN.prototype._batch = function (array, options, callback) {
10271 var i = -1
10272 , key
10273 , value
10274 , iter
10275 , len = array.length
10276 , tree = this._store[this._location]
10277
10278 while (++i < len) {
10279 if (!array[i])
10280 continue
10281
10282 key = this._isBuffer(array[i].key) ? array[i].key : String(array[i].key)
10283 iter = tree.find(key)
10284
10285 if (array[i].type === 'put') {
10286 value = this._isBuffer(array[i].value) ? array[i].value : String(array[i].value)
10287 tree = iter.valid ? iter.update(value) : tree.insert(key, value)
10288 } else {
10289 tree = iter.remove()
10290 }
10291 }
10292
10293 this._store[this._location] = tree
10294
10295 setImmediate(callback)
10296}
10297
10298MemDOWN.prototype._iterator = function (options) {
10299 return new MemIterator(this, options)
10300}
10301
10302MemDOWN.prototype._isBuffer = function (obj) {
10303 return Buffer.isBuffer(obj)
10304}
10305
10306MemDOWN.destroy = function (name, callback) {
10307 var key = '$' + name
10308
10309 if (key in globalStore)
10310 delete globalStore[key]
10311
10312 setImmediate(callback)
10313}
10314
10315module.exports = MemDOWN
10316
10317}).call(this,_dereq_(9).Buffer)
10318},{"22":22,"25":25,"54":54,"59":59,"67":67,"9":9}],56:[function(_dereq_,module,exports){
10319(function (process){
10320/* Copyright (c) 2013 Rod Vagg, MIT License */
10321
10322function AbstractChainedBatch (db) {
10323 this._db = db
10324 this._operations = []
10325 this._written = false
10326}
10327
10328AbstractChainedBatch.prototype._checkWritten = function () {
10329 if (this._written)
10330 throw new Error('write() already called on this batch')
10331}
10332
10333AbstractChainedBatch.prototype.put = function (key, value) {
10334 this._checkWritten()
10335
10336 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10337 if (err)
10338 throw err
10339
10340 if (!this._db._isBuffer(key)) key = String(key)
10341 if (!this._db._isBuffer(value)) value = String(value)
10342
10343 if (typeof this._put == 'function' )
10344 this._put(key, value)
10345 else
10346 this._operations.push({ type: 'put', key: key, value: value })
10347
10348 return this
10349}
10350
10351AbstractChainedBatch.prototype.del = function (key) {
10352 this._checkWritten()
10353
10354 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10355 if (err) throw err
10356
10357 if (!this._db._isBuffer(key)) key = String(key)
10358
10359 if (typeof this._del == 'function' )
10360 this._del(key)
10361 else
10362 this._operations.push({ type: 'del', key: key })
10363
10364 return this
10365}
10366
10367AbstractChainedBatch.prototype.clear = function () {
10368 this._checkWritten()
10369
10370 this._operations = []
10371
10372 if (typeof this._clear == 'function' )
10373 this._clear()
10374
10375 return this
10376}
10377
10378AbstractChainedBatch.prototype.write = function (options, callback) {
10379 this._checkWritten()
10380
10381 if (typeof options == 'function')
10382 callback = options
10383 if (typeof callback != 'function')
10384 throw new Error('write() requires a callback argument')
10385 if (typeof options != 'object')
10386 options = {}
10387
10388 this._written = true
10389
10390 if (typeof this._write == 'function' )
10391 return this._write(callback)
10392
10393 if (typeof this._db._batch == 'function')
10394 return this._db._batch(this._operations, options, callback)
10395
10396 process.nextTick(callback)
10397}
10398
10399module.exports = AbstractChainedBatch
10400}).call(this,_dereq_(71))
10401},{"71":71}],57:[function(_dereq_,module,exports){
10402(function (process){
10403/* Copyright (c) 2013 Rod Vagg, MIT License */
10404
10405function AbstractIterator (db) {
10406 this.db = db
10407 this._ended = false
10408 this._nexting = false
10409}
10410
10411AbstractIterator.prototype.next = function (callback) {
10412 var self = this
10413
10414 if (typeof callback != 'function')
10415 throw new Error('next() requires a callback argument')
10416
10417 if (self._ended)
10418 return callback(new Error('cannot call next() after end()'))
10419 if (self._nexting)
10420 return callback(new Error('cannot call next() before previous next() has completed'))
10421
10422 self._nexting = true
10423 if (typeof self._next == 'function') {
10424 return self._next(function () {
10425 self._nexting = false
10426 callback.apply(null, arguments)
10427 })
10428 }
10429
10430 process.nextTick(function () {
10431 self._nexting = false
10432 callback()
10433 })
10434}
10435
10436AbstractIterator.prototype.end = function (callback) {
10437 if (typeof callback != 'function')
10438 throw new Error('end() requires a callback argument')
10439
10440 if (this._ended)
10441 return callback(new Error('end() already called on iterator'))
10442
10443 this._ended = true
10444
10445 if (typeof this._end == 'function')
10446 return this._end(callback)
10447
10448 process.nextTick(callback)
10449}
10450
10451module.exports = AbstractIterator
10452
10453}).call(this,_dereq_(71))
10454},{"71":71}],58:[function(_dereq_,module,exports){
10455(function (Buffer,process){
10456/* Copyright (c) 2013 Rod Vagg, MIT License */
10457
10458var xtend = _dereq_(68)
10459 , AbstractIterator = _dereq_(57)
10460 , AbstractChainedBatch = _dereq_(56)
10461
10462function AbstractLevelDOWN (location) {
10463 if (!arguments.length || location === undefined)
10464 throw new Error('constructor requires at least a location argument')
10465
10466 if (typeof location != 'string')
10467 throw new Error('constructor requires a location string argument')
10468
10469 this.location = location
10470 this.status = 'new'
10471}
10472
10473AbstractLevelDOWN.prototype.open = function (options, callback) {
10474 var self = this
10475 , oldStatus = this.status
10476
10477 if (typeof options == 'function')
10478 callback = options
10479
10480 if (typeof callback != 'function')
10481 throw new Error('open() requires a callback argument')
10482
10483 if (typeof options != 'object')
10484 options = {}
10485
10486 options.createIfMissing = options.createIfMissing != false
10487 options.errorIfExists = !!options.errorIfExists
10488
10489 if (typeof this._open == 'function') {
10490 this.status = 'opening'
10491 this._open(options, function (err) {
10492 if (err) {
10493 self.status = oldStatus
10494 return callback(err)
10495 }
10496 self.status = 'open'
10497 callback()
10498 })
10499 } else {
10500 this.status = 'open'
10501 process.nextTick(callback)
10502 }
10503}
10504
10505AbstractLevelDOWN.prototype.close = function (callback) {
10506 var self = this
10507 , oldStatus = this.status
10508
10509 if (typeof callback != 'function')
10510 throw new Error('close() requires a callback argument')
10511
10512 if (typeof this._close == 'function') {
10513 this.status = 'closing'
10514 this._close(function (err) {
10515 if (err) {
10516 self.status = oldStatus
10517 return callback(err)
10518 }
10519 self.status = 'closed'
10520 callback()
10521 })
10522 } else {
10523 this.status = 'closed'
10524 process.nextTick(callback)
10525 }
10526}
10527
10528AbstractLevelDOWN.prototype.get = function (key, options, callback) {
10529 var err
10530
10531 if (typeof options == 'function')
10532 callback = options
10533
10534 if (typeof callback != 'function')
10535 throw new Error('get() requires a callback argument')
10536
10537 if (err = this._checkKey(key, 'key', this._isBuffer))
10538 return callback(err)
10539
10540 if (!this._isBuffer(key))
10541 key = String(key)
10542
10543 if (typeof options != 'object')
10544 options = {}
10545
10546 options.asBuffer = options.asBuffer != false
10547
10548 if (typeof this._get == 'function')
10549 return this._get(key, options, callback)
10550
10551 process.nextTick(function () { callback(new Error('NotFound')) })
10552}
10553
10554AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
10555 var err
10556
10557 if (typeof options == 'function')
10558 callback = options
10559
10560 if (typeof callback != 'function')
10561 throw new Error('put() requires a callback argument')
10562
10563 if (err = this._checkKey(key, 'key', this._isBuffer))
10564 return callback(err)
10565
10566 if (!this._isBuffer(key))
10567 key = String(key)
10568
10569 // coerce value to string in node, don't touch it in browser
10570 // (indexeddb can store any JS type)
10571 if (value != null && !this._isBuffer(value) && !process.browser)
10572 value = String(value)
10573
10574 if (typeof options != 'object')
10575 options = {}
10576
10577 if (typeof this._put == 'function')
10578 return this._put(key, value, options, callback)
10579
10580 process.nextTick(callback)
10581}
10582
10583AbstractLevelDOWN.prototype.del = function (key, options, callback) {
10584 var err
10585
10586 if (typeof options == 'function')
10587 callback = options
10588
10589 if (typeof callback != 'function')
10590 throw new Error('del() requires a callback argument')
10591
10592 if (err = this._checkKey(key, 'key', this._isBuffer))
10593 return callback(err)
10594
10595 if (!this._isBuffer(key))
10596 key = String(key)
10597
10598 if (typeof options != 'object')
10599 options = {}
10600
10601 if (typeof this._del == 'function')
10602 return this._del(key, options, callback)
10603
10604 process.nextTick(callback)
10605}
10606
10607AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
10608 if (!arguments.length)
10609 return this._chainedBatch()
10610
10611 if (typeof options == 'function')
10612 callback = options
10613
10614 if (typeof array == 'function')
10615 callback = array
10616
10617 if (typeof callback != 'function')
10618 throw new Error('batch(array) requires a callback argument')
10619
10620 if (!Array.isArray(array))
10621 return callback(new Error('batch(array) requires an array argument'))
10622
10623 if (!options || typeof options != 'object')
10624 options = {}
10625
10626 var i = 0
10627 , l = array.length
10628 , e
10629 , err
10630
10631 for (; i < l; i++) {
10632 e = array[i]
10633 if (typeof e != 'object')
10634 continue
10635
10636 if (err = this._checkKey(e.type, 'type', this._isBuffer))
10637 return callback(err)
10638
10639 if (err = this._checkKey(e.key, 'key', this._isBuffer))
10640 return callback(err)
10641 }
10642
10643 if (typeof this._batch == 'function')
10644 return this._batch(array, options, callback)
10645
10646 process.nextTick(callback)
10647}
10648
10649//TODO: remove from here, not a necessary primitive
10650AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
10651 if ( start == null
10652 || end == null
10653 || typeof start == 'function'
10654 || typeof end == 'function') {
10655 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
10656 }
10657
10658 if (typeof callback != 'function')
10659 throw new Error('approximateSize() requires a callback argument')
10660
10661 if (!this._isBuffer(start))
10662 start = String(start)
10663
10664 if (!this._isBuffer(end))
10665 end = String(end)
10666
10667 if (typeof this._approximateSize == 'function')
10668 return this._approximateSize(start, end, callback)
10669
10670 process.nextTick(function () {
10671 callback(null, 0)
10672 })
10673}
10674
10675AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
10676 var self = this
10677
10678 options = xtend(options)
10679
10680 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
10681 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
10682 delete options[o]
10683 })
10684
10685 options.reverse = !!options.reverse
10686 options.keys = options.keys != false
10687 options.values = options.values != false
10688 options.limit = 'limit' in options ? options.limit : -1
10689 options.keyAsBuffer = options.keyAsBuffer != false
10690 options.valueAsBuffer = options.valueAsBuffer != false
10691
10692 return options
10693}
10694
10695AbstractLevelDOWN.prototype.iterator = function (options) {
10696 if (typeof options != 'object')
10697 options = {}
10698
10699 options = this._setupIteratorOptions(options)
10700
10701 if (typeof this._iterator == 'function')
10702 return this._iterator(options)
10703
10704 return new AbstractIterator(this)
10705}
10706
10707AbstractLevelDOWN.prototype._chainedBatch = function () {
10708 return new AbstractChainedBatch(this)
10709}
10710
10711AbstractLevelDOWN.prototype._isBuffer = function (obj) {
10712 return Buffer.isBuffer(obj)
10713}
10714
10715AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
10716
10717 if (obj === null || obj === undefined)
10718 return new Error(type + ' cannot be `null` or `undefined`')
10719
10720 if (this._isBuffer(obj)) {
10721 if (obj.length === 0)
10722 return new Error(type + ' cannot be an empty Buffer')
10723 } else if (String(obj) === '')
10724 return new Error(type + ' cannot be an empty String')
10725}
10726
10727module.exports = AbstractLevelDOWN
10728
10729}).call(this,{"isBuffer":_dereq_(26)},_dereq_(71))
10730},{"26":26,"56":56,"57":57,"68":68,"71":71}],59:[function(_dereq_,module,exports){
10731exports.AbstractLevelDOWN = _dereq_(58)
10732exports.AbstractIterator = _dereq_(57)
10733exports.AbstractChainedBatch = _dereq_(56)
10734exports.isLevelDOWN = _dereq_(60)
10735
10736},{"56":56,"57":57,"58":58,"60":60}],60:[function(_dereq_,module,exports){
10737var AbstractLevelDOWN = _dereq_(58)
10738
10739function isLevelDOWN (db) {
10740 if (!db || typeof db !== 'object')
10741 return false
10742 return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) {
10743 // TODO remove approximateSize check when method is gone
10744 return name[0] != '_' && name != 'approximateSize'
10745 }).every(function (name) {
10746 return typeof db[name] == 'function'
10747 })
10748}
10749
10750module.exports = isLevelDOWN
10751
10752},{"58":58}],61:[function(_dereq_,module,exports){
10753'use strict';
10754var types = [
10755 _dereq_(64),
10756 _dereq_(63),
10757 _dereq_(62),
10758 _dereq_(65),
10759 _dereq_(66)
10760];
10761var draining;
10762var currentQueue;
10763var queueIndex = -1;
10764var queue = [];
10765var scheduled = false;
10766function cleanUpNextTick() {
10767 if (!draining || !currentQueue) {
10768 return;
10769 }
10770 draining = false;
10771 if (currentQueue.length) {
10772 queue = currentQueue.concat(queue);
10773 } else {
10774 queueIndex = -1;
10775 }
10776 if (queue.length) {
10777 nextTick();
10778 }
10779}
10780
10781//named nextTick for less confusing stack traces
10782function nextTick() {
10783 if (draining) {
10784 return;
10785 }
10786 scheduled = false;
10787 draining = true;
10788 var len = queue.length;
10789 var timeout = setTimeout(cleanUpNextTick);
10790 while (len) {
10791 currentQueue = queue;
10792 queue = [];
10793 while (currentQueue && ++queueIndex < len) {
10794 currentQueue[queueIndex].run();
10795 }
10796 queueIndex = -1;
10797 len = queue.length;
10798 }
10799 currentQueue = null;
10800 queueIndex = -1;
10801 draining = false;
10802 clearTimeout(timeout);
10803}
10804var scheduleDrain;
10805var i = -1;
10806var len = types.length;
10807while (++i < len) {
10808 if (types[i] && types[i].test && types[i].test()) {
10809 scheduleDrain = types[i].install(nextTick);
10810 break;
10811 }
10812}
10813// v8 likes predictible objects
10814function Item(fun, array) {
10815 this.fun = fun;
10816 this.array = array;
10817}
10818Item.prototype.run = function () {
10819 var fun = this.fun;
10820 var array = this.array;
10821 switch (array.length) {
10822 case 0:
10823 return fun();
10824 case 1:
10825 return fun(array[0]);
10826 case 2:
10827 return fun(array[0], array[1]);
10828 case 3:
10829 return fun(array[0], array[1], array[2]);
10830 default:
10831 return fun.apply(null, array);
10832 }
10833
10834};
10835module.exports = immediate;
10836function immediate(task) {
10837 var args = new Array(arguments.length - 1);
10838 if (arguments.length > 1) {
10839 for (var i = 1; i < arguments.length; i++) {
10840 args[i - 1] = arguments[i];
10841 }
10842 }
10843 queue.push(new Item(task, args));
10844 if (!scheduled && !draining) {
10845 scheduled = true;
10846 scheduleDrain();
10847 }
10848}
10849
10850},{"62":62,"63":63,"64":64,"65":65,"66":66}],62:[function(_dereq_,module,exports){
10851(function (global){
10852'use strict';
10853
10854exports.test = function () {
10855 if (global.setImmediate) {
10856 // we can only get here in IE10
10857 // which doesn't handel postMessage well
10858 return false;
10859 }
10860 return typeof global.MessageChannel !== 'undefined';
10861};
10862
10863exports.install = function (func) {
10864 var channel = new global.MessageChannel();
10865 channel.port1.onmessage = func;
10866 return function () {
10867 channel.port2.postMessage(0);
10868 };
10869};
10870}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10871},{}],63:[function(_dereq_,module,exports){
10872(function (global){
10873'use strict';
10874//based off rsvp https://github.com/tildeio/rsvp.js
10875//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
10876//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
10877
10878var Mutation = global.MutationObserver || global.WebKitMutationObserver;
10879
10880exports.test = function () {
10881 return Mutation;
10882};
10883
10884exports.install = function (handle) {
10885 var called = 0;
10886 var observer = new Mutation(handle);
10887 var element = global.document.createTextNode('');
10888 observer.observe(element, {
10889 characterData: true
10890 });
10891 return function () {
10892 element.data = (called = ++called % 2);
10893 };
10894};
10895}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10896},{}],64:[function(_dereq_,module,exports){
10897(function (process){
10898'use strict';
10899exports.test = function () {
10900 // Don't get fooled by e.g. browserify environments.
10901 return (typeof process !== 'undefined') && !process.browser;
10902};
10903
10904exports.install = function (func) {
10905 return function () {
10906 process.nextTick(func);
10907 };
10908};
10909
10910}).call(this,_dereq_(71))
10911},{"71":71}],65:[function(_dereq_,module,exports){
10912(function (global){
10913'use strict';
10914
10915exports.test = function () {
10916 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
10917};
10918
10919exports.install = function (handle) {
10920 return function () {
10921
10922 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
10923 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
10924 var scriptEl = global.document.createElement('script');
10925 scriptEl.onreadystatechange = function () {
10926 handle();
10927
10928 scriptEl.onreadystatechange = null;
10929 scriptEl.parentNode.removeChild(scriptEl);
10930 scriptEl = null;
10931 };
10932 global.document.documentElement.appendChild(scriptEl);
10933
10934 return handle;
10935 };
10936};
10937}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10938},{}],66:[function(_dereq_,module,exports){
10939'use strict';
10940exports.test = function () {
10941 return true;
10942};
10943
10944exports.install = function (t) {
10945 return function () {
10946 setTimeout(t, 0);
10947 };
10948};
10949},{}],67:[function(_dereq_,module,exports){
10950(function (Buffer){
10951
10952exports.compare = function (a, b) {
10953
10954 if(Buffer.isBuffer(a)) {
10955 var l = Math.min(a.length, b.length)
10956 for(var i = 0; i < l; i++) {
10957 var cmp = a[i] - b[i]
10958 if(cmp) return cmp
10959 }
10960 return a.length - b.length
10961 }
10962
10963 return a < b ? -1 : a > b ? 1 : 0
10964}
10965
10966function has(obj, key) {
10967 return Object.hasOwnProperty.call(obj, key)
10968}
10969
10970// to be compatible with the current abstract-leveldown tests
10971// nullish or empty strings.
10972// I could use !!val but I want to permit numbers and booleans,
10973// if possible.
10974
10975function isDef (val) {
10976 return val !== undefined && val !== ''
10977}
10978
10979function has (range, name) {
10980 return Object.hasOwnProperty.call(range, name)
10981}
10982
10983function hasKey(range, name) {
10984 return Object.hasOwnProperty.call(range, name) && name
10985}
10986
10987var lowerBoundKey = exports.lowerBoundKey = function (range) {
10988 return (
10989 hasKey(range, 'gt')
10990 || hasKey(range, 'gte')
10991 || hasKey(range, 'min')
10992 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10993 || undefined
10994 )
10995}
10996
10997var lowerBound = exports.lowerBound = function (range) {
10998 var k = lowerBoundKey(range)
10999 return k && range[k]
11000}
11001
11002var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
11003 return has(range, 'gt') ? false : true
11004}
11005
11006var upperBoundInclusive = exports.upperBoundInclusive =
11007 function (range) {
11008 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
11009 }
11010
11011var lowerBoundExclusive = exports.lowerBoundExclusive =
11012 function (range) {
11013 return !lowerBoundInclusive(range)
11014 }
11015
11016var upperBoundExclusive = exports.upperBoundExclusive =
11017 function (range) {
11018 return !upperBoundInclusive(range)
11019 }
11020
11021var upperBoundKey = exports.upperBoundKey = function (range) {
11022 return (
11023 hasKey(range, 'lt')
11024 || hasKey(range, 'lte')
11025 || hasKey(range, 'max')
11026 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
11027 || undefined
11028 )
11029}
11030
11031var upperBound = exports.upperBound = function (range) {
11032 var k = upperBoundKey(range)
11033 return k && range[k]
11034}
11035
11036function id (e) { return e }
11037
11038exports.toLtgt = function (range, _range, map, lower, upper) {
11039 _range = _range || {}
11040 map = map || id
11041 var defaults = arguments.length > 3
11042 var lb = exports.lowerBoundKey(range)
11043 var ub = exports.upperBoundKey(range)
11044 if(lb) {
11045 if(lb === 'gt') _range.gt = map(range.gt, false)
11046 else _range.gte = map(range[lb], false)
11047 }
11048 else if(defaults)
11049 _range.gte = map(lower, false)
11050
11051 if(ub) {
11052 if(ub === 'lt') _range.lt = map(range.lt, true)
11053 else _range.lte = map(range[ub], true)
11054 }
11055 else if(defaults)
11056 _range.lte = map(upper, true)
11057
11058 if(range.reverse != null)
11059 _range.reverse = !!range.reverse
11060
11061 //if range was used mutably
11062 //(in level-sublevel it's part of an options object
11063 //that has more properties on it.)
11064 if(has(_range, 'max')) delete _range.max
11065 if(has(_range, 'min')) delete _range.min
11066 if(has(_range, 'start')) delete _range.start
11067 if(has(_range, 'end')) delete _range.end
11068
11069 return _range
11070}
11071
11072exports.contains = function (range, key, compare) {
11073 compare = compare || exports.compare
11074
11075 var lb = lowerBound(range)
11076 if(isDef(lb)) {
11077 var cmp = compare(key, lb)
11078 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
11079 return false
11080 }
11081
11082 var ub = upperBound(range)
11083 if(isDef(ub)) {
11084 var cmp = compare(key, ub)
11085 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
11086 return false
11087 }
11088
11089 return true
11090}
11091
11092exports.filter = function (range, compare) {
11093 return function (key) {
11094 return exports.contains(range, key, compare)
11095 }
11096}
11097
11098
11099
11100
11101
11102
11103}).call(this,{"isBuffer":_dereq_(26)})
11104},{"26":26}],68:[function(_dereq_,module,exports){
11105arguments[4][17][0].apply(exports,arguments)
11106},{"17":17}],69:[function(_dereq_,module,exports){
11107/*
11108object-assign
11109(c) Sindre Sorhus
11110@license MIT
11111*/
11112
11113'use strict';
11114/* eslint-disable no-unused-vars */
11115var getOwnPropertySymbols = Object.getOwnPropertySymbols;
11116var hasOwnProperty = Object.prototype.hasOwnProperty;
11117var propIsEnumerable = Object.prototype.propertyIsEnumerable;
11118
11119function toObject(val) {
11120 if (val === null || val === undefined) {
11121 throw new TypeError('Object.assign cannot be called with null or undefined');
11122 }
11123
11124 return Object(val);
11125}
11126
11127function shouldUseNative() {
11128 try {
11129 if (!Object.assign) {
11130 return false;
11131 }
11132
11133 // Detect buggy property enumeration order in older V8 versions.
11134
11135 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
11136 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
11137 test1[5] = 'de';
11138 if (Object.getOwnPropertyNames(test1)[0] === '5') {
11139 return false;
11140 }
11141
11142 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
11143 var test2 = {};
11144 for (var i = 0; i < 10; i++) {
11145 test2['_' + String.fromCharCode(i)] = i;
11146 }
11147 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
11148 return test2[n];
11149 });
11150 if (order2.join('') !== '0123456789') {
11151 return false;
11152 }
11153
11154 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
11155 var test3 = {};
11156 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
11157 test3[letter] = letter;
11158 });
11159 if (Object.keys(Object.assign({}, test3)).join('') !==
11160 'abcdefghijklmnopqrst') {
11161 return false;
11162 }
11163
11164 return true;
11165 } catch (err) {
11166 // We don't expect any of the above to throw, but better to be safe.
11167 return false;
11168 }
11169}
11170
11171module.exports = shouldUseNative() ? Object.assign : function (target, source) {
11172 var from;
11173 var to = toObject(target);
11174 var symbols;
11175
11176 for (var s = 1; s < arguments.length; s++) {
11177 from = Object(arguments[s]);
11178
11179 for (var key in from) {
11180 if (hasOwnProperty.call(from, key)) {
11181 to[key] = from[key];
11182 }
11183 }
11184
11185 if (getOwnPropertySymbols) {
11186 symbols = getOwnPropertySymbols(from);
11187 for (var i = 0; i < symbols.length; i++) {
11188 if (propIsEnumerable.call(from, symbols[i])) {
11189 to[symbols[i]] = from[symbols[i]];
11190 }
11191 }
11192 }
11193 }
11194
11195 return to;
11196};
11197
11198},{}],70:[function(_dereq_,module,exports){
11199(function (process){
11200'use strict';
11201
11202if (!process.version ||
11203 process.version.indexOf('v0.') === 0 ||
11204 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
11205 module.exports = { nextTick: nextTick };
11206} else {
11207 module.exports = process
11208}
11209
11210function nextTick(fn, arg1, arg2, arg3) {
11211 if (typeof fn !== 'function') {
11212 throw new TypeError('"callback" argument must be a function');
11213 }
11214 var len = arguments.length;
11215 var args, i;
11216 switch (len) {
11217 case 0:
11218 case 1:
11219 return process.nextTick(fn);
11220 case 2:
11221 return process.nextTick(function afterTickOne() {
11222 fn.call(null, arg1);
11223 });
11224 case 3:
11225 return process.nextTick(function afterTickTwo() {
11226 fn.call(null, arg1, arg2);
11227 });
11228 case 4:
11229 return process.nextTick(function afterTickThree() {
11230 fn.call(null, arg1, arg2, arg3);
11231 });
11232 default:
11233 args = new Array(len - 1);
11234 i = 0;
11235 while (i < args.length) {
11236 args[i++] = arguments[i];
11237 }
11238 return process.nextTick(function afterTick() {
11239 fn.apply(null, args);
11240 });
11241 }
11242}
11243
11244
11245}).call(this,_dereq_(71))
11246},{"71":71}],71:[function(_dereq_,module,exports){
11247// shim for using process in browser
11248var process = module.exports = {};
11249
11250// cached from whatever global is present so that test runners that stub it
11251// don't break things. But we need to wrap it in a try catch in case it is
11252// wrapped in strict mode code which doesn't define any globals. It's inside a
11253// function because try/catches deoptimize in certain engines.
11254
11255var cachedSetTimeout;
11256var cachedClearTimeout;
11257
11258function defaultSetTimout() {
11259 throw new Error('setTimeout has not been defined');
11260}
11261function defaultClearTimeout () {
11262 throw new Error('clearTimeout has not been defined');
11263}
11264(function () {
11265 try {
11266 if (typeof setTimeout === 'function') {
11267 cachedSetTimeout = setTimeout;
11268 } else {
11269 cachedSetTimeout = defaultSetTimout;
11270 }
11271 } catch (e) {
11272 cachedSetTimeout = defaultSetTimout;
11273 }
11274 try {
11275 if (typeof clearTimeout === 'function') {
11276 cachedClearTimeout = clearTimeout;
11277 } else {
11278 cachedClearTimeout = defaultClearTimeout;
11279 }
11280 } catch (e) {
11281 cachedClearTimeout = defaultClearTimeout;
11282 }
11283} ())
11284function runTimeout(fun) {
11285 if (cachedSetTimeout === setTimeout) {
11286 //normal enviroments in sane situations
11287 return setTimeout(fun, 0);
11288 }
11289 // if setTimeout wasn't available but was latter defined
11290 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
11291 cachedSetTimeout = setTimeout;
11292 return setTimeout(fun, 0);
11293 }
11294 try {
11295 // when when somebody has screwed with setTimeout but no I.E. maddness
11296 return cachedSetTimeout(fun, 0);
11297 } catch(e){
11298 try {
11299 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11300 return cachedSetTimeout.call(null, fun, 0);
11301 } catch(e){
11302 // 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
11303 return cachedSetTimeout.call(this, fun, 0);
11304 }
11305 }
11306
11307
11308}
11309function runClearTimeout(marker) {
11310 if (cachedClearTimeout === clearTimeout) {
11311 //normal enviroments in sane situations
11312 return clearTimeout(marker);
11313 }
11314 // if clearTimeout wasn't available but was latter defined
11315 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
11316 cachedClearTimeout = clearTimeout;
11317 return clearTimeout(marker);
11318 }
11319 try {
11320 // when when somebody has screwed with setTimeout but no I.E. maddness
11321 return cachedClearTimeout(marker);
11322 } catch (e){
11323 try {
11324 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11325 return cachedClearTimeout.call(null, marker);
11326 } catch (e){
11327 // 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.
11328 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
11329 return cachedClearTimeout.call(this, marker);
11330 }
11331 }
11332
11333
11334
11335}
11336var queue = [];
11337var draining = false;
11338var currentQueue;
11339var queueIndex = -1;
11340
11341function cleanUpNextTick() {
11342 if (!draining || !currentQueue) {
11343 return;
11344 }
11345 draining = false;
11346 if (currentQueue.length) {
11347 queue = currentQueue.concat(queue);
11348 } else {
11349 queueIndex = -1;
11350 }
11351 if (queue.length) {
11352 drainQueue();
11353 }
11354}
11355
11356function drainQueue() {
11357 if (draining) {
11358 return;
11359 }
11360 var timeout = runTimeout(cleanUpNextTick);
11361 draining = true;
11362
11363 var len = queue.length;
11364 while(len) {
11365 currentQueue = queue;
11366 queue = [];
11367 while (++queueIndex < len) {
11368 if (currentQueue) {
11369 currentQueue[queueIndex].run();
11370 }
11371 }
11372 queueIndex = -1;
11373 len = queue.length;
11374 }
11375 currentQueue = null;
11376 draining = false;
11377 runClearTimeout(timeout);
11378}
11379
11380process.nextTick = function (fun) {
11381 var args = new Array(arguments.length - 1);
11382 if (arguments.length > 1) {
11383 for (var i = 1; i < arguments.length; i++) {
11384 args[i - 1] = arguments[i];
11385 }
11386 }
11387 queue.push(new Item(fun, args));
11388 if (queue.length === 1 && !draining) {
11389 runTimeout(drainQueue);
11390 }
11391};
11392
11393// v8 likes predictible objects
11394function Item(fun, array) {
11395 this.fun = fun;
11396 this.array = array;
11397}
11398Item.prototype.run = function () {
11399 this.fun.apply(null, this.array);
11400};
11401process.title = 'browser';
11402process.browser = true;
11403process.env = {};
11404process.argv = [];
11405process.version = ''; // empty string to avoid regexp issues
11406process.versions = {};
11407
11408function noop() {}
11409
11410process.on = noop;
11411process.addListener = noop;
11412process.once = noop;
11413process.off = noop;
11414process.removeListener = noop;
11415process.removeAllListeners = noop;
11416process.emit = noop;
11417process.prependListener = noop;
11418process.prependOnceListener = noop;
11419
11420process.listeners = function (name) { return [] }
11421
11422process.binding = function (name) {
11423 throw new Error('process.binding is not supported');
11424};
11425
11426process.cwd = function () { return '/' };
11427process.chdir = function (dir) {
11428 throw new Error('process.chdir is not supported');
11429};
11430process.umask = function() { return 0; };
11431
11432},{}],72:[function(_dereq_,module,exports){
11433/*!
11434 * prr
11435 * (c) 2013 Rod Vagg <rod@vagg.org>
11436 * https://github.com/rvagg/prr
11437 * License: MIT
11438 */
11439
11440(function (name, context, definition) {
11441 if (typeof module != 'undefined' && module.exports)
11442 module.exports = definition()
11443 else
11444 context[name] = definition()
11445})('prr', this, function() {
11446
11447 var setProperty = typeof Object.defineProperty == 'function'
11448 ? function (obj, key, options) {
11449 Object.defineProperty(obj, key, options)
11450 return obj
11451 }
11452 : function (obj, key, options) { // < es5
11453 obj[key] = options.value
11454 return obj
11455 }
11456
11457 , makeOptions = function (value, options) {
11458 var oo = typeof options == 'object'
11459 , os = !oo && typeof options == 'string'
11460 , op = function (p) {
11461 return oo
11462 ? !!options[p]
11463 : os
11464 ? options.indexOf(p[0]) > -1
11465 : false
11466 }
11467
11468 return {
11469 enumerable : op('enumerable')
11470 , configurable : op('configurable')
11471 , writable : op('writable')
11472 , value : value
11473 }
11474 }
11475
11476 , prr = function (obj, key, value, options) {
11477 var k
11478
11479 options = makeOptions(value, options)
11480
11481 if (typeof key == 'object') {
11482 for (k in key) {
11483 if (Object.hasOwnProperty.call(key, k)) {
11484 options.value = key[k]
11485 setProperty(obj, k, options)
11486 }
11487 }
11488 return obj
11489 }
11490
11491 return setProperty(obj, key, options)
11492 }
11493
11494 return prr
11495})
11496},{}],73:[function(_dereq_,module,exports){
11497(function (process){
11498// Copyright Joyent, Inc. and other Node contributors.
11499//
11500// Permission is hereby granted, free of charge, to any person obtaining a
11501// copy of this software and associated documentation files (the
11502// "Software"), to deal in the Software without restriction, including
11503// without limitation the rights to use, copy, modify, merge, publish,
11504// distribute, sublicense, and/or sell copies of the Software, and to permit
11505// persons to whom the Software is furnished to do so, subject to the
11506// following conditions:
11507//
11508// The above copyright notice and this permission notice shall be included
11509// in all copies or substantial portions of the Software.
11510//
11511// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11512// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11513// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11514// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11515// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11516// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11517// USE OR OTHER DEALINGS IN THE SOFTWARE.
11518
11519// a duplex stream is just a stream that is both readable and writable.
11520// Since JS doesn't have multiple prototypal inheritance, this class
11521// prototypally inherits from Readable, and then parasitically from
11522// Writable.
11523
11524module.exports = Duplex;
11525
11526/*<replacement>*/
11527var objectKeys = Object.keys || function (obj) {
11528 var keys = [];
11529 for (var key in obj) keys.push(key);
11530 return keys;
11531}
11532/*</replacement>*/
11533
11534
11535/*<replacement>*/
11536var util = _dereq_(10);
11537util.inherits = _dereq_(25);
11538/*</replacement>*/
11539
11540var Readable = _dereq_(75);
11541var Writable = _dereq_(77);
11542
11543util.inherits(Duplex, Readable);
11544
11545forEach(objectKeys(Writable.prototype), function(method) {
11546 if (!Duplex.prototype[method])
11547 Duplex.prototype[method] = Writable.prototype[method];
11548});
11549
11550function Duplex(options) {
11551 if (!(this instanceof Duplex))
11552 return new Duplex(options);
11553
11554 Readable.call(this, options);
11555 Writable.call(this, options);
11556
11557 if (options && options.readable === false)
11558 this.readable = false;
11559
11560 if (options && options.writable === false)
11561 this.writable = false;
11562
11563 this.allowHalfOpen = true;
11564 if (options && options.allowHalfOpen === false)
11565 this.allowHalfOpen = false;
11566
11567 this.once('end', onend);
11568}
11569
11570// the no-half-open enforcer
11571function onend() {
11572 // if we allow half-open state, or if the writable side ended,
11573 // then we're ok.
11574 if (this.allowHalfOpen || this._writableState.ended)
11575 return;
11576
11577 // no more data can be written.
11578 // But allow more writes to happen in this tick.
11579 process.nextTick(this.end.bind(this));
11580}
11581
11582function forEach (xs, f) {
11583 for (var i = 0, l = xs.length; i < l; i++) {
11584 f(xs[i], i);
11585 }
11586}
11587
11588}).call(this,_dereq_(71))
11589},{"10":10,"25":25,"71":71,"75":75,"77":77}],74:[function(_dereq_,module,exports){
11590// Copyright Joyent, Inc. and other Node contributors.
11591//
11592// Permission is hereby granted, free of charge, to any person obtaining a
11593// copy of this software and associated documentation files (the
11594// "Software"), to deal in the Software without restriction, including
11595// without limitation the rights to use, copy, modify, merge, publish,
11596// distribute, sublicense, and/or sell copies of the Software, and to permit
11597// persons to whom the Software is furnished to do so, subject to the
11598// following conditions:
11599//
11600// The above copyright notice and this permission notice shall be included
11601// in all copies or substantial portions of the Software.
11602//
11603// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11604// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11605// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11606// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11607// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11608// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11609// USE OR OTHER DEALINGS IN THE SOFTWARE.
11610
11611// a passthrough stream.
11612// basically just the most minimal sort of Transform stream.
11613// Every written chunk gets output as-is.
11614
11615module.exports = PassThrough;
11616
11617var Transform = _dereq_(76);
11618
11619/*<replacement>*/
11620var util = _dereq_(10);
11621util.inherits = _dereq_(25);
11622/*</replacement>*/
11623
11624util.inherits(PassThrough, Transform);
11625
11626function PassThrough(options) {
11627 if (!(this instanceof PassThrough))
11628 return new PassThrough(options);
11629
11630 Transform.call(this, options);
11631}
11632
11633PassThrough.prototype._transform = function(chunk, encoding, cb) {
11634 cb(null, chunk);
11635};
11636
11637},{"10":10,"25":25,"76":76}],75:[function(_dereq_,module,exports){
11638(function (process){
11639// Copyright Joyent, Inc. and other Node contributors.
11640//
11641// Permission is hereby granted, free of charge, to any person obtaining a
11642// copy of this software and associated documentation files (the
11643// "Software"), to deal in the Software without restriction, including
11644// without limitation the rights to use, copy, modify, merge, publish,
11645// distribute, sublicense, and/or sell copies of the Software, and to permit
11646// persons to whom the Software is furnished to do so, subject to the
11647// following conditions:
11648//
11649// The above copyright notice and this permission notice shall be included
11650// in all copies or substantial portions of the Software.
11651//
11652// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11653// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11654// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11655// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11656// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11657// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11658// USE OR OTHER DEALINGS IN THE SOFTWARE.
11659
11660module.exports = Readable;
11661
11662/*<replacement>*/
11663var isArray = _dereq_(27);
11664/*</replacement>*/
11665
11666
11667/*<replacement>*/
11668var Buffer = _dereq_(9).Buffer;
11669/*</replacement>*/
11670
11671Readable.ReadableState = ReadableState;
11672
11673var EE = _dereq_(21).EventEmitter;
11674
11675/*<replacement>*/
11676if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11677 return emitter.listeners(type).length;
11678};
11679/*</replacement>*/
11680
11681var Stream = _dereq_(82);
11682
11683/*<replacement>*/
11684var util = _dereq_(10);
11685util.inherits = _dereq_(25);
11686/*</replacement>*/
11687
11688var StringDecoder;
11689
11690util.inherits(Readable, Stream);
11691
11692function ReadableState(options, stream) {
11693 options = options || {};
11694
11695 // the point at which it stops calling _read() to fill the buffer
11696 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11697 var hwm = options.highWaterMark;
11698 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
11699
11700 // cast to ints.
11701 this.highWaterMark = ~~this.highWaterMark;
11702
11703 this.buffer = [];
11704 this.length = 0;
11705 this.pipes = null;
11706 this.pipesCount = 0;
11707 this.flowing = false;
11708 this.ended = false;
11709 this.endEmitted = false;
11710 this.reading = false;
11711
11712 // In streams that never have any data, and do push(null) right away,
11713 // the consumer can miss the 'end' event if they do some I/O before
11714 // consuming the stream. So, we don't emit('end') until some reading
11715 // happens.
11716 this.calledRead = false;
11717
11718 // a flag to be able to tell if the onwrite cb is called immediately,
11719 // or on a later tick. We set this to true at first, becuase any
11720 // actions that shouldn't happen until "later" should generally also
11721 // not happen before the first write call.
11722 this.sync = true;
11723
11724 // whenever we return null, then we set a flag to say
11725 // that we're awaiting a 'readable' event emission.
11726 this.needReadable = false;
11727 this.emittedReadable = false;
11728 this.readableListening = false;
11729
11730
11731 // object stream flag. Used to make read(n) ignore n and to
11732 // make all the buffer merging and length checks go away
11733 this.objectMode = !!options.objectMode;
11734
11735 // Crypto is kind of old and crusty. Historically, its default string
11736 // encoding is 'binary' so we have to make this configurable.
11737 // Everything else in the universe uses 'utf8', though.
11738 this.defaultEncoding = options.defaultEncoding || 'utf8';
11739
11740 // when piping, we only care about 'readable' events that happen
11741 // after read()ing all the bytes and not getting any pushback.
11742 this.ranOut = false;
11743
11744 // the number of writers that are awaiting a drain event in .pipe()s
11745 this.awaitDrain = 0;
11746
11747 // if true, a maybeReadMore has been scheduled
11748 this.readingMore = false;
11749
11750 this.decoder = null;
11751 this.encoding = null;
11752 if (options.encoding) {
11753 if (!StringDecoder)
11754 StringDecoder = _dereq_(78).StringDecoder;
11755 this.decoder = new StringDecoder(options.encoding);
11756 this.encoding = options.encoding;
11757 }
11758}
11759
11760function Readable(options) {
11761 if (!(this instanceof Readable))
11762 return new Readable(options);
11763
11764 this._readableState = new ReadableState(options, this);
11765
11766 // legacy
11767 this.readable = true;
11768
11769 Stream.call(this);
11770}
11771
11772// Manually shove something into the read() buffer.
11773// This returns true if the highWaterMark has not been hit yet,
11774// similar to how Writable.write() returns true if you should
11775// write() some more.
11776Readable.prototype.push = function(chunk, encoding) {
11777 var state = this._readableState;
11778
11779 if (typeof chunk === 'string' && !state.objectMode) {
11780 encoding = encoding || state.defaultEncoding;
11781 if (encoding !== state.encoding) {
11782 chunk = new Buffer(chunk, encoding);
11783 encoding = '';
11784 }
11785 }
11786
11787 return readableAddChunk(this, state, chunk, encoding, false);
11788};
11789
11790// Unshift should *always* be something directly out of read()
11791Readable.prototype.unshift = function(chunk) {
11792 var state = this._readableState;
11793 return readableAddChunk(this, state, chunk, '', true);
11794};
11795
11796function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11797 var er = chunkInvalid(state, chunk);
11798 if (er) {
11799 stream.emit('error', er);
11800 } else if (chunk === null || chunk === undefined) {
11801 state.reading = false;
11802 if (!state.ended)
11803 onEofChunk(stream, state);
11804 } else if (state.objectMode || chunk && chunk.length > 0) {
11805 if (state.ended && !addToFront) {
11806 var e = new Error('stream.push() after EOF');
11807 stream.emit('error', e);
11808 } else if (state.endEmitted && addToFront) {
11809 var e = new Error('stream.unshift() after end event');
11810 stream.emit('error', e);
11811 } else {
11812 if (state.decoder && !addToFront && !encoding)
11813 chunk = state.decoder.write(chunk);
11814
11815 // update the buffer info.
11816 state.length += state.objectMode ? 1 : chunk.length;
11817 if (addToFront) {
11818 state.buffer.unshift(chunk);
11819 } else {
11820 state.reading = false;
11821 state.buffer.push(chunk);
11822 }
11823
11824 if (state.needReadable)
11825 emitReadable(stream);
11826
11827 maybeReadMore(stream, state);
11828 }
11829 } else if (!addToFront) {
11830 state.reading = false;
11831 }
11832
11833 return needMoreData(state);
11834}
11835
11836
11837
11838// if it's past the high water mark, we can push in some more.
11839// Also, if we have no data yet, we can stand some
11840// more bytes. This is to work around cases where hwm=0,
11841// such as the repl. Also, if the push() triggered a
11842// readable event, and the user called read(largeNumber) such that
11843// needReadable was set, then we ought to push more, so that another
11844// 'readable' event will be triggered.
11845function needMoreData(state) {
11846 return !state.ended &&
11847 (state.needReadable ||
11848 state.length < state.highWaterMark ||
11849 state.length === 0);
11850}
11851
11852// backwards compatibility.
11853Readable.prototype.setEncoding = function(enc) {
11854 if (!StringDecoder)
11855 StringDecoder = _dereq_(78).StringDecoder;
11856 this._readableState.decoder = new StringDecoder(enc);
11857 this._readableState.encoding = enc;
11858};
11859
11860// Don't raise the hwm > 128MB
11861var MAX_HWM = 0x800000;
11862function roundUpToNextPowerOf2(n) {
11863 if (n >= MAX_HWM) {
11864 n = MAX_HWM;
11865 } else {
11866 // Get the next highest power of 2
11867 n--;
11868 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
11869 n++;
11870 }
11871 return n;
11872}
11873
11874function howMuchToRead(n, state) {
11875 if (state.length === 0 && state.ended)
11876 return 0;
11877
11878 if (state.objectMode)
11879 return n === 0 ? 0 : 1;
11880
11881 if (n === null || isNaN(n)) {
11882 // only flow one buffer at a time
11883 if (state.flowing && state.buffer.length)
11884 return state.buffer[0].length;
11885 else
11886 return state.length;
11887 }
11888
11889 if (n <= 0)
11890 return 0;
11891
11892 // If we're asking for more than the target buffer level,
11893 // then raise the water mark. Bump up to the next highest
11894 // power of 2, to prevent increasing it excessively in tiny
11895 // amounts.
11896 if (n > state.highWaterMark)
11897 state.highWaterMark = roundUpToNextPowerOf2(n);
11898
11899 // don't have that much. return null, unless we've ended.
11900 if (n > state.length) {
11901 if (!state.ended) {
11902 state.needReadable = true;
11903 return 0;
11904 } else
11905 return state.length;
11906 }
11907
11908 return n;
11909}
11910
11911// you can override either this method, or the async _read(n) below.
11912Readable.prototype.read = function(n) {
11913 var state = this._readableState;
11914 state.calledRead = true;
11915 var nOrig = n;
11916 var ret;
11917
11918 if (typeof n !== 'number' || n > 0)
11919 state.emittedReadable = false;
11920
11921 // if we're doing read(0) to trigger a readable event, but we
11922 // already have a bunch of data in the buffer, then just trigger
11923 // the 'readable' event and move on.
11924 if (n === 0 &&
11925 state.needReadable &&
11926 (state.length >= state.highWaterMark || state.ended)) {
11927 emitReadable(this);
11928 return null;
11929 }
11930
11931 n = howMuchToRead(n, state);
11932
11933 // if we've ended, and we're now clear, then finish it up.
11934 if (n === 0 && state.ended) {
11935 ret = null;
11936
11937 // In cases where the decoder did not receive enough data
11938 // to produce a full chunk, then immediately received an
11939 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
11940 // howMuchToRead will see this and coerce the amount to
11941 // read to zero (because it's looking at the length of the
11942 // first <Buffer > in state.buffer), and we'll end up here.
11943 //
11944 // This can only happen via state.decoder -- no other venue
11945 // exists for pushing a zero-length chunk into state.buffer
11946 // and triggering this behavior. In this case, we return our
11947 // remaining data and end the stream, if appropriate.
11948 if (state.length > 0 && state.decoder) {
11949 ret = fromList(n, state);
11950 state.length -= ret.length;
11951 }
11952
11953 if (state.length === 0)
11954 endReadable(this);
11955
11956 return ret;
11957 }
11958
11959 // All the actual chunk generation logic needs to be
11960 // *below* the call to _read. The reason is that in certain
11961 // synthetic stream cases, such as passthrough streams, _read
11962 // may be a completely synchronous operation which may change
11963 // the state of the read buffer, providing enough data when
11964 // before there was *not* enough.
11965 //
11966 // So, the steps are:
11967 // 1. Figure out what the state of things will be after we do
11968 // a read from the buffer.
11969 //
11970 // 2. If that resulting state will trigger a _read, then call _read.
11971 // Note that this may be asynchronous, or synchronous. Yes, it is
11972 // deeply ugly to write APIs this way, but that still doesn't mean
11973 // that the Readable class should behave improperly, as streams are
11974 // designed to be sync/async agnostic.
11975 // Take note if the _read call is sync or async (ie, if the read call
11976 // has returned yet), so that we know whether or not it's safe to emit
11977 // 'readable' etc.
11978 //
11979 // 3. Actually pull the requested chunks out of the buffer and return.
11980
11981 // if we need a readable event, then we need to do some reading.
11982 var doRead = state.needReadable;
11983
11984 // if we currently have less than the highWaterMark, then also read some
11985 if (state.length - n <= state.highWaterMark)
11986 doRead = true;
11987
11988 // however, if we've ended, then there's no point, and if we're already
11989 // reading, then it's unnecessary.
11990 if (state.ended || state.reading)
11991 doRead = false;
11992
11993 if (doRead) {
11994 state.reading = true;
11995 state.sync = true;
11996 // if the length is currently zero, then we *need* a readable event.
11997 if (state.length === 0)
11998 state.needReadable = true;
11999 // call internal read method
12000 this._read(state.highWaterMark);
12001 state.sync = false;
12002 }
12003
12004 // If _read called its callback synchronously, then `reading`
12005 // will be false, and we need to re-evaluate how much data we
12006 // can return to the user.
12007 if (doRead && !state.reading)
12008 n = howMuchToRead(nOrig, state);
12009
12010 if (n > 0)
12011 ret = fromList(n, state);
12012 else
12013 ret = null;
12014
12015 if (ret === null) {
12016 state.needReadable = true;
12017 n = 0;
12018 }
12019
12020 state.length -= n;
12021
12022 // If we have nothing in the buffer, then we want to know
12023 // as soon as we *do* get something into the buffer.
12024 if (state.length === 0 && !state.ended)
12025 state.needReadable = true;
12026
12027 // If we happened to read() exactly the remaining amount in the
12028 // buffer, and the EOF has been seen at this point, then make sure
12029 // that we emit 'end' on the very next tick.
12030 if (state.ended && !state.endEmitted && state.length === 0)
12031 endReadable(this);
12032
12033 return ret;
12034};
12035
12036function chunkInvalid(state, chunk) {
12037 var er = null;
12038 if (!Buffer.isBuffer(chunk) &&
12039 'string' !== typeof chunk &&
12040 chunk !== null &&
12041 chunk !== undefined &&
12042 !state.objectMode) {
12043 er = new TypeError('Invalid non-string/buffer chunk');
12044 }
12045 return er;
12046}
12047
12048
12049function onEofChunk(stream, state) {
12050 if (state.decoder && !state.ended) {
12051 var chunk = state.decoder.end();
12052 if (chunk && chunk.length) {
12053 state.buffer.push(chunk);
12054 state.length += state.objectMode ? 1 : chunk.length;
12055 }
12056 }
12057 state.ended = true;
12058
12059 // if we've ended and we have some data left, then emit
12060 // 'readable' now to make sure it gets picked up.
12061 if (state.length > 0)
12062 emitReadable(stream);
12063 else
12064 endReadable(stream);
12065}
12066
12067// Don't emit readable right away in sync mode, because this can trigger
12068// another read() call => stack overflow. This way, it might trigger
12069// a nextTick recursion warning, but that's not so bad.
12070function emitReadable(stream) {
12071 var state = stream._readableState;
12072 state.needReadable = false;
12073 if (state.emittedReadable)
12074 return;
12075
12076 state.emittedReadable = true;
12077 if (state.sync)
12078 process.nextTick(function() {
12079 emitReadable_(stream);
12080 });
12081 else
12082 emitReadable_(stream);
12083}
12084
12085function emitReadable_(stream) {
12086 stream.emit('readable');
12087}
12088
12089
12090// at this point, the user has presumably seen the 'readable' event,
12091// and called read() to consume some data. that may have triggered
12092// in turn another _read(n) call, in which case reading = true if
12093// it's in progress.
12094// However, if we're not ended, or reading, and the length < hwm,
12095// then go ahead and try to read some more preemptively.
12096function maybeReadMore(stream, state) {
12097 if (!state.readingMore) {
12098 state.readingMore = true;
12099 process.nextTick(function() {
12100 maybeReadMore_(stream, state);
12101 });
12102 }
12103}
12104
12105function maybeReadMore_(stream, state) {
12106 var len = state.length;
12107 while (!state.reading && !state.flowing && !state.ended &&
12108 state.length < state.highWaterMark) {
12109 stream.read(0);
12110 if (len === state.length)
12111 // didn't get any data, stop spinning.
12112 break;
12113 else
12114 len = state.length;
12115 }
12116 state.readingMore = false;
12117}
12118
12119// abstract method. to be overridden in specific implementation classes.
12120// call cb(er, data) where data is <= n in length.
12121// for virtual (non-string, non-buffer) streams, "length" is somewhat
12122// arbitrary, and perhaps not very meaningful.
12123Readable.prototype._read = function(n) {
12124 this.emit('error', new Error('not implemented'));
12125};
12126
12127Readable.prototype.pipe = function(dest, pipeOpts) {
12128 var src = this;
12129 var state = this._readableState;
12130
12131 switch (state.pipesCount) {
12132 case 0:
12133 state.pipes = dest;
12134 break;
12135 case 1:
12136 state.pipes = [state.pipes, dest];
12137 break;
12138 default:
12139 state.pipes.push(dest);
12140 break;
12141 }
12142 state.pipesCount += 1;
12143
12144 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
12145 dest !== process.stdout &&
12146 dest !== process.stderr;
12147
12148 var endFn = doEnd ? onend : cleanup;
12149 if (state.endEmitted)
12150 process.nextTick(endFn);
12151 else
12152 src.once('end', endFn);
12153
12154 dest.on('unpipe', onunpipe);
12155 function onunpipe(readable) {
12156 if (readable !== src) return;
12157 cleanup();
12158 }
12159
12160 function onend() {
12161 dest.end();
12162 }
12163
12164 // when the dest drains, it reduces the awaitDrain counter
12165 // on the source. This would be more elegant with a .once()
12166 // handler in flow(), but adding and removing repeatedly is
12167 // too slow.
12168 var ondrain = pipeOnDrain(src);
12169 dest.on('drain', ondrain);
12170
12171 function cleanup() {
12172 // cleanup event handlers once the pipe is broken
12173 dest.removeListener('close', onclose);
12174 dest.removeListener('finish', onfinish);
12175 dest.removeListener('drain', ondrain);
12176 dest.removeListener('error', onerror);
12177 dest.removeListener('unpipe', onunpipe);
12178 src.removeListener('end', onend);
12179 src.removeListener('end', cleanup);
12180
12181 // if the reader is waiting for a drain event from this
12182 // specific writer, then it would cause it to never start
12183 // flowing again.
12184 // So, if this is awaiting a drain, then we just call it now.
12185 // If we don't know, then assume that we are waiting for one.
12186 if (!dest._writableState || dest._writableState.needDrain)
12187 ondrain();
12188 }
12189
12190 // if the dest has an error, then stop piping into it.
12191 // however, don't suppress the throwing behavior for this.
12192 function onerror(er) {
12193 unpipe();
12194 dest.removeListener('error', onerror);
12195 if (EE.listenerCount(dest, 'error') === 0)
12196 dest.emit('error', er);
12197 }
12198 // This is a brutally ugly hack to make sure that our error handler
12199 // is attached before any userland ones. NEVER DO THIS.
12200 if (!dest._events || !dest._events.error)
12201 dest.on('error', onerror);
12202 else if (isArray(dest._events.error))
12203 dest._events.error.unshift(onerror);
12204 else
12205 dest._events.error = [onerror, dest._events.error];
12206
12207
12208
12209 // Both close and finish should trigger unpipe, but only once.
12210 function onclose() {
12211 dest.removeListener('finish', onfinish);
12212 unpipe();
12213 }
12214 dest.once('close', onclose);
12215 function onfinish() {
12216 dest.removeListener('close', onclose);
12217 unpipe();
12218 }
12219 dest.once('finish', onfinish);
12220
12221 function unpipe() {
12222 src.unpipe(dest);
12223 }
12224
12225 // tell the dest that it's being piped to
12226 dest.emit('pipe', src);
12227
12228 // start the flow if it hasn't been started already.
12229 if (!state.flowing) {
12230 // the handler that waits for readable events after all
12231 // the data gets sucked out in flow.
12232 // This would be easier to follow with a .once() handler
12233 // in flow(), but that is too slow.
12234 this.on('readable', pipeOnReadable);
12235
12236 state.flowing = true;
12237 process.nextTick(function() {
12238 flow(src);
12239 });
12240 }
12241
12242 return dest;
12243};
12244
12245function pipeOnDrain(src) {
12246 return function() {
12247 var dest = this;
12248 var state = src._readableState;
12249 state.awaitDrain--;
12250 if (state.awaitDrain === 0)
12251 flow(src);
12252 };
12253}
12254
12255function flow(src) {
12256 var state = src._readableState;
12257 var chunk;
12258 state.awaitDrain = 0;
12259
12260 function write(dest, i, list) {
12261 var written = dest.write(chunk);
12262 if (false === written) {
12263 state.awaitDrain++;
12264 }
12265 }
12266
12267 while (state.pipesCount && null !== (chunk = src.read())) {
12268
12269 if (state.pipesCount === 1)
12270 write(state.pipes, 0, null);
12271 else
12272 forEach(state.pipes, write);
12273
12274 src.emit('data', chunk);
12275
12276 // if anyone needs a drain, then we have to wait for that.
12277 if (state.awaitDrain > 0)
12278 return;
12279 }
12280
12281 // if every destination was unpiped, either before entering this
12282 // function, or in the while loop, then stop flowing.
12283 //
12284 // NB: This is a pretty rare edge case.
12285 if (state.pipesCount === 0) {
12286 state.flowing = false;
12287
12288 // if there were data event listeners added, then switch to old mode.
12289 if (EE.listenerCount(src, 'data') > 0)
12290 emitDataEvents(src);
12291 return;
12292 }
12293
12294 // at this point, no one needed a drain, so we just ran out of data
12295 // on the next readable event, start it over again.
12296 state.ranOut = true;
12297}
12298
12299function pipeOnReadable() {
12300 if (this._readableState.ranOut) {
12301 this._readableState.ranOut = false;
12302 flow(this);
12303 }
12304}
12305
12306
12307Readable.prototype.unpipe = function(dest) {
12308 var state = this._readableState;
12309
12310 // if we're not piping anywhere, then do nothing.
12311 if (state.pipesCount === 0)
12312 return this;
12313
12314 // just one destination. most common case.
12315 if (state.pipesCount === 1) {
12316 // passed in one, but it's not the right one.
12317 if (dest && dest !== state.pipes)
12318 return this;
12319
12320 if (!dest)
12321 dest = state.pipes;
12322
12323 // got a match.
12324 state.pipes = null;
12325 state.pipesCount = 0;
12326 this.removeListener('readable', pipeOnReadable);
12327 state.flowing = false;
12328 if (dest)
12329 dest.emit('unpipe', this);
12330 return this;
12331 }
12332
12333 // slow case. multiple pipe destinations.
12334
12335 if (!dest) {
12336 // remove all.
12337 var dests = state.pipes;
12338 var len = state.pipesCount;
12339 state.pipes = null;
12340 state.pipesCount = 0;
12341 this.removeListener('readable', pipeOnReadable);
12342 state.flowing = false;
12343
12344 for (var i = 0; i < len; i++)
12345 dests[i].emit('unpipe', this);
12346 return this;
12347 }
12348
12349 // try to find the right one.
12350 var i = indexOf(state.pipes, dest);
12351 if (i === -1)
12352 return this;
12353
12354 state.pipes.splice(i, 1);
12355 state.pipesCount -= 1;
12356 if (state.pipesCount === 1)
12357 state.pipes = state.pipes[0];
12358
12359 dest.emit('unpipe', this);
12360
12361 return this;
12362};
12363
12364// set up data events if they are asked for
12365// Ensure readable listeners eventually get something
12366Readable.prototype.on = function(ev, fn) {
12367 var res = Stream.prototype.on.call(this, ev, fn);
12368
12369 if (ev === 'data' && !this._readableState.flowing)
12370 emitDataEvents(this);
12371
12372 if (ev === 'readable' && this.readable) {
12373 var state = this._readableState;
12374 if (!state.readableListening) {
12375 state.readableListening = true;
12376 state.emittedReadable = false;
12377 state.needReadable = true;
12378 if (!state.reading) {
12379 this.read(0);
12380 } else if (state.length) {
12381 emitReadable(this, state);
12382 }
12383 }
12384 }
12385
12386 return res;
12387};
12388Readable.prototype.addListener = Readable.prototype.on;
12389
12390// pause() and resume() are remnants of the legacy readable stream API
12391// If the user uses them, then switch into old mode.
12392Readable.prototype.resume = function() {
12393 emitDataEvents(this);
12394 this.read(0);
12395 this.emit('resume');
12396};
12397
12398Readable.prototype.pause = function() {
12399 emitDataEvents(this, true);
12400 this.emit('pause');
12401};
12402
12403function emitDataEvents(stream, startPaused) {
12404 var state = stream._readableState;
12405
12406 if (state.flowing) {
12407 // https://github.com/isaacs/readable-stream/issues/16
12408 throw new Error('Cannot switch to old mode now.');
12409 }
12410
12411 var paused = startPaused || false;
12412 var readable = false;
12413
12414 // convert to an old-style stream.
12415 stream.readable = true;
12416 stream.pipe = Stream.prototype.pipe;
12417 stream.on = stream.addListener = Stream.prototype.on;
12418
12419 stream.on('readable', function() {
12420 readable = true;
12421
12422 var c;
12423 while (!paused && (null !== (c = stream.read())))
12424 stream.emit('data', c);
12425
12426 if (c === null) {
12427 readable = false;
12428 stream._readableState.needReadable = true;
12429 }
12430 });
12431
12432 stream.pause = function() {
12433 paused = true;
12434 this.emit('pause');
12435 };
12436
12437 stream.resume = function() {
12438 paused = false;
12439 if (readable)
12440 process.nextTick(function() {
12441 stream.emit('readable');
12442 });
12443 else
12444 this.read(0);
12445 this.emit('resume');
12446 };
12447
12448 // now make it start, just in case it hadn't already.
12449 stream.emit('readable');
12450}
12451
12452// wrap an old-style stream as the async data source.
12453// This is *not* part of the readable stream interface.
12454// It is an ugly unfortunate mess of history.
12455Readable.prototype.wrap = function(stream) {
12456 var state = this._readableState;
12457 var paused = false;
12458
12459 var self = this;
12460 stream.on('end', function() {
12461 if (state.decoder && !state.ended) {
12462 var chunk = state.decoder.end();
12463 if (chunk && chunk.length)
12464 self.push(chunk);
12465 }
12466
12467 self.push(null);
12468 });
12469
12470 stream.on('data', function(chunk) {
12471 if (state.decoder)
12472 chunk = state.decoder.write(chunk);
12473
12474 // don't skip over falsy values in objectMode
12475 //if (state.objectMode && util.isNullOrUndefined(chunk))
12476 if (state.objectMode && (chunk === null || chunk === undefined))
12477 return;
12478 else if (!state.objectMode && (!chunk || !chunk.length))
12479 return;
12480
12481 var ret = self.push(chunk);
12482 if (!ret) {
12483 paused = true;
12484 stream.pause();
12485 }
12486 });
12487
12488 // proxy all the other methods.
12489 // important when wrapping filters and duplexes.
12490 for (var i in stream) {
12491 if (typeof stream[i] === 'function' &&
12492 typeof this[i] === 'undefined') {
12493 this[i] = function(method) { return function() {
12494 return stream[method].apply(stream, arguments);
12495 }}(i);
12496 }
12497 }
12498
12499 // proxy certain important events.
12500 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
12501 forEach(events, function(ev) {
12502 stream.on(ev, self.emit.bind(self, ev));
12503 });
12504
12505 // when we try to consume some more bytes, simply unpause the
12506 // underlying stream.
12507 self._read = function(n) {
12508 if (paused) {
12509 paused = false;
12510 stream.resume();
12511 }
12512 };
12513
12514 return self;
12515};
12516
12517
12518
12519// exposed for testing purposes only.
12520Readable._fromList = fromList;
12521
12522// Pluck off n bytes from an array of buffers.
12523// Length is the combined lengths of all the buffers in the list.
12524function fromList(n, state) {
12525 var list = state.buffer;
12526 var length = state.length;
12527 var stringMode = !!state.decoder;
12528 var objectMode = !!state.objectMode;
12529 var ret;
12530
12531 // nothing in the list, definitely empty.
12532 if (list.length === 0)
12533 return null;
12534
12535 if (length === 0)
12536 ret = null;
12537 else if (objectMode)
12538 ret = list.shift();
12539 else if (!n || n >= length) {
12540 // read it all, truncate the array.
12541 if (stringMode)
12542 ret = list.join('');
12543 else
12544 ret = Buffer.concat(list, length);
12545 list.length = 0;
12546 } else {
12547 // read just some of it.
12548 if (n < list[0].length) {
12549 // just take a part of the first list item.
12550 // slice is the same for buffers and strings.
12551 var buf = list[0];
12552 ret = buf.slice(0, n);
12553 list[0] = buf.slice(n);
12554 } else if (n === list[0].length) {
12555 // first list is a perfect match
12556 ret = list.shift();
12557 } else {
12558 // complex case.
12559 // we have enough to cover it, but it spans past the first buffer.
12560 if (stringMode)
12561 ret = '';
12562 else
12563 ret = new Buffer(n);
12564
12565 var c = 0;
12566 for (var i = 0, l = list.length; i < l && c < n; i++) {
12567 var buf = list[0];
12568 var cpy = Math.min(n - c, buf.length);
12569
12570 if (stringMode)
12571 ret += buf.slice(0, cpy);
12572 else
12573 buf.copy(ret, c, 0, cpy);
12574
12575 if (cpy < buf.length)
12576 list[0] = buf.slice(cpy);
12577 else
12578 list.shift();
12579
12580 c += cpy;
12581 }
12582 }
12583 }
12584
12585 return ret;
12586}
12587
12588function endReadable(stream) {
12589 var state = stream._readableState;
12590
12591 // If we get here before consuming all the bytes, then that is a
12592 // bug in node. Should never happen.
12593 if (state.length > 0)
12594 throw new Error('endReadable called on non-empty stream');
12595
12596 if (!state.endEmitted && state.calledRead) {
12597 state.ended = true;
12598 process.nextTick(function() {
12599 // Check that we didn't get one last unshift.
12600 if (!state.endEmitted && state.length === 0) {
12601 state.endEmitted = true;
12602 stream.readable = false;
12603 stream.emit('end');
12604 }
12605 });
12606 }
12607}
12608
12609function forEach (xs, f) {
12610 for (var i = 0, l = xs.length; i < l; i++) {
12611 f(xs[i], i);
12612 }
12613}
12614
12615function indexOf (xs, x) {
12616 for (var i = 0, l = xs.length; i < l; i++) {
12617 if (xs[i] === x) return i;
12618 }
12619 return -1;
12620}
12621
12622}).call(this,_dereq_(71))
12623},{"10":10,"21":21,"25":25,"27":27,"71":71,"78":78,"82":82,"9":9}],76:[function(_dereq_,module,exports){
12624// Copyright Joyent, Inc. and other Node contributors.
12625//
12626// Permission is hereby granted, free of charge, to any person obtaining a
12627// copy of this software and associated documentation files (the
12628// "Software"), to deal in the Software without restriction, including
12629// without limitation the rights to use, copy, modify, merge, publish,
12630// distribute, sublicense, and/or sell copies of the Software, and to permit
12631// persons to whom the Software is furnished to do so, subject to the
12632// following conditions:
12633//
12634// The above copyright notice and this permission notice shall be included
12635// in all copies or substantial portions of the Software.
12636//
12637// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12638// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12639// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12640// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12641// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12642// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12643// USE OR OTHER DEALINGS IN THE SOFTWARE.
12644
12645
12646// a transform stream is a readable/writable stream where you do
12647// something with the data. Sometimes it's called a "filter",
12648// but that's not a great name for it, since that implies a thing where
12649// some bits pass through, and others are simply ignored. (That would
12650// be a valid example of a transform, of course.)
12651//
12652// While the output is causally related to the input, it's not a
12653// necessarily symmetric or synchronous transformation. For example,
12654// a zlib stream might take multiple plain-text writes(), and then
12655// emit a single compressed chunk some time in the future.
12656//
12657// Here's how this works:
12658//
12659// The Transform stream has all the aspects of the readable and writable
12660// stream classes. When you write(chunk), that calls _write(chunk,cb)
12661// internally, and returns false if there's a lot of pending writes
12662// buffered up. When you call read(), that calls _read(n) until
12663// there's enough pending readable data buffered up.
12664//
12665// In a transform stream, the written data is placed in a buffer. When
12666// _read(n) is called, it transforms the queued up data, calling the
12667// buffered _write cb's as it consumes chunks. If consuming a single
12668// written chunk would result in multiple output chunks, then the first
12669// outputted bit calls the readcb, and subsequent chunks just go into
12670// the read buffer, and will cause it to emit 'readable' if necessary.
12671//
12672// This way, back-pressure is actually determined by the reading side,
12673// since _read has to be called to start processing a new chunk. However,
12674// a pathological inflate type of transform can cause excessive buffering
12675// here. For example, imagine a stream where every byte of input is
12676// interpreted as an integer from 0-255, and then results in that many
12677// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12678// 1kb of data being output. In this case, you could write a very small
12679// amount of input, and end up with a very large amount of output. In
12680// such a pathological inflating mechanism, there'd be no way to tell
12681// the system to stop doing the transform. A single 4MB write could
12682// cause the system to run out of memory.
12683//
12684// However, even in such a pathological case, only a single written chunk
12685// would be consumed, and then the rest would wait (un-transformed) until
12686// the results of the previous transformed chunk were consumed.
12687
12688module.exports = Transform;
12689
12690var Duplex = _dereq_(73);
12691
12692/*<replacement>*/
12693var util = _dereq_(10);
12694util.inherits = _dereq_(25);
12695/*</replacement>*/
12696
12697util.inherits(Transform, Duplex);
12698
12699
12700function TransformState(options, stream) {
12701 this.afterTransform = function(er, data) {
12702 return afterTransform(stream, er, data);
12703 };
12704
12705 this.needTransform = false;
12706 this.transforming = false;
12707 this.writecb = null;
12708 this.writechunk = null;
12709}
12710
12711function afterTransform(stream, er, data) {
12712 var ts = stream._transformState;
12713 ts.transforming = false;
12714
12715 var cb = ts.writecb;
12716
12717 if (!cb)
12718 return stream.emit('error', new Error('no writecb in Transform class'));
12719
12720 ts.writechunk = null;
12721 ts.writecb = null;
12722
12723 if (data !== null && data !== undefined)
12724 stream.push(data);
12725
12726 if (cb)
12727 cb(er);
12728
12729 var rs = stream._readableState;
12730 rs.reading = false;
12731 if (rs.needReadable || rs.length < rs.highWaterMark) {
12732 stream._read(rs.highWaterMark);
12733 }
12734}
12735
12736
12737function Transform(options) {
12738 if (!(this instanceof Transform))
12739 return new Transform(options);
12740
12741 Duplex.call(this, options);
12742
12743 var ts = this._transformState = new TransformState(options, this);
12744
12745 // when the writable side finishes, then flush out anything remaining.
12746 var stream = this;
12747
12748 // start out asking for a readable event once data is transformed.
12749 this._readableState.needReadable = true;
12750
12751 // we have implemented the _read method, and done the other things
12752 // that Readable wants before the first _read call, so unset the
12753 // sync guard flag.
12754 this._readableState.sync = false;
12755
12756 this.once('finish', function() {
12757 if ('function' === typeof this._flush)
12758 this._flush(function(er) {
12759 done(stream, er);
12760 });
12761 else
12762 done(stream);
12763 });
12764}
12765
12766Transform.prototype.push = function(chunk, encoding) {
12767 this._transformState.needTransform = false;
12768 return Duplex.prototype.push.call(this, chunk, encoding);
12769};
12770
12771// This is the part where you do stuff!
12772// override this function in implementation classes.
12773// 'chunk' is an input chunk.
12774//
12775// Call `push(newChunk)` to pass along transformed output
12776// to the readable side. You may call 'push' zero or more times.
12777//
12778// Call `cb(err)` when you are done with this chunk. If you pass
12779// an error, then that'll put the hurt on the whole operation. If you
12780// never call cb(), then you'll never get another chunk.
12781Transform.prototype._transform = function(chunk, encoding, cb) {
12782 throw new Error('not implemented');
12783};
12784
12785Transform.prototype._write = function(chunk, encoding, cb) {
12786 var ts = this._transformState;
12787 ts.writecb = cb;
12788 ts.writechunk = chunk;
12789 ts.writeencoding = encoding;
12790 if (!ts.transforming) {
12791 var rs = this._readableState;
12792 if (ts.needTransform ||
12793 rs.needReadable ||
12794 rs.length < rs.highWaterMark)
12795 this._read(rs.highWaterMark);
12796 }
12797};
12798
12799// Doesn't matter what the args are here.
12800// _transform does all the work.
12801// That we got here means that the readable side wants more data.
12802Transform.prototype._read = function(n) {
12803 var ts = this._transformState;
12804
12805 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
12806 ts.transforming = true;
12807 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12808 } else {
12809 // mark that we need a transform, so that any data that comes in
12810 // will get processed, now that we've asked for it.
12811 ts.needTransform = true;
12812 }
12813};
12814
12815
12816function done(stream, er) {
12817 if (er)
12818 return stream.emit('error', er);
12819
12820 // if there's nothing in the write buffer, then that means
12821 // that nothing more will ever be provided
12822 var ws = stream._writableState;
12823 var rs = stream._readableState;
12824 var ts = stream._transformState;
12825
12826 if (ws.length)
12827 throw new Error('calling transform done when ws.length != 0');
12828
12829 if (ts.transforming)
12830 throw new Error('calling transform done when still transforming');
12831
12832 return stream.push(null);
12833}
12834
12835},{"10":10,"25":25,"73":73}],77:[function(_dereq_,module,exports){
12836(function (process){
12837// Copyright Joyent, Inc. and other Node contributors.
12838//
12839// Permission is hereby granted, free of charge, to any person obtaining a
12840// copy of this software and associated documentation files (the
12841// "Software"), to deal in the Software without restriction, including
12842// without limitation the rights to use, copy, modify, merge, publish,
12843// distribute, sublicense, and/or sell copies of the Software, and to permit
12844// persons to whom the Software is furnished to do so, subject to the
12845// following conditions:
12846//
12847// The above copyright notice and this permission notice shall be included
12848// in all copies or substantial portions of the Software.
12849//
12850// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12851// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12852// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12853// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12854// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12855// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12856// USE OR OTHER DEALINGS IN THE SOFTWARE.
12857
12858// A bit simpler than readable streams.
12859// Implement an async ._write(chunk, cb), and it'll handle all
12860// the drain event emission and buffering.
12861
12862module.exports = Writable;
12863
12864/*<replacement>*/
12865var Buffer = _dereq_(9).Buffer;
12866/*</replacement>*/
12867
12868Writable.WritableState = WritableState;
12869
12870
12871/*<replacement>*/
12872var util = _dereq_(10);
12873util.inherits = _dereq_(25);
12874/*</replacement>*/
12875
12876var Stream = _dereq_(82);
12877
12878util.inherits(Writable, Stream);
12879
12880function WriteReq(chunk, encoding, cb) {
12881 this.chunk = chunk;
12882 this.encoding = encoding;
12883 this.callback = cb;
12884}
12885
12886function WritableState(options, stream) {
12887 options = options || {};
12888
12889 // the point at which write() starts returning false
12890 // Note: 0 is a valid value, means that we always return false if
12891 // the entire buffer is not flushed immediately on write()
12892 var hwm = options.highWaterMark;
12893 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
12894
12895 // object stream flag to indicate whether or not this stream
12896 // contains buffers or objects.
12897 this.objectMode = !!options.objectMode;
12898
12899 // cast to ints.
12900 this.highWaterMark = ~~this.highWaterMark;
12901
12902 this.needDrain = false;
12903 // at the start of calling end()
12904 this.ending = false;
12905 // when end() has been called, and returned
12906 this.ended = false;
12907 // when 'finish' is emitted
12908 this.finished = false;
12909
12910 // should we decode strings into buffers before passing to _write?
12911 // this is here so that some node-core streams can optimize string
12912 // handling at a lower level.
12913 var noDecode = options.decodeStrings === false;
12914 this.decodeStrings = !noDecode;
12915
12916 // Crypto is kind of old and crusty. Historically, its default string
12917 // encoding is 'binary' so we have to make this configurable.
12918 // Everything else in the universe uses 'utf8', though.
12919 this.defaultEncoding = options.defaultEncoding || 'utf8';
12920
12921 // not an actual buffer we keep track of, but a measurement
12922 // of how much we're waiting to get pushed to some underlying
12923 // socket or file.
12924 this.length = 0;
12925
12926 // a flag to see when we're in the middle of a write.
12927 this.writing = false;
12928
12929 // a flag to be able to tell if the onwrite cb is called immediately,
12930 // or on a later tick. We set this to true at first, becuase any
12931 // actions that shouldn't happen until "later" should generally also
12932 // not happen before the first write call.
12933 this.sync = true;
12934
12935 // a flag to know if we're processing previously buffered items, which
12936 // may call the _write() callback in the same tick, so that we don't
12937 // end up in an overlapped onwrite situation.
12938 this.bufferProcessing = false;
12939
12940 // the callback that's passed to _write(chunk,cb)
12941 this.onwrite = function(er) {
12942 onwrite(stream, er);
12943 };
12944
12945 // the callback that the user supplies to write(chunk,encoding,cb)
12946 this.writecb = null;
12947
12948 // the amount that is being written when _write is called.
12949 this.writelen = 0;
12950
12951 this.buffer = [];
12952
12953 // True if the error was already emitted and should not be thrown again
12954 this.errorEmitted = false;
12955}
12956
12957function Writable(options) {
12958 var Duplex = _dereq_(73);
12959
12960 // Writable ctor is applied to Duplexes, though they're not
12961 // instanceof Writable, they're instanceof Readable.
12962 if (!(this instanceof Writable) && !(this instanceof Duplex))
12963 return new Writable(options);
12964
12965 this._writableState = new WritableState(options, this);
12966
12967 // legacy.
12968 this.writable = true;
12969
12970 Stream.call(this);
12971}
12972
12973// Otherwise people can pipe Writable streams, which is just wrong.
12974Writable.prototype.pipe = function() {
12975 this.emit('error', new Error('Cannot pipe. Not readable.'));
12976};
12977
12978
12979function writeAfterEnd(stream, state, cb) {
12980 var er = new Error('write after end');
12981 // TODO: defer error events consistently everywhere, not just the cb
12982 stream.emit('error', er);
12983 process.nextTick(function() {
12984 cb(er);
12985 });
12986}
12987
12988// If we get something that is not a buffer, string, null, or undefined,
12989// and we're not in objectMode, then that's an error.
12990// Otherwise stream chunks are all considered to be of length=1, and the
12991// watermarks determine how many objects to keep in the buffer, rather than
12992// how many bytes or characters.
12993function validChunk(stream, state, chunk, cb) {
12994 var valid = true;
12995 if (!Buffer.isBuffer(chunk) &&
12996 'string' !== typeof chunk &&
12997 chunk !== null &&
12998 chunk !== undefined &&
12999 !state.objectMode) {
13000 var er = new TypeError('Invalid non-string/buffer chunk');
13001 stream.emit('error', er);
13002 process.nextTick(function() {
13003 cb(er);
13004 });
13005 valid = false;
13006 }
13007 return valid;
13008}
13009
13010Writable.prototype.write = function(chunk, encoding, cb) {
13011 var state = this._writableState;
13012 var ret = false;
13013
13014 if (typeof encoding === 'function') {
13015 cb = encoding;
13016 encoding = null;
13017 }
13018
13019 if (Buffer.isBuffer(chunk))
13020 encoding = 'buffer';
13021 else if (!encoding)
13022 encoding = state.defaultEncoding;
13023
13024 if (typeof cb !== 'function')
13025 cb = function() {};
13026
13027 if (state.ended)
13028 writeAfterEnd(this, state, cb);
13029 else if (validChunk(this, state, chunk, cb))
13030 ret = writeOrBuffer(this, state, chunk, encoding, cb);
13031
13032 return ret;
13033};
13034
13035function decodeChunk(state, chunk, encoding) {
13036 if (!state.objectMode &&
13037 state.decodeStrings !== false &&
13038 typeof chunk === 'string') {
13039 chunk = new Buffer(chunk, encoding);
13040 }
13041 return chunk;
13042}
13043
13044// if we're already writing something, then just put this
13045// in the queue, and wait our turn. Otherwise, call _write
13046// If we return false, then we need a drain event, so set that flag.
13047function writeOrBuffer(stream, state, chunk, encoding, cb) {
13048 chunk = decodeChunk(state, chunk, encoding);
13049 if (Buffer.isBuffer(chunk))
13050 encoding = 'buffer';
13051 var len = state.objectMode ? 1 : chunk.length;
13052
13053 state.length += len;
13054
13055 var ret = state.length < state.highWaterMark;
13056 // we must ensure that previous needDrain will not be reset to false.
13057 if (!ret)
13058 state.needDrain = true;
13059
13060 if (state.writing)
13061 state.buffer.push(new WriteReq(chunk, encoding, cb));
13062 else
13063 doWrite(stream, state, len, chunk, encoding, cb);
13064
13065 return ret;
13066}
13067
13068function doWrite(stream, state, len, chunk, encoding, cb) {
13069 state.writelen = len;
13070 state.writecb = cb;
13071 state.writing = true;
13072 state.sync = true;
13073 stream._write(chunk, encoding, state.onwrite);
13074 state.sync = false;
13075}
13076
13077function onwriteError(stream, state, sync, er, cb) {
13078 if (sync)
13079 process.nextTick(function() {
13080 cb(er);
13081 });
13082 else
13083 cb(er);
13084
13085 stream._writableState.errorEmitted = true;
13086 stream.emit('error', er);
13087}
13088
13089function onwriteStateUpdate(state) {
13090 state.writing = false;
13091 state.writecb = null;
13092 state.length -= state.writelen;
13093 state.writelen = 0;
13094}
13095
13096function onwrite(stream, er) {
13097 var state = stream._writableState;
13098 var sync = state.sync;
13099 var cb = state.writecb;
13100
13101 onwriteStateUpdate(state);
13102
13103 if (er)
13104 onwriteError(stream, state, sync, er, cb);
13105 else {
13106 // Check if we're actually ready to finish, but don't emit yet
13107 var finished = needFinish(stream, state);
13108
13109 if (!finished && !state.bufferProcessing && state.buffer.length)
13110 clearBuffer(stream, state);
13111
13112 if (sync) {
13113 process.nextTick(function() {
13114 afterWrite(stream, state, finished, cb);
13115 });
13116 } else {
13117 afterWrite(stream, state, finished, cb);
13118 }
13119 }
13120}
13121
13122function afterWrite(stream, state, finished, cb) {
13123 if (!finished)
13124 onwriteDrain(stream, state);
13125 cb();
13126 if (finished)
13127 finishMaybe(stream, state);
13128}
13129
13130// Must force callback to be called on nextTick, so that we don't
13131// emit 'drain' before the write() consumer gets the 'false' return
13132// value, and has a chance to attach a 'drain' listener.
13133function onwriteDrain(stream, state) {
13134 if (state.length === 0 && state.needDrain) {
13135 state.needDrain = false;
13136 stream.emit('drain');
13137 }
13138}
13139
13140
13141// if there's something in the buffer waiting, then process it
13142function clearBuffer(stream, state) {
13143 state.bufferProcessing = true;
13144
13145 for (var c = 0; c < state.buffer.length; c++) {
13146 var entry = state.buffer[c];
13147 var chunk = entry.chunk;
13148 var encoding = entry.encoding;
13149 var cb = entry.callback;
13150 var len = state.objectMode ? 1 : chunk.length;
13151
13152 doWrite(stream, state, len, chunk, encoding, cb);
13153
13154 // if we didn't call the onwrite immediately, then
13155 // it means that we need to wait until it does.
13156 // also, that means that the chunk and cb are currently
13157 // being processed, so move the buffer counter past them.
13158 if (state.writing) {
13159 c++;
13160 break;
13161 }
13162 }
13163
13164 state.bufferProcessing = false;
13165 if (c < state.buffer.length)
13166 state.buffer = state.buffer.slice(c);
13167 else
13168 state.buffer.length = 0;
13169}
13170
13171Writable.prototype._write = function(chunk, encoding, cb) {
13172 cb(new Error('not implemented'));
13173};
13174
13175Writable.prototype.end = function(chunk, encoding, cb) {
13176 var state = this._writableState;
13177
13178 if (typeof chunk === 'function') {
13179 cb = chunk;
13180 chunk = null;
13181 encoding = null;
13182 } else if (typeof encoding === 'function') {
13183 cb = encoding;
13184 encoding = null;
13185 }
13186
13187 if (typeof chunk !== 'undefined' && chunk !== null)
13188 this.write(chunk, encoding);
13189
13190 // ignore unnecessary end() calls.
13191 if (!state.ending && !state.finished)
13192 endWritable(this, state, cb);
13193};
13194
13195
13196function needFinish(stream, state) {
13197 return (state.ending &&
13198 state.length === 0 &&
13199 !state.finished &&
13200 !state.writing);
13201}
13202
13203function finishMaybe(stream, state) {
13204 var need = needFinish(stream, state);
13205 if (need) {
13206 state.finished = true;
13207 stream.emit('finish');
13208 }
13209 return need;
13210}
13211
13212function endWritable(stream, state, cb) {
13213 state.ending = true;
13214 finishMaybe(stream, state);
13215 if (cb) {
13216 if (state.finished)
13217 process.nextTick(cb);
13218 else
13219 stream.once('finish', cb);
13220 }
13221 state.ended = true;
13222}
13223
13224}).call(this,_dereq_(71))
13225},{"10":10,"25":25,"71":71,"73":73,"82":82,"9":9}],78:[function(_dereq_,module,exports){
13226// Copyright Joyent, Inc. and other Node contributors.
13227//
13228// Permission is hereby granted, free of charge, to any person obtaining a
13229// copy of this software and associated documentation files (the
13230// "Software"), to deal in the Software without restriction, including
13231// without limitation the rights to use, copy, modify, merge, publish,
13232// distribute, sublicense, and/or sell copies of the Software, and to permit
13233// persons to whom the Software is furnished to do so, subject to the
13234// following conditions:
13235//
13236// The above copyright notice and this permission notice shall be included
13237// in all copies or substantial portions of the Software.
13238//
13239// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13240// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13241// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13242// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13243// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13244// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13245// USE OR OTHER DEALINGS IN THE SOFTWARE.
13246
13247var Buffer = _dereq_(9).Buffer;
13248
13249var isBufferEncoding = Buffer.isEncoding
13250 || function(encoding) {
13251 switch (encoding && encoding.toLowerCase()) {
13252 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;
13253 default: return false;
13254 }
13255 }
13256
13257
13258function assertEncoding(encoding) {
13259 if (encoding && !isBufferEncoding(encoding)) {
13260 throw new Error('Unknown encoding: ' + encoding);
13261 }
13262}
13263
13264// StringDecoder provides an interface for efficiently splitting a series of
13265// buffers into a series of JS strings without breaking apart multi-byte
13266// characters. CESU-8 is handled as part of the UTF-8 encoding.
13267//
13268// @TODO Handling all encodings inside a single object makes it very difficult
13269// to reason about this code, so it should be split up in the future.
13270// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
13271// points as used by CESU-8.
13272var StringDecoder = exports.StringDecoder = function(encoding) {
13273 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
13274 assertEncoding(encoding);
13275 switch (this.encoding) {
13276 case 'utf8':
13277 // CESU-8 represents each of Surrogate Pair by 3-bytes
13278 this.surrogateSize = 3;
13279 break;
13280 case 'ucs2':
13281 case 'utf16le':
13282 // UTF-16 represents each of Surrogate Pair by 2-bytes
13283 this.surrogateSize = 2;
13284 this.detectIncompleteChar = utf16DetectIncompleteChar;
13285 break;
13286 case 'base64':
13287 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
13288 this.surrogateSize = 3;
13289 this.detectIncompleteChar = base64DetectIncompleteChar;
13290 break;
13291 default:
13292 this.write = passThroughWrite;
13293 return;
13294 }
13295
13296 // Enough space to store all bytes of a single character. UTF-8 needs 4
13297 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
13298 this.charBuffer = new Buffer(6);
13299 // Number of bytes received for the current incomplete multi-byte character.
13300 this.charReceived = 0;
13301 // Number of bytes expected for the current incomplete multi-byte character.
13302 this.charLength = 0;
13303};
13304
13305
13306// write decodes the given buffer and returns it as JS string that is
13307// guaranteed to not contain any partial multi-byte characters. Any partial
13308// character found at the end of the buffer is buffered up, and will be
13309// returned when calling write again with the remaining bytes.
13310//
13311// Note: Converting a Buffer containing an orphan surrogate to a String
13312// currently works, but converting a String to a Buffer (via `new Buffer`, or
13313// Buffer#write) will replace incomplete surrogates with the unicode
13314// replacement character. See https://codereview.chromium.org/121173009/ .
13315StringDecoder.prototype.write = function(buffer) {
13316 var charStr = '';
13317 // if our last write ended with an incomplete multibyte character
13318 while (this.charLength) {
13319 // determine how many remaining bytes this buffer has to offer for this char
13320 var available = (buffer.length >= this.charLength - this.charReceived) ?
13321 this.charLength - this.charReceived :
13322 buffer.length;
13323
13324 // add the new bytes to the char buffer
13325 buffer.copy(this.charBuffer, this.charReceived, 0, available);
13326 this.charReceived += available;
13327
13328 if (this.charReceived < this.charLength) {
13329 // still not enough chars in this buffer? wait for more ...
13330 return '';
13331 }
13332
13333 // remove bytes belonging to the current character from the buffer
13334 buffer = buffer.slice(available, buffer.length);
13335
13336 // get the character that was split
13337 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
13338
13339 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13340 var charCode = charStr.charCodeAt(charStr.length - 1);
13341 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13342 this.charLength += this.surrogateSize;
13343 charStr = '';
13344 continue;
13345 }
13346 this.charReceived = this.charLength = 0;
13347
13348 // if there are no more bytes in this buffer, just emit our char
13349 if (buffer.length === 0) {
13350 return charStr;
13351 }
13352 break;
13353 }
13354
13355 // determine and set charLength / charReceived
13356 this.detectIncompleteChar(buffer);
13357
13358 var end = buffer.length;
13359 if (this.charLength) {
13360 // buffer the incomplete character bytes we got
13361 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
13362 end -= this.charReceived;
13363 }
13364
13365 charStr += buffer.toString(this.encoding, 0, end);
13366
13367 var end = charStr.length - 1;
13368 var charCode = charStr.charCodeAt(end);
13369 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13370 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13371 var size = this.surrogateSize;
13372 this.charLength += size;
13373 this.charReceived += size;
13374 this.charBuffer.copy(this.charBuffer, size, 0, size);
13375 buffer.copy(this.charBuffer, 0, 0, size);
13376 return charStr.substring(0, end);
13377 }
13378
13379 // or just emit the charStr
13380 return charStr;
13381};
13382
13383// detectIncompleteChar determines if there is an incomplete UTF-8 character at
13384// the end of the given buffer. If so, it sets this.charLength to the byte
13385// length that character, and sets this.charReceived to the number of bytes
13386// that are available for this character.
13387StringDecoder.prototype.detectIncompleteChar = function(buffer) {
13388 // determine how many bytes we have to check at the end of this buffer
13389 var i = (buffer.length >= 3) ? 3 : buffer.length;
13390
13391 // Figure out if one of the last i bytes of our buffer announces an
13392 // incomplete char.
13393 for (; i > 0; i--) {
13394 var c = buffer[buffer.length - i];
13395
13396 // See http://en.wikipedia.org/wiki/UTF-8#Description
13397
13398 // 110XXXXX
13399 if (i == 1 && c >> 5 == 0x06) {
13400 this.charLength = 2;
13401 break;
13402 }
13403
13404 // 1110XXXX
13405 if (i <= 2 && c >> 4 == 0x0E) {
13406 this.charLength = 3;
13407 break;
13408 }
13409
13410 // 11110XXX
13411 if (i <= 3 && c >> 3 == 0x1E) {
13412 this.charLength = 4;
13413 break;
13414 }
13415 }
13416 this.charReceived = i;
13417};
13418
13419StringDecoder.prototype.end = function(buffer) {
13420 var res = '';
13421 if (buffer && buffer.length)
13422 res = this.write(buffer);
13423
13424 if (this.charReceived) {
13425 var cr = this.charReceived;
13426 var buf = this.charBuffer;
13427 var enc = this.encoding;
13428 res += buf.slice(0, cr).toString(enc);
13429 }
13430
13431 return res;
13432};
13433
13434function passThroughWrite(buffer) {
13435 return buffer.toString(this.encoding);
13436}
13437
13438function utf16DetectIncompleteChar(buffer) {
13439 this.charReceived = buffer.length % 2;
13440 this.charLength = this.charReceived ? 2 : 0;
13441}
13442
13443function base64DetectIncompleteChar(buffer) {
13444 this.charReceived = buffer.length % 3;
13445 this.charLength = this.charReceived ? 3 : 0;
13446}
13447
13448},{"9":9}],79:[function(_dereq_,module,exports){
13449var Stream = _dereq_(82); // hack to fix a circular dependency issue when used with browserify
13450exports = module.exports = _dereq_(75);
13451exports.Stream = Stream;
13452exports.Readable = exports;
13453exports.Writable = _dereq_(77);
13454exports.Duplex = _dereq_(73);
13455exports.Transform = _dereq_(76);
13456exports.PassThrough = _dereq_(74);
13457
13458},{"73":73,"74":74,"75":75,"76":76,"77":77,"82":82}],80:[function(_dereq_,module,exports){
13459/* eslint-disable node/no-deprecated-api */
13460var buffer = _dereq_(9)
13461var Buffer = buffer.Buffer
13462
13463// alternative to using Object.keys for old browsers
13464function copyProps (src, dst) {
13465 for (var key in src) {
13466 dst[key] = src[key]
13467 }
13468}
13469if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13470 module.exports = buffer
13471} else {
13472 // Copy properties from require('buffer')
13473 copyProps(buffer, exports)
13474 exports.Buffer = SafeBuffer
13475}
13476
13477function SafeBuffer (arg, encodingOrOffset, length) {
13478 return Buffer(arg, encodingOrOffset, length)
13479}
13480
13481// Copy static methods from Buffer
13482copyProps(Buffer, SafeBuffer)
13483
13484SafeBuffer.from = function (arg, encodingOrOffset, length) {
13485 if (typeof arg === 'number') {
13486 throw new TypeError('Argument must not be a number')
13487 }
13488 return Buffer(arg, encodingOrOffset, length)
13489}
13490
13491SafeBuffer.alloc = function (size, fill, encoding) {
13492 if (typeof size !== 'number') {
13493 throw new TypeError('Argument must be a number')
13494 }
13495 var buf = Buffer(size)
13496 if (fill !== undefined) {
13497 if (typeof encoding === 'string') {
13498 buf.fill(fill, encoding)
13499 } else {
13500 buf.fill(fill)
13501 }
13502 } else {
13503 buf.fill(0)
13504 }
13505 return buf
13506}
13507
13508SafeBuffer.allocUnsafe = function (size) {
13509 if (typeof size !== 'number') {
13510 throw new TypeError('Argument must be a number')
13511 }
13512 return Buffer(size)
13513}
13514
13515SafeBuffer.allocUnsafeSlow = function (size) {
13516 if (typeof size !== 'number') {
13517 throw new TypeError('Argument must be a number')
13518 }
13519 return buffer.SlowBuffer(size)
13520}
13521
13522},{"9":9}],81:[function(_dereq_,module,exports){
13523(function (factory) {
13524 if (typeof exports === 'object') {
13525 // Node/CommonJS
13526 module.exports = factory();
13527 } else if (typeof define === 'function' && define.amd) {
13528 // AMD
13529 define(factory);
13530 } else {
13531 // Browser globals (with support for web workers)
13532 var glob;
13533
13534 try {
13535 glob = window;
13536 } catch (e) {
13537 glob = self;
13538 }
13539
13540 glob.SparkMD5 = factory();
13541 }
13542}(function (undefined) {
13543
13544 'use strict';
13545
13546 /*
13547 * Fastest md5 implementation around (JKM md5).
13548 * Credits: Joseph Myers
13549 *
13550 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
13551 * @see http://jsperf.com/md5-shootout/7
13552 */
13553
13554 /* this function is much faster,
13555 so if possible we use it. Some IEs
13556 are the only ones I know of that
13557 need the idiotic second function,
13558 generated by an if clause. */
13559 var add32 = function (a, b) {
13560 return (a + b) & 0xFFFFFFFF;
13561 },
13562 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
13563
13564
13565 function cmn(q, a, b, x, s, t) {
13566 a = add32(add32(a, q), add32(x, t));
13567 return add32((a << s) | (a >>> (32 - s)), b);
13568 }
13569
13570 function md5cycle(x, k) {
13571 var a = x[0],
13572 b = x[1],
13573 c = x[2],
13574 d = x[3];
13575
13576 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
13577 a = (a << 7 | a >>> 25) + b | 0;
13578 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
13579 d = (d << 12 | d >>> 20) + a | 0;
13580 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
13581 c = (c << 17 | c >>> 15) + d | 0;
13582 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
13583 b = (b << 22 | b >>> 10) + c | 0;
13584 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
13585 a = (a << 7 | a >>> 25) + b | 0;
13586 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
13587 d = (d << 12 | d >>> 20) + a | 0;
13588 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
13589 c = (c << 17 | c >>> 15) + d | 0;
13590 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
13591 b = (b << 22 | b >>> 10) + c | 0;
13592 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
13593 a = (a << 7 | a >>> 25) + b | 0;
13594 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
13595 d = (d << 12 | d >>> 20) + a | 0;
13596 c += (d & a | ~d & b) + k[10] - 42063 | 0;
13597 c = (c << 17 | c >>> 15) + d | 0;
13598 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
13599 b = (b << 22 | b >>> 10) + c | 0;
13600 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
13601 a = (a << 7 | a >>> 25) + b | 0;
13602 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
13603 d = (d << 12 | d >>> 20) + a | 0;
13604 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
13605 c = (c << 17 | c >>> 15) + d | 0;
13606 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
13607 b = (b << 22 | b >>> 10) + c | 0;
13608
13609 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
13610 a = (a << 5 | a >>> 27) + b | 0;
13611 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
13612 d = (d << 9 | d >>> 23) + a | 0;
13613 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
13614 c = (c << 14 | c >>> 18) + d | 0;
13615 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
13616 b = (b << 20 | b >>> 12) + c | 0;
13617 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
13618 a = (a << 5 | a >>> 27) + b | 0;
13619 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
13620 d = (d << 9 | d >>> 23) + a | 0;
13621 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
13622 c = (c << 14 | c >>> 18) + d | 0;
13623 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
13624 b = (b << 20 | b >>> 12) + c | 0;
13625 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
13626 a = (a << 5 | a >>> 27) + b | 0;
13627 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
13628 d = (d << 9 | d >>> 23) + a | 0;
13629 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
13630 c = (c << 14 | c >>> 18) + d | 0;
13631 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
13632 b = (b << 20 | b >>> 12) + c | 0;
13633 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
13634 a = (a << 5 | a >>> 27) + b | 0;
13635 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
13636 d = (d << 9 | d >>> 23) + a | 0;
13637 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
13638 c = (c << 14 | c >>> 18) + d | 0;
13639 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
13640 b = (b << 20 | b >>> 12) + c | 0;
13641
13642 a += (b ^ c ^ d) + k[5] - 378558 | 0;
13643 a = (a << 4 | a >>> 28) + b | 0;
13644 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
13645 d = (d << 11 | d >>> 21) + a | 0;
13646 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
13647 c = (c << 16 | c >>> 16) + d | 0;
13648 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
13649 b = (b << 23 | b >>> 9) + c | 0;
13650 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
13651 a = (a << 4 | a >>> 28) + b | 0;
13652 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
13653 d = (d << 11 | d >>> 21) + a | 0;
13654 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
13655 c = (c << 16 | c >>> 16) + d | 0;
13656 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
13657 b = (b << 23 | b >>> 9) + c | 0;
13658 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
13659 a = (a << 4 | a >>> 28) + b | 0;
13660 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
13661 d = (d << 11 | d >>> 21) + a | 0;
13662 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
13663 c = (c << 16 | c >>> 16) + d | 0;
13664 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
13665 b = (b << 23 | b >>> 9) + c | 0;
13666 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
13667 a = (a << 4 | a >>> 28) + b | 0;
13668 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
13669 d = (d << 11 | d >>> 21) + a | 0;
13670 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
13671 c = (c << 16 | c >>> 16) + d | 0;
13672 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
13673 b = (b << 23 | b >>> 9) + c | 0;
13674
13675 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
13676 a = (a << 6 | a >>> 26) + b | 0;
13677 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
13678 d = (d << 10 | d >>> 22) + a | 0;
13679 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
13680 c = (c << 15 | c >>> 17) + d | 0;
13681 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
13682 b = (b << 21 |b >>> 11) + c | 0;
13683 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
13684 a = (a << 6 | a >>> 26) + b | 0;
13685 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
13686 d = (d << 10 | d >>> 22) + a | 0;
13687 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
13688 c = (c << 15 | c >>> 17) + d | 0;
13689 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
13690 b = (b << 21 |b >>> 11) + c | 0;
13691 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
13692 a = (a << 6 | a >>> 26) + b | 0;
13693 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
13694 d = (d << 10 | d >>> 22) + a | 0;
13695 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
13696 c = (c << 15 | c >>> 17) + d | 0;
13697 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
13698 b = (b << 21 |b >>> 11) + c | 0;
13699 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
13700 a = (a << 6 | a >>> 26) + b | 0;
13701 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
13702 d = (d << 10 | d >>> 22) + a | 0;
13703 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
13704 c = (c << 15 | c >>> 17) + d | 0;
13705 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
13706 b = (b << 21 | b >>> 11) + c | 0;
13707
13708 x[0] = a + x[0] | 0;
13709 x[1] = b + x[1] | 0;
13710 x[2] = c + x[2] | 0;
13711 x[3] = d + x[3] | 0;
13712 }
13713
13714 function md5blk(s) {
13715 var md5blks = [],
13716 i; /* Andy King said do it this way. */
13717
13718 for (i = 0; i < 64; i += 4) {
13719 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
13720 }
13721 return md5blks;
13722 }
13723
13724 function md5blk_array(a) {
13725 var md5blks = [],
13726 i; /* Andy King said do it this way. */
13727
13728 for (i = 0; i < 64; i += 4) {
13729 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13730 }
13731 return md5blks;
13732 }
13733
13734 function md51(s) {
13735 var n = s.length,
13736 state = [1732584193, -271733879, -1732584194, 271733878],
13737 i,
13738 length,
13739 tail,
13740 tmp,
13741 lo,
13742 hi;
13743
13744 for (i = 64; i <= n; i += 64) {
13745 md5cycle(state, md5blk(s.substring(i - 64, i)));
13746 }
13747 s = s.substring(i - 64);
13748 length = s.length;
13749 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13750 for (i = 0; i < length; i += 1) {
13751 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13752 }
13753 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13754 if (i > 55) {
13755 md5cycle(state, tail);
13756 for (i = 0; i < 16; i += 1) {
13757 tail[i] = 0;
13758 }
13759 }
13760
13761 // Beware that the final length might not fit in 32 bits so we take care of that
13762 tmp = n * 8;
13763 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13764 lo = parseInt(tmp[2], 16);
13765 hi = parseInt(tmp[1], 16) || 0;
13766
13767 tail[14] = lo;
13768 tail[15] = hi;
13769
13770 md5cycle(state, tail);
13771 return state;
13772 }
13773
13774 function md51_array(a) {
13775 var n = a.length,
13776 state = [1732584193, -271733879, -1732584194, 271733878],
13777 i,
13778 length,
13779 tail,
13780 tmp,
13781 lo,
13782 hi;
13783
13784 for (i = 64; i <= n; i += 64) {
13785 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13786 }
13787
13788 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13789 // containing the last element of the parent array if the sub array specified starts
13790 // beyond the length of the parent array - weird.
13791 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13792 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13793
13794 length = a.length;
13795 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13796 for (i = 0; i < length; i += 1) {
13797 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13798 }
13799
13800 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13801 if (i > 55) {
13802 md5cycle(state, tail);
13803 for (i = 0; i < 16; i += 1) {
13804 tail[i] = 0;
13805 }
13806 }
13807
13808 // Beware that the final length might not fit in 32 bits so we take care of that
13809 tmp = n * 8;
13810 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13811 lo = parseInt(tmp[2], 16);
13812 hi = parseInt(tmp[1], 16) || 0;
13813
13814 tail[14] = lo;
13815 tail[15] = hi;
13816
13817 md5cycle(state, tail);
13818
13819 return state;
13820 }
13821
13822 function rhex(n) {
13823 var s = '',
13824 j;
13825 for (j = 0; j < 4; j += 1) {
13826 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
13827 }
13828 return s;
13829 }
13830
13831 function hex(x) {
13832 var i;
13833 for (i = 0; i < x.length; i += 1) {
13834 x[i] = rhex(x[i]);
13835 }
13836 return x.join('');
13837 }
13838
13839 // In some cases the fast add32 function cannot be used..
13840 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
13841 add32 = function (x, y) {
13842 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
13843 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
13844 return (msw << 16) | (lsw & 0xFFFF);
13845 };
13846 }
13847
13848 // ---------------------------------------------------
13849
13850 /**
13851 * ArrayBuffer slice polyfill.
13852 *
13853 * @see https://github.com/ttaubert/node-arraybuffer-slice
13854 */
13855
13856 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
13857 (function () {
13858 function clamp(val, length) {
13859 val = (val | 0) || 0;
13860
13861 if (val < 0) {
13862 return Math.max(val + length, 0);
13863 }
13864
13865 return Math.min(val, length);
13866 }
13867
13868 ArrayBuffer.prototype.slice = function (from, to) {
13869 var length = this.byteLength,
13870 begin = clamp(from, length),
13871 end = length,
13872 num,
13873 target,
13874 targetArray,
13875 sourceArray;
13876
13877 if (to !== undefined) {
13878 end = clamp(to, length);
13879 }
13880
13881 if (begin > end) {
13882 return new ArrayBuffer(0);
13883 }
13884
13885 num = end - begin;
13886 target = new ArrayBuffer(num);
13887 targetArray = new Uint8Array(target);
13888
13889 sourceArray = new Uint8Array(this, begin, num);
13890 targetArray.set(sourceArray);
13891
13892 return target;
13893 };
13894 })();
13895 }
13896
13897 // ---------------------------------------------------
13898
13899 /**
13900 * Helpers.
13901 */
13902
13903 function toUtf8(str) {
13904 if (/[\u0080-\uFFFF]/.test(str)) {
13905 str = unescape(encodeURIComponent(str));
13906 }
13907
13908 return str;
13909 }
13910
13911 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
13912 var length = str.length,
13913 buff = new ArrayBuffer(length),
13914 arr = new Uint8Array(buff),
13915 i;
13916
13917 for (i = 0; i < length; i += 1) {
13918 arr[i] = str.charCodeAt(i);
13919 }
13920
13921 return returnUInt8Array ? arr : buff;
13922 }
13923
13924 function arrayBuffer2Utf8Str(buff) {
13925 return String.fromCharCode.apply(null, new Uint8Array(buff));
13926 }
13927
13928 function concatenateArrayBuffers(first, second, returnUInt8Array) {
13929 var result = new Uint8Array(first.byteLength + second.byteLength);
13930
13931 result.set(new Uint8Array(first));
13932 result.set(new Uint8Array(second), first.byteLength);
13933
13934 return returnUInt8Array ? result : result.buffer;
13935 }
13936
13937 function hexToBinaryString(hex) {
13938 var bytes = [],
13939 length = hex.length,
13940 x;
13941
13942 for (x = 0; x < length - 1; x += 2) {
13943 bytes.push(parseInt(hex.substr(x, 2), 16));
13944 }
13945
13946 return String.fromCharCode.apply(String, bytes);
13947 }
13948
13949 // ---------------------------------------------------
13950
13951 /**
13952 * SparkMD5 OOP implementation.
13953 *
13954 * Use this class to perform an incremental md5, otherwise use the
13955 * static methods instead.
13956 */
13957
13958 function SparkMD5() {
13959 // call reset to init the instance
13960 this.reset();
13961 }
13962
13963 /**
13964 * Appends a string.
13965 * A conversion will be applied if an utf8 string is detected.
13966 *
13967 * @param {String} str The string to be appended
13968 *
13969 * @return {SparkMD5} The instance itself
13970 */
13971 SparkMD5.prototype.append = function (str) {
13972 // Converts the string to utf8 bytes if necessary
13973 // Then append as binary
13974 this.appendBinary(toUtf8(str));
13975
13976 return this;
13977 };
13978
13979 /**
13980 * Appends a binary string.
13981 *
13982 * @param {String} contents The binary string to be appended
13983 *
13984 * @return {SparkMD5} The instance itself
13985 */
13986 SparkMD5.prototype.appendBinary = function (contents) {
13987 this._buff += contents;
13988 this._length += contents.length;
13989
13990 var length = this._buff.length,
13991 i;
13992
13993 for (i = 64; i <= length; i += 64) {
13994 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
13995 }
13996
13997 this._buff = this._buff.substring(i - 64);
13998
13999 return this;
14000 };
14001
14002 /**
14003 * Finishes the incremental computation, reseting the internal state and
14004 * returning the result.
14005 *
14006 * @param {Boolean} raw True to get the raw string, false to get the hex string
14007 *
14008 * @return {String} The result
14009 */
14010 SparkMD5.prototype.end = function (raw) {
14011 var buff = this._buff,
14012 length = buff.length,
14013 i,
14014 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14015 ret;
14016
14017 for (i = 0; i < length; i += 1) {
14018 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
14019 }
14020
14021 this._finish(tail, length);
14022 ret = hex(this._hash);
14023
14024 if (raw) {
14025 ret = hexToBinaryString(ret);
14026 }
14027
14028 this.reset();
14029
14030 return ret;
14031 };
14032
14033 /**
14034 * Resets the internal state of the computation.
14035 *
14036 * @return {SparkMD5} The instance itself
14037 */
14038 SparkMD5.prototype.reset = function () {
14039 this._buff = '';
14040 this._length = 0;
14041 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14042
14043 return this;
14044 };
14045
14046 /**
14047 * Gets the internal state of the computation.
14048 *
14049 * @return {Object} The state
14050 */
14051 SparkMD5.prototype.getState = function () {
14052 return {
14053 buff: this._buff,
14054 length: this._length,
14055 hash: this._hash
14056 };
14057 };
14058
14059 /**
14060 * Gets the internal state of the computation.
14061 *
14062 * @param {Object} state The state
14063 *
14064 * @return {SparkMD5} The instance itself
14065 */
14066 SparkMD5.prototype.setState = function (state) {
14067 this._buff = state.buff;
14068 this._length = state.length;
14069 this._hash = state.hash;
14070
14071 return this;
14072 };
14073
14074 /**
14075 * Releases memory used by the incremental buffer and other additional
14076 * resources. If you plan to use the instance again, use reset instead.
14077 */
14078 SparkMD5.prototype.destroy = function () {
14079 delete this._hash;
14080 delete this._buff;
14081 delete this._length;
14082 };
14083
14084 /**
14085 * Finish the final calculation based on the tail.
14086 *
14087 * @param {Array} tail The tail (will be modified)
14088 * @param {Number} length The length of the remaining buffer
14089 */
14090 SparkMD5.prototype._finish = function (tail, length) {
14091 var i = length,
14092 tmp,
14093 lo,
14094 hi;
14095
14096 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
14097 if (i > 55) {
14098 md5cycle(this._hash, tail);
14099 for (i = 0; i < 16; i += 1) {
14100 tail[i] = 0;
14101 }
14102 }
14103
14104 // Do the final computation based on the tail and length
14105 // Beware that the final length may not fit in 32 bits so we take care of that
14106 tmp = this._length * 8;
14107 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
14108 lo = parseInt(tmp[2], 16);
14109 hi = parseInt(tmp[1], 16) || 0;
14110
14111 tail[14] = lo;
14112 tail[15] = hi;
14113 md5cycle(this._hash, tail);
14114 };
14115
14116 /**
14117 * Performs the md5 hash on a string.
14118 * A conversion will be applied if utf8 string is detected.
14119 *
14120 * @param {String} str The string
14121 * @param {Boolean} raw True to get the raw string, false to get the hex string
14122 *
14123 * @return {String} The result
14124 */
14125 SparkMD5.hash = function (str, raw) {
14126 // Converts the string to utf8 bytes if necessary
14127 // Then compute it using the binary function
14128 return SparkMD5.hashBinary(toUtf8(str), raw);
14129 };
14130
14131 /**
14132 * Performs the md5 hash on a binary string.
14133 *
14134 * @param {String} content The binary string
14135 * @param {Boolean} raw True to get the raw string, false to get the hex string
14136 *
14137 * @return {String} The result
14138 */
14139 SparkMD5.hashBinary = function (content, raw) {
14140 var hash = md51(content),
14141 ret = hex(hash);
14142
14143 return raw ? hexToBinaryString(ret) : ret;
14144 };
14145
14146 // ---------------------------------------------------
14147
14148 /**
14149 * SparkMD5 OOP implementation for array buffers.
14150 *
14151 * Use this class to perform an incremental md5 ONLY for array buffers.
14152 */
14153 SparkMD5.ArrayBuffer = function () {
14154 // call reset to init the instance
14155 this.reset();
14156 };
14157
14158 /**
14159 * Appends an array buffer.
14160 *
14161 * @param {ArrayBuffer} arr The array to be appended
14162 *
14163 * @return {SparkMD5.ArrayBuffer} The instance itself
14164 */
14165 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
14166 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
14167 length = buff.length,
14168 i;
14169
14170 this._length += arr.byteLength;
14171
14172 for (i = 64; i <= length; i += 64) {
14173 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
14174 }
14175
14176 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
14177
14178 return this;
14179 };
14180
14181 /**
14182 * Finishes the incremental computation, reseting the internal state and
14183 * returning the result.
14184 *
14185 * @param {Boolean} raw True to get the raw string, false to get the hex string
14186 *
14187 * @return {String} The result
14188 */
14189 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
14190 var buff = this._buff,
14191 length = buff.length,
14192 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14193 i,
14194 ret;
14195
14196 for (i = 0; i < length; i += 1) {
14197 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
14198 }
14199
14200 this._finish(tail, length);
14201 ret = hex(this._hash);
14202
14203 if (raw) {
14204 ret = hexToBinaryString(ret);
14205 }
14206
14207 this.reset();
14208
14209 return ret;
14210 };
14211
14212 /**
14213 * Resets the internal state of the computation.
14214 *
14215 * @return {SparkMD5.ArrayBuffer} The instance itself
14216 */
14217 SparkMD5.ArrayBuffer.prototype.reset = function () {
14218 this._buff = new Uint8Array(0);
14219 this._length = 0;
14220 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14221
14222 return this;
14223 };
14224
14225 /**
14226 * Gets the internal state of the computation.
14227 *
14228 * @return {Object} The state
14229 */
14230 SparkMD5.ArrayBuffer.prototype.getState = function () {
14231 var state = SparkMD5.prototype.getState.call(this);
14232
14233 // Convert buffer to a string
14234 state.buff = arrayBuffer2Utf8Str(state.buff);
14235
14236 return state;
14237 };
14238
14239 /**
14240 * Gets the internal state of the computation.
14241 *
14242 * @param {Object} state The state
14243 *
14244 * @return {SparkMD5.ArrayBuffer} The instance itself
14245 */
14246 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
14247 // Convert string to buffer
14248 state.buff = utf8Str2ArrayBuffer(state.buff, true);
14249
14250 return SparkMD5.prototype.setState.call(this, state);
14251 };
14252
14253 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
14254
14255 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
14256
14257 /**
14258 * Performs the md5 hash on an array buffer.
14259 *
14260 * @param {ArrayBuffer} arr The array buffer
14261 * @param {Boolean} raw True to get the raw string, false to get the hex one
14262 *
14263 * @return {String} The result
14264 */
14265 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
14266 var hash = md51_array(new Uint8Array(arr)),
14267 ret = hex(hash);
14268
14269 return raw ? hexToBinaryString(ret) : ret;
14270 };
14271
14272 return SparkMD5;
14273}));
14274
14275},{}],82:[function(_dereq_,module,exports){
14276// Copyright Joyent, Inc. and other Node contributors.
14277//
14278// Permission is hereby granted, free of charge, to any person obtaining a
14279// copy of this software and associated documentation files (the
14280// "Software"), to deal in the Software without restriction, including
14281// without limitation the rights to use, copy, modify, merge, publish,
14282// distribute, sublicense, and/or sell copies of the Software, and to permit
14283// persons to whom the Software is furnished to do so, subject to the
14284// following conditions:
14285//
14286// The above copyright notice and this permission notice shall be included
14287// in all copies or substantial portions of the Software.
14288//
14289// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14290// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14291// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14292// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14293// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14294// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14295// USE OR OTHER DEALINGS IN THE SOFTWARE.
14296
14297module.exports = Stream;
14298
14299var EE = _dereq_(21).EventEmitter;
14300var inherits = _dereq_(25);
14301
14302inherits(Stream, EE);
14303Stream.Readable = _dereq_(94);
14304Stream.Writable = _dereq_(96);
14305Stream.Duplex = _dereq_(84);
14306Stream.Transform = _dereq_(95);
14307Stream.PassThrough = _dereq_(93);
14308
14309// Backwards-compat with node 0.4.x
14310Stream.Stream = Stream;
14311
14312
14313
14314// old-style streams. Note that the pipe method (the only relevant
14315// part of this class) is overridden in the Readable class.
14316
14317function Stream() {
14318 EE.call(this);
14319}
14320
14321Stream.prototype.pipe = function(dest, options) {
14322 var source = this;
14323
14324 function ondata(chunk) {
14325 if (dest.writable) {
14326 if (false === dest.write(chunk) && source.pause) {
14327 source.pause();
14328 }
14329 }
14330 }
14331
14332 source.on('data', ondata);
14333
14334 function ondrain() {
14335 if (source.readable && source.resume) {
14336 source.resume();
14337 }
14338 }
14339
14340 dest.on('drain', ondrain);
14341
14342 // If the 'end' option is not supplied, dest.end() will be called when
14343 // source gets the 'end' or 'close' events. Only dest.end() once.
14344 if (!dest._isStdio && (!options || options.end !== false)) {
14345 source.on('end', onend);
14346 source.on('close', onclose);
14347 }
14348
14349 var didOnEnd = false;
14350 function onend() {
14351 if (didOnEnd) return;
14352 didOnEnd = true;
14353
14354 dest.end();
14355 }
14356
14357
14358 function onclose() {
14359 if (didOnEnd) return;
14360 didOnEnd = true;
14361
14362 if (typeof dest.destroy === 'function') dest.destroy();
14363 }
14364
14365 // don't leave dangling pipes when there are errors.
14366 function onerror(er) {
14367 cleanup();
14368 if (EE.listenerCount(this, 'error') === 0) {
14369 throw er; // Unhandled stream error in pipe.
14370 }
14371 }
14372
14373 source.on('error', onerror);
14374 dest.on('error', onerror);
14375
14376 // remove all the event listeners that were added.
14377 function cleanup() {
14378 source.removeListener('data', ondata);
14379 dest.removeListener('drain', ondrain);
14380
14381 source.removeListener('end', onend);
14382 source.removeListener('close', onclose);
14383
14384 source.removeListener('error', onerror);
14385 dest.removeListener('error', onerror);
14386
14387 source.removeListener('end', cleanup);
14388 source.removeListener('close', cleanup);
14389
14390 dest.removeListener('close', cleanup);
14391 }
14392
14393 source.on('end', cleanup);
14394 source.on('close', cleanup);
14395
14396 dest.on('close', cleanup);
14397
14398 dest.emit('pipe', source);
14399
14400 // Allow for unix-like usage: A.pipe(B).pipe(C)
14401 return dest;
14402};
14403
14404},{"21":21,"25":25,"84":84,"93":93,"94":94,"95":95,"96":96}],83:[function(_dereq_,module,exports){
14405var toString = {}.toString;
14406
14407module.exports = Array.isArray || function (arr) {
14408 return toString.call(arr) == '[object Array]';
14409};
14410
14411},{}],84:[function(_dereq_,module,exports){
14412module.exports = _dereq_(85);
14413
14414},{"85":85}],85:[function(_dereq_,module,exports){
14415// Copyright Joyent, Inc. and other Node contributors.
14416//
14417// Permission is hereby granted, free of charge, to any person obtaining a
14418// copy of this software and associated documentation files (the
14419// "Software"), to deal in the Software without restriction, including
14420// without limitation the rights to use, copy, modify, merge, publish,
14421// distribute, sublicense, and/or sell copies of the Software, and to permit
14422// persons to whom the Software is furnished to do so, subject to the
14423// following conditions:
14424//
14425// The above copyright notice and this permission notice shall be included
14426// in all copies or substantial portions of the Software.
14427//
14428// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14429// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14430// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14431// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14432// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14433// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14434// USE OR OTHER DEALINGS IN THE SOFTWARE.
14435
14436// a duplex stream is just a stream that is both readable and writable.
14437// Since JS doesn't have multiple prototypal inheritance, this class
14438// prototypally inherits from Readable, and then parasitically from
14439// Writable.
14440
14441'use strict';
14442
14443/*<replacement>*/
14444
14445var pna = _dereq_(70);
14446/*</replacement>*/
14447
14448/*<replacement>*/
14449var objectKeys = Object.keys || function (obj) {
14450 var keys = [];
14451 for (var key in obj) {
14452 keys.push(key);
14453 }return keys;
14454};
14455/*</replacement>*/
14456
14457module.exports = Duplex;
14458
14459/*<replacement>*/
14460var util = _dereq_(10);
14461util.inherits = _dereq_(25);
14462/*</replacement>*/
14463
14464var Readable = _dereq_(87);
14465var Writable = _dereq_(89);
14466
14467util.inherits(Duplex, Readable);
14468
14469{
14470 // avoid scope creep, the keys array can then be collected
14471 var keys = objectKeys(Writable.prototype);
14472 for (var v = 0; v < keys.length; v++) {
14473 var method = keys[v];
14474 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
14475 }
14476}
14477
14478function Duplex(options) {
14479 if (!(this instanceof Duplex)) return new Duplex(options);
14480
14481 Readable.call(this, options);
14482 Writable.call(this, options);
14483
14484 if (options && options.readable === false) this.readable = false;
14485
14486 if (options && options.writable === false) this.writable = false;
14487
14488 this.allowHalfOpen = true;
14489 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
14490
14491 this.once('end', onend);
14492}
14493
14494Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
14495 // making it explicit this property is not enumerable
14496 // because otherwise some prototype manipulation in
14497 // userland will fail
14498 enumerable: false,
14499 get: function () {
14500 return this._writableState.highWaterMark;
14501 }
14502});
14503
14504// the no-half-open enforcer
14505function onend() {
14506 // if we allow half-open state, or if the writable side ended,
14507 // then we're ok.
14508 if (this.allowHalfOpen || this._writableState.ended) return;
14509
14510 // no more data can be written.
14511 // But allow more writes to happen in this tick.
14512 pna.nextTick(onEndNT, this);
14513}
14514
14515function onEndNT(self) {
14516 self.end();
14517}
14518
14519Object.defineProperty(Duplex.prototype, 'destroyed', {
14520 get: function () {
14521 if (this._readableState === undefined || this._writableState === undefined) {
14522 return false;
14523 }
14524 return this._readableState.destroyed && this._writableState.destroyed;
14525 },
14526 set: function (value) {
14527 // we ignore the value if the stream
14528 // has not been initialized yet
14529 if (this._readableState === undefined || this._writableState === undefined) {
14530 return;
14531 }
14532
14533 // backward compatibility, the user is explicitly
14534 // managing destroyed
14535 this._readableState.destroyed = value;
14536 this._writableState.destroyed = value;
14537 }
14538});
14539
14540Duplex.prototype._destroy = function (err, cb) {
14541 this.push(null);
14542 this.end();
14543
14544 pna.nextTick(cb, err);
14545};
14546},{"10":10,"25":25,"70":70,"87":87,"89":89}],86:[function(_dereq_,module,exports){
14547// Copyright Joyent, Inc. and other Node contributors.
14548//
14549// Permission is hereby granted, free of charge, to any person obtaining a
14550// copy of this software and associated documentation files (the
14551// "Software"), to deal in the Software without restriction, including
14552// without limitation the rights to use, copy, modify, merge, publish,
14553// distribute, sublicense, and/or sell copies of the Software, and to permit
14554// persons to whom the Software is furnished to do so, subject to the
14555// following conditions:
14556//
14557// The above copyright notice and this permission notice shall be included
14558// in all copies or substantial portions of the Software.
14559//
14560// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14561// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14562// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14563// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14564// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14565// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14566// USE OR OTHER DEALINGS IN THE SOFTWARE.
14567
14568// a passthrough stream.
14569// basically just the most minimal sort of Transform stream.
14570// Every written chunk gets output as-is.
14571
14572'use strict';
14573
14574module.exports = PassThrough;
14575
14576var Transform = _dereq_(88);
14577
14578/*<replacement>*/
14579var util = _dereq_(10);
14580util.inherits = _dereq_(25);
14581/*</replacement>*/
14582
14583util.inherits(PassThrough, Transform);
14584
14585function PassThrough(options) {
14586 if (!(this instanceof PassThrough)) return new PassThrough(options);
14587
14588 Transform.call(this, options);
14589}
14590
14591PassThrough.prototype._transform = function (chunk, encoding, cb) {
14592 cb(null, chunk);
14593};
14594},{"10":10,"25":25,"88":88}],87:[function(_dereq_,module,exports){
14595(function (process,global){
14596// Copyright Joyent, Inc. and other Node contributors.
14597//
14598// Permission is hereby granted, free of charge, to any person obtaining a
14599// copy of this software and associated documentation files (the
14600// "Software"), to deal in the Software without restriction, including
14601// without limitation the rights to use, copy, modify, merge, publish,
14602// distribute, sublicense, and/or sell copies of the Software, and to permit
14603// persons to whom the Software is furnished to do so, subject to the
14604// following conditions:
14605//
14606// The above copyright notice and this permission notice shall be included
14607// in all copies or substantial portions of the Software.
14608//
14609// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14610// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14611// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14612// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14613// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14614// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14615// USE OR OTHER DEALINGS IN THE SOFTWARE.
14616
14617'use strict';
14618
14619/*<replacement>*/
14620
14621var pna = _dereq_(70);
14622/*</replacement>*/
14623
14624module.exports = Readable;
14625
14626/*<replacement>*/
14627var isArray = _dereq_(83);
14628/*</replacement>*/
14629
14630/*<replacement>*/
14631var Duplex;
14632/*</replacement>*/
14633
14634Readable.ReadableState = ReadableState;
14635
14636/*<replacement>*/
14637var EE = _dereq_(21).EventEmitter;
14638
14639var EElistenerCount = function (emitter, type) {
14640 return emitter.listeners(type).length;
14641};
14642/*</replacement>*/
14643
14644/*<replacement>*/
14645var Stream = _dereq_(92);
14646/*</replacement>*/
14647
14648/*<replacement>*/
14649
14650var Buffer = _dereq_(80).Buffer;
14651var OurUint8Array = global.Uint8Array || function () {};
14652function _uint8ArrayToBuffer(chunk) {
14653 return Buffer.from(chunk);
14654}
14655function _isUint8Array(obj) {
14656 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14657}
14658
14659/*</replacement>*/
14660
14661/*<replacement>*/
14662var util = _dereq_(10);
14663util.inherits = _dereq_(25);
14664/*</replacement>*/
14665
14666/*<replacement>*/
14667var debugUtil = _dereq_(7);
14668var debug = void 0;
14669if (debugUtil && debugUtil.debuglog) {
14670 debug = debugUtil.debuglog('stream');
14671} else {
14672 debug = function () {};
14673}
14674/*</replacement>*/
14675
14676var BufferList = _dereq_(90);
14677var destroyImpl = _dereq_(91);
14678var StringDecoder;
14679
14680util.inherits(Readable, Stream);
14681
14682var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14683
14684function prependListener(emitter, event, fn) {
14685 // Sadly this is not cacheable as some libraries bundle their own
14686 // event emitter implementation with them.
14687 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
14688
14689 // This is a hack to make sure that our error handler is attached before any
14690 // userland ones. NEVER DO THIS. This is here only because this code needs
14691 // to continue to work with older versions of Node.js that do not include
14692 // the prependListener() method. The goal is to eventually remove this hack.
14693 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]];
14694}
14695
14696function ReadableState(options, stream) {
14697 Duplex = Duplex || _dereq_(85);
14698
14699 options = options || {};
14700
14701 // Duplex streams are both readable and writable, but share
14702 // the same options object.
14703 // However, some cases require setting options to different
14704 // values for the readable and the writable sides of the duplex stream.
14705 // These options can be provided separately as readableXXX and writableXXX.
14706 var isDuplex = stream instanceof Duplex;
14707
14708 // object stream flag. Used to make read(n) ignore n and to
14709 // make all the buffer merging and length checks go away
14710 this.objectMode = !!options.objectMode;
14711
14712 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
14713
14714 // the point at which it stops calling _read() to fill the buffer
14715 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14716 var hwm = options.highWaterMark;
14717 var readableHwm = options.readableHighWaterMark;
14718 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14719
14720 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
14721
14722 // cast to ints.
14723 this.highWaterMark = Math.floor(this.highWaterMark);
14724
14725 // A linked list is used to store data chunks instead of an array because the
14726 // linked list can remove elements from the beginning faster than
14727 // array.shift()
14728 this.buffer = new BufferList();
14729 this.length = 0;
14730 this.pipes = null;
14731 this.pipesCount = 0;
14732 this.flowing = null;
14733 this.ended = false;
14734 this.endEmitted = false;
14735 this.reading = false;
14736
14737 // a flag to be able to tell if the event 'readable'/'data' is emitted
14738 // immediately, or on a later tick. We set this to true at first, because
14739 // any actions that shouldn't happen until "later" should generally also
14740 // not happen before the first read call.
14741 this.sync = true;
14742
14743 // whenever we return null, then we set a flag to say
14744 // that we're awaiting a 'readable' event emission.
14745 this.needReadable = false;
14746 this.emittedReadable = false;
14747 this.readableListening = false;
14748 this.resumeScheduled = false;
14749
14750 // has it been destroyed
14751 this.destroyed = false;
14752
14753 // Crypto is kind of old and crusty. Historically, its default string
14754 // encoding is 'binary' so we have to make this configurable.
14755 // Everything else in the universe uses 'utf8', though.
14756 this.defaultEncoding = options.defaultEncoding || 'utf8';
14757
14758 // the number of writers that are awaiting a drain event in .pipe()s
14759 this.awaitDrain = 0;
14760
14761 // if true, a maybeReadMore has been scheduled
14762 this.readingMore = false;
14763
14764 this.decoder = null;
14765 this.encoding = null;
14766 if (options.encoding) {
14767 if (!StringDecoder) StringDecoder = _dereq_(97).StringDecoder;
14768 this.decoder = new StringDecoder(options.encoding);
14769 this.encoding = options.encoding;
14770 }
14771}
14772
14773function Readable(options) {
14774 Duplex = Duplex || _dereq_(85);
14775
14776 if (!(this instanceof Readable)) return new Readable(options);
14777
14778 this._readableState = new ReadableState(options, this);
14779
14780 // legacy
14781 this.readable = true;
14782
14783 if (options) {
14784 if (typeof options.read === 'function') this._read = options.read;
14785
14786 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14787 }
14788
14789 Stream.call(this);
14790}
14791
14792Object.defineProperty(Readable.prototype, 'destroyed', {
14793 get: function () {
14794 if (this._readableState === undefined) {
14795 return false;
14796 }
14797 return this._readableState.destroyed;
14798 },
14799 set: function (value) {
14800 // we ignore the value if the stream
14801 // has not been initialized yet
14802 if (!this._readableState) {
14803 return;
14804 }
14805
14806 // backward compatibility, the user is explicitly
14807 // managing destroyed
14808 this._readableState.destroyed = value;
14809 }
14810});
14811
14812Readable.prototype.destroy = destroyImpl.destroy;
14813Readable.prototype._undestroy = destroyImpl.undestroy;
14814Readable.prototype._destroy = function (err, cb) {
14815 this.push(null);
14816 cb(err);
14817};
14818
14819// Manually shove something into the read() buffer.
14820// This returns true if the highWaterMark has not been hit yet,
14821// similar to how Writable.write() returns true if you should
14822// write() some more.
14823Readable.prototype.push = function (chunk, encoding) {
14824 var state = this._readableState;
14825 var skipChunkCheck;
14826
14827 if (!state.objectMode) {
14828 if (typeof chunk === 'string') {
14829 encoding = encoding || state.defaultEncoding;
14830 if (encoding !== state.encoding) {
14831 chunk = Buffer.from(chunk, encoding);
14832 encoding = '';
14833 }
14834 skipChunkCheck = true;
14835 }
14836 } else {
14837 skipChunkCheck = true;
14838 }
14839
14840 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
14841};
14842
14843// Unshift should *always* be something directly out of read()
14844Readable.prototype.unshift = function (chunk) {
14845 return readableAddChunk(this, chunk, null, true, false);
14846};
14847
14848function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
14849 var state = stream._readableState;
14850 if (chunk === null) {
14851 state.reading = false;
14852 onEofChunk(stream, state);
14853 } else {
14854 var er;
14855 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
14856 if (er) {
14857 stream.emit('error', er);
14858 } else if (state.objectMode || chunk && chunk.length > 0) {
14859 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
14860 chunk = _uint8ArrayToBuffer(chunk);
14861 }
14862
14863 if (addToFront) {
14864 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
14865 } else if (state.ended) {
14866 stream.emit('error', new Error('stream.push() after EOF'));
14867 } else {
14868 state.reading = false;
14869 if (state.decoder && !encoding) {
14870 chunk = state.decoder.write(chunk);
14871 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
14872 } else {
14873 addChunk(stream, state, chunk, false);
14874 }
14875 }
14876 } else if (!addToFront) {
14877 state.reading = false;
14878 }
14879 }
14880
14881 return needMoreData(state);
14882}
14883
14884function addChunk(stream, state, chunk, addToFront) {
14885 if (state.flowing && state.length === 0 && !state.sync) {
14886 stream.emit('data', chunk);
14887 stream.read(0);
14888 } else {
14889 // update the buffer info.
14890 state.length += state.objectMode ? 1 : chunk.length;
14891 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
14892
14893 if (state.needReadable) emitReadable(stream);
14894 }
14895 maybeReadMore(stream, state);
14896}
14897
14898function chunkInvalid(state, chunk) {
14899 var er;
14900 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
14901 er = new TypeError('Invalid non-string/buffer chunk');
14902 }
14903 return er;
14904}
14905
14906// if it's past the high water mark, we can push in some more.
14907// Also, if we have no data yet, we can stand some
14908// more bytes. This is to work around cases where hwm=0,
14909// such as the repl. Also, if the push() triggered a
14910// readable event, and the user called read(largeNumber) such that
14911// needReadable was set, then we ought to push more, so that another
14912// 'readable' event will be triggered.
14913function needMoreData(state) {
14914 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
14915}
14916
14917Readable.prototype.isPaused = function () {
14918 return this._readableState.flowing === false;
14919};
14920
14921// backwards compatibility.
14922Readable.prototype.setEncoding = function (enc) {
14923 if (!StringDecoder) StringDecoder = _dereq_(97).StringDecoder;
14924 this._readableState.decoder = new StringDecoder(enc);
14925 this._readableState.encoding = enc;
14926 return this;
14927};
14928
14929// Don't raise the hwm > 8MB
14930var MAX_HWM = 0x800000;
14931function computeNewHighWaterMark(n) {
14932 if (n >= MAX_HWM) {
14933 n = MAX_HWM;
14934 } else {
14935 // Get the next highest power of 2 to prevent increasing hwm excessively in
14936 // tiny amounts
14937 n--;
14938 n |= n >>> 1;
14939 n |= n >>> 2;
14940 n |= n >>> 4;
14941 n |= n >>> 8;
14942 n |= n >>> 16;
14943 n++;
14944 }
14945 return n;
14946}
14947
14948// This function is designed to be inlinable, so please take care when making
14949// changes to the function body.
14950function howMuchToRead(n, state) {
14951 if (n <= 0 || state.length === 0 && state.ended) return 0;
14952 if (state.objectMode) return 1;
14953 if (n !== n) {
14954 // Only flow one buffer at a time
14955 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
14956 }
14957 // If we're asking for more than the current hwm, then raise the hwm.
14958 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
14959 if (n <= state.length) return n;
14960 // Don't have enough
14961 if (!state.ended) {
14962 state.needReadable = true;
14963 return 0;
14964 }
14965 return state.length;
14966}
14967
14968// you can override either this method, or the async _read(n) below.
14969Readable.prototype.read = function (n) {
14970 debug('read', n);
14971 n = parseInt(n, 10);
14972 var state = this._readableState;
14973 var nOrig = n;
14974
14975 if (n !== 0) state.emittedReadable = false;
14976
14977 // if we're doing read(0) to trigger a readable event, but we
14978 // already have a bunch of data in the buffer, then just trigger
14979 // the 'readable' event and move on.
14980 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
14981 debug('read: emitReadable', state.length, state.ended);
14982 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
14983 return null;
14984 }
14985
14986 n = howMuchToRead(n, state);
14987
14988 // if we've ended, and we're now clear, then finish it up.
14989 if (n === 0 && state.ended) {
14990 if (state.length === 0) endReadable(this);
14991 return null;
14992 }
14993
14994 // All the actual chunk generation logic needs to be
14995 // *below* the call to _read. The reason is that in certain
14996 // synthetic stream cases, such as passthrough streams, _read
14997 // may be a completely synchronous operation which may change
14998 // the state of the read buffer, providing enough data when
14999 // before there was *not* enough.
15000 //
15001 // So, the steps are:
15002 // 1. Figure out what the state of things will be after we do
15003 // a read from the buffer.
15004 //
15005 // 2. If that resulting state will trigger a _read, then call _read.
15006 // Note that this may be asynchronous, or synchronous. Yes, it is
15007 // deeply ugly to write APIs this way, but that still doesn't mean
15008 // that the Readable class should behave improperly, as streams are
15009 // designed to be sync/async agnostic.
15010 // Take note if the _read call is sync or async (ie, if the read call
15011 // has returned yet), so that we know whether or not it's safe to emit
15012 // 'readable' etc.
15013 //
15014 // 3. Actually pull the requested chunks out of the buffer and return.
15015
15016 // if we need a readable event, then we need to do some reading.
15017 var doRead = state.needReadable;
15018 debug('need readable', doRead);
15019
15020 // if we currently have less than the highWaterMark, then also read some
15021 if (state.length === 0 || state.length - n < state.highWaterMark) {
15022 doRead = true;
15023 debug('length less than watermark', doRead);
15024 }
15025
15026 // however, if we've ended, then there's no point, and if we're already
15027 // reading, then it's unnecessary.
15028 if (state.ended || state.reading) {
15029 doRead = false;
15030 debug('reading or ended', doRead);
15031 } else if (doRead) {
15032 debug('do read');
15033 state.reading = true;
15034 state.sync = true;
15035 // if the length is currently zero, then we *need* a readable event.
15036 if (state.length === 0) state.needReadable = true;
15037 // call internal read method
15038 this._read(state.highWaterMark);
15039 state.sync = false;
15040 // If _read pushed data synchronously, then `reading` will be false,
15041 // and we need to re-evaluate how much data we can return to the user.
15042 if (!state.reading) n = howMuchToRead(nOrig, state);
15043 }
15044
15045 var ret;
15046 if (n > 0) ret = fromList(n, state);else ret = null;
15047
15048 if (ret === null) {
15049 state.needReadable = true;
15050 n = 0;
15051 } else {
15052 state.length -= n;
15053 }
15054
15055 if (state.length === 0) {
15056 // If we have nothing in the buffer, then we want to know
15057 // as soon as we *do* get something into the buffer.
15058 if (!state.ended) state.needReadable = true;
15059
15060 // If we tried to read() past the EOF, then emit end on the next tick.
15061 if (nOrig !== n && state.ended) endReadable(this);
15062 }
15063
15064 if (ret !== null) this.emit('data', ret);
15065
15066 return ret;
15067};
15068
15069function onEofChunk(stream, state) {
15070 if (state.ended) return;
15071 if (state.decoder) {
15072 var chunk = state.decoder.end();
15073 if (chunk && chunk.length) {
15074 state.buffer.push(chunk);
15075 state.length += state.objectMode ? 1 : chunk.length;
15076 }
15077 }
15078 state.ended = true;
15079
15080 // emit 'readable' now to make sure it gets picked up.
15081 emitReadable(stream);
15082}
15083
15084// Don't emit readable right away in sync mode, because this can trigger
15085// another read() call => stack overflow. This way, it might trigger
15086// a nextTick recursion warning, but that's not so bad.
15087function emitReadable(stream) {
15088 var state = stream._readableState;
15089 state.needReadable = false;
15090 if (!state.emittedReadable) {
15091 debug('emitReadable', state.flowing);
15092 state.emittedReadable = true;
15093 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
15094 }
15095}
15096
15097function emitReadable_(stream) {
15098 debug('emit readable');
15099 stream.emit('readable');
15100 flow(stream);
15101}
15102
15103// at this point, the user has presumably seen the 'readable' event,
15104// and called read() to consume some data. that may have triggered
15105// in turn another _read(n) call, in which case reading = true if
15106// it's in progress.
15107// However, if we're not ended, or reading, and the length < hwm,
15108// then go ahead and try to read some more preemptively.
15109function maybeReadMore(stream, state) {
15110 if (!state.readingMore) {
15111 state.readingMore = true;
15112 pna.nextTick(maybeReadMore_, stream, state);
15113 }
15114}
15115
15116function maybeReadMore_(stream, state) {
15117 var len = state.length;
15118 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
15119 debug('maybeReadMore read 0');
15120 stream.read(0);
15121 if (len === state.length)
15122 // didn't get any data, stop spinning.
15123 break;else len = state.length;
15124 }
15125 state.readingMore = false;
15126}
15127
15128// abstract method. to be overridden in specific implementation classes.
15129// call cb(er, data) where data is <= n in length.
15130// for virtual (non-string, non-buffer) streams, "length" is somewhat
15131// arbitrary, and perhaps not very meaningful.
15132Readable.prototype._read = function (n) {
15133 this.emit('error', new Error('_read() is not implemented'));
15134};
15135
15136Readable.prototype.pipe = function (dest, pipeOpts) {
15137 var src = this;
15138 var state = this._readableState;
15139
15140 switch (state.pipesCount) {
15141 case 0:
15142 state.pipes = dest;
15143 break;
15144 case 1:
15145 state.pipes = [state.pipes, dest];
15146 break;
15147 default:
15148 state.pipes.push(dest);
15149 break;
15150 }
15151 state.pipesCount += 1;
15152 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
15153
15154 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
15155
15156 var endFn = doEnd ? onend : unpipe;
15157 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
15158
15159 dest.on('unpipe', onunpipe);
15160 function onunpipe(readable, unpipeInfo) {
15161 debug('onunpipe');
15162 if (readable === src) {
15163 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
15164 unpipeInfo.hasUnpiped = true;
15165 cleanup();
15166 }
15167 }
15168 }
15169
15170 function onend() {
15171 debug('onend');
15172 dest.end();
15173 }
15174
15175 // when the dest drains, it reduces the awaitDrain counter
15176 // on the source. This would be more elegant with a .once()
15177 // handler in flow(), but adding and removing repeatedly is
15178 // too slow.
15179 var ondrain = pipeOnDrain(src);
15180 dest.on('drain', ondrain);
15181
15182 var cleanedUp = false;
15183 function cleanup() {
15184 debug('cleanup');
15185 // cleanup event handlers once the pipe is broken
15186 dest.removeListener('close', onclose);
15187 dest.removeListener('finish', onfinish);
15188 dest.removeListener('drain', ondrain);
15189 dest.removeListener('error', onerror);
15190 dest.removeListener('unpipe', onunpipe);
15191 src.removeListener('end', onend);
15192 src.removeListener('end', unpipe);
15193 src.removeListener('data', ondata);
15194
15195 cleanedUp = true;
15196
15197 // if the reader is waiting for a drain event from this
15198 // specific writer, then it would cause it to never start
15199 // flowing again.
15200 // So, if this is awaiting a drain, then we just call it now.
15201 // If we don't know, then assume that we are waiting for one.
15202 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
15203 }
15204
15205 // If the user pushes more data while we're writing to dest then we'll end up
15206 // in ondata again. However, we only want to increase awaitDrain once because
15207 // dest will only emit one 'drain' event for the multiple writes.
15208 // => Introduce a guard on increasing awaitDrain.
15209 var increasedAwaitDrain = false;
15210 src.on('data', ondata);
15211 function ondata(chunk) {
15212 debug('ondata');
15213 increasedAwaitDrain = false;
15214 var ret = dest.write(chunk);
15215 if (false === ret && !increasedAwaitDrain) {
15216 // If the user unpiped during `dest.write()`, it is possible
15217 // to get stuck in a permanently paused state if that write
15218 // also returned false.
15219 // => Check whether `dest` is still a piping destination.
15220 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
15221 debug('false write response, pause', src._readableState.awaitDrain);
15222 src._readableState.awaitDrain++;
15223 increasedAwaitDrain = true;
15224 }
15225 src.pause();
15226 }
15227 }
15228
15229 // if the dest has an error, then stop piping into it.
15230 // however, don't suppress the throwing behavior for this.
15231 function onerror(er) {
15232 debug('onerror', er);
15233 unpipe();
15234 dest.removeListener('error', onerror);
15235 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
15236 }
15237
15238 // Make sure our error handler is attached before userland ones.
15239 prependListener(dest, 'error', onerror);
15240
15241 // Both close and finish should trigger unpipe, but only once.
15242 function onclose() {
15243 dest.removeListener('finish', onfinish);
15244 unpipe();
15245 }
15246 dest.once('close', onclose);
15247 function onfinish() {
15248 debug('onfinish');
15249 dest.removeListener('close', onclose);
15250 unpipe();
15251 }
15252 dest.once('finish', onfinish);
15253
15254 function unpipe() {
15255 debug('unpipe');
15256 src.unpipe(dest);
15257 }
15258
15259 // tell the dest that it's being piped to
15260 dest.emit('pipe', src);
15261
15262 // start the flow if it hasn't been started already.
15263 if (!state.flowing) {
15264 debug('pipe resume');
15265 src.resume();
15266 }
15267
15268 return dest;
15269};
15270
15271function pipeOnDrain(src) {
15272 return function () {
15273 var state = src._readableState;
15274 debug('pipeOnDrain', state.awaitDrain);
15275 if (state.awaitDrain) state.awaitDrain--;
15276 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
15277 state.flowing = true;
15278 flow(src);
15279 }
15280 };
15281}
15282
15283Readable.prototype.unpipe = function (dest) {
15284 var state = this._readableState;
15285 var unpipeInfo = { hasUnpiped: false };
15286
15287 // if we're not piping anywhere, then do nothing.
15288 if (state.pipesCount === 0) return this;
15289
15290 // just one destination. most common case.
15291 if (state.pipesCount === 1) {
15292 // passed in one, but it's not the right one.
15293 if (dest && dest !== state.pipes) return this;
15294
15295 if (!dest) dest = state.pipes;
15296
15297 // got a match.
15298 state.pipes = null;
15299 state.pipesCount = 0;
15300 state.flowing = false;
15301 if (dest) dest.emit('unpipe', this, unpipeInfo);
15302 return this;
15303 }
15304
15305 // slow case. multiple pipe destinations.
15306
15307 if (!dest) {
15308 // remove all.
15309 var dests = state.pipes;
15310 var len = state.pipesCount;
15311 state.pipes = null;
15312 state.pipesCount = 0;
15313 state.flowing = false;
15314
15315 for (var i = 0; i < len; i++) {
15316 dests[i].emit('unpipe', this, unpipeInfo);
15317 }return this;
15318 }
15319
15320 // try to find the right one.
15321 var index = indexOf(state.pipes, dest);
15322 if (index === -1) return this;
15323
15324 state.pipes.splice(index, 1);
15325 state.pipesCount -= 1;
15326 if (state.pipesCount === 1) state.pipes = state.pipes[0];
15327
15328 dest.emit('unpipe', this, unpipeInfo);
15329
15330 return this;
15331};
15332
15333// set up data events if they are asked for
15334// Ensure readable listeners eventually get something
15335Readable.prototype.on = function (ev, fn) {
15336 var res = Stream.prototype.on.call(this, ev, fn);
15337
15338 if (ev === 'data') {
15339 // Start flowing on next tick if stream isn't explicitly paused
15340 if (this._readableState.flowing !== false) this.resume();
15341 } else if (ev === 'readable') {
15342 var state = this._readableState;
15343 if (!state.endEmitted && !state.readableListening) {
15344 state.readableListening = state.needReadable = true;
15345 state.emittedReadable = false;
15346 if (!state.reading) {
15347 pna.nextTick(nReadingNextTick, this);
15348 } else if (state.length) {
15349 emitReadable(this);
15350 }
15351 }
15352 }
15353
15354 return res;
15355};
15356Readable.prototype.addListener = Readable.prototype.on;
15357
15358function nReadingNextTick(self) {
15359 debug('readable nexttick read 0');
15360 self.read(0);
15361}
15362
15363// pause() and resume() are remnants of the legacy readable stream API
15364// If the user uses them, then switch into old mode.
15365Readable.prototype.resume = function () {
15366 var state = this._readableState;
15367 if (!state.flowing) {
15368 debug('resume');
15369 state.flowing = true;
15370 resume(this, state);
15371 }
15372 return this;
15373};
15374
15375function resume(stream, state) {
15376 if (!state.resumeScheduled) {
15377 state.resumeScheduled = true;
15378 pna.nextTick(resume_, stream, state);
15379 }
15380}
15381
15382function resume_(stream, state) {
15383 if (!state.reading) {
15384 debug('resume read 0');
15385 stream.read(0);
15386 }
15387
15388 state.resumeScheduled = false;
15389 state.awaitDrain = 0;
15390 stream.emit('resume');
15391 flow(stream);
15392 if (state.flowing && !state.reading) stream.read(0);
15393}
15394
15395Readable.prototype.pause = function () {
15396 debug('call pause flowing=%j', this._readableState.flowing);
15397 if (false !== this._readableState.flowing) {
15398 debug('pause');
15399 this._readableState.flowing = false;
15400 this.emit('pause');
15401 }
15402 return this;
15403};
15404
15405function flow(stream) {
15406 var state = stream._readableState;
15407 debug('flow', state.flowing);
15408 while (state.flowing && stream.read() !== null) {}
15409}
15410
15411// wrap an old-style stream as the async data source.
15412// This is *not* part of the readable stream interface.
15413// It is an ugly unfortunate mess of history.
15414Readable.prototype.wrap = function (stream) {
15415 var _this = this;
15416
15417 var state = this._readableState;
15418 var paused = false;
15419
15420 stream.on('end', function () {
15421 debug('wrapped end');
15422 if (state.decoder && !state.ended) {
15423 var chunk = state.decoder.end();
15424 if (chunk && chunk.length) _this.push(chunk);
15425 }
15426
15427 _this.push(null);
15428 });
15429
15430 stream.on('data', function (chunk) {
15431 debug('wrapped data');
15432 if (state.decoder) chunk = state.decoder.write(chunk);
15433
15434 // don't skip over falsy values in objectMode
15435 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
15436
15437 var ret = _this.push(chunk);
15438 if (!ret) {
15439 paused = true;
15440 stream.pause();
15441 }
15442 });
15443
15444 // proxy all the other methods.
15445 // important when wrapping filters and duplexes.
15446 for (var i in stream) {
15447 if (this[i] === undefined && typeof stream[i] === 'function') {
15448 this[i] = function (method) {
15449 return function () {
15450 return stream[method].apply(stream, arguments);
15451 };
15452 }(i);
15453 }
15454 }
15455
15456 // proxy certain important events.
15457 for (var n = 0; n < kProxyEvents.length; n++) {
15458 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
15459 }
15460
15461 // when we try to consume some more bytes, simply unpause the
15462 // underlying stream.
15463 this._read = function (n) {
15464 debug('wrapped _read', n);
15465 if (paused) {
15466 paused = false;
15467 stream.resume();
15468 }
15469 };
15470
15471 return this;
15472};
15473
15474Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
15475 // making it explicit this property is not enumerable
15476 // because otherwise some prototype manipulation in
15477 // userland will fail
15478 enumerable: false,
15479 get: function () {
15480 return this._readableState.highWaterMark;
15481 }
15482});
15483
15484// exposed for testing purposes only.
15485Readable._fromList = fromList;
15486
15487// Pluck off n bytes from an array of buffers.
15488// Length is the combined lengths of all the buffers in the list.
15489// This function is designed to be inlinable, so please take care when making
15490// changes to the function body.
15491function fromList(n, state) {
15492 // nothing buffered
15493 if (state.length === 0) return null;
15494
15495 var ret;
15496 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
15497 // read it all, truncate the list
15498 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);
15499 state.buffer.clear();
15500 } else {
15501 // read part of list
15502 ret = fromListPartial(n, state.buffer, state.decoder);
15503 }
15504
15505 return ret;
15506}
15507
15508// Extracts only enough buffered data to satisfy the amount requested.
15509// This function is designed to be inlinable, so please take care when making
15510// changes to the function body.
15511function fromListPartial(n, list, hasStrings) {
15512 var ret;
15513 if (n < list.head.data.length) {
15514 // slice is the same for buffers and strings
15515 ret = list.head.data.slice(0, n);
15516 list.head.data = list.head.data.slice(n);
15517 } else if (n === list.head.data.length) {
15518 // first chunk is a perfect match
15519 ret = list.shift();
15520 } else {
15521 // result spans more than one buffer
15522 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
15523 }
15524 return ret;
15525}
15526
15527// Copies a specified amount of characters from the list of buffered data
15528// chunks.
15529// This function is designed to be inlinable, so please take care when making
15530// changes to the function body.
15531function copyFromBufferString(n, list) {
15532 var p = list.head;
15533 var c = 1;
15534 var ret = p.data;
15535 n -= ret.length;
15536 while (p = p.next) {
15537 var str = p.data;
15538 var nb = n > str.length ? str.length : n;
15539 if (nb === str.length) ret += str;else ret += str.slice(0, n);
15540 n -= nb;
15541 if (n === 0) {
15542 if (nb === str.length) {
15543 ++c;
15544 if (p.next) list.head = p.next;else list.head = list.tail = null;
15545 } else {
15546 list.head = p;
15547 p.data = str.slice(nb);
15548 }
15549 break;
15550 }
15551 ++c;
15552 }
15553 list.length -= c;
15554 return ret;
15555}
15556
15557// Copies a specified amount of bytes from the list of buffered data chunks.
15558// This function is designed to be inlinable, so please take care when making
15559// changes to the function body.
15560function copyFromBuffer(n, list) {
15561 var ret = Buffer.allocUnsafe(n);
15562 var p = list.head;
15563 var c = 1;
15564 p.data.copy(ret);
15565 n -= p.data.length;
15566 while (p = p.next) {
15567 var buf = p.data;
15568 var nb = n > buf.length ? buf.length : n;
15569 buf.copy(ret, ret.length - n, 0, nb);
15570 n -= nb;
15571 if (n === 0) {
15572 if (nb === buf.length) {
15573 ++c;
15574 if (p.next) list.head = p.next;else list.head = list.tail = null;
15575 } else {
15576 list.head = p;
15577 p.data = buf.slice(nb);
15578 }
15579 break;
15580 }
15581 ++c;
15582 }
15583 list.length -= c;
15584 return ret;
15585}
15586
15587function endReadable(stream) {
15588 var state = stream._readableState;
15589
15590 // If we get here before consuming all the bytes, then that is a
15591 // bug in node. Should never happen.
15592 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
15593
15594 if (!state.endEmitted) {
15595 state.ended = true;
15596 pna.nextTick(endReadableNT, state, stream);
15597 }
15598}
15599
15600function endReadableNT(state, stream) {
15601 // Check that we didn't get one last unshift.
15602 if (!state.endEmitted && state.length === 0) {
15603 state.endEmitted = true;
15604 stream.readable = false;
15605 stream.emit('end');
15606 }
15607}
15608
15609function indexOf(xs, x) {
15610 for (var i = 0, l = xs.length; i < l; i++) {
15611 if (xs[i] === x) return i;
15612 }
15613 return -1;
15614}
15615}).call(this,_dereq_(71),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15616},{"10":10,"21":21,"25":25,"7":7,"70":70,"71":71,"80":80,"83":83,"85":85,"90":90,"91":91,"92":92,"97":97}],88:[function(_dereq_,module,exports){
15617// Copyright Joyent, Inc. and other Node contributors.
15618//
15619// Permission is hereby granted, free of charge, to any person obtaining a
15620// copy of this software and associated documentation files (the
15621// "Software"), to deal in the Software without restriction, including
15622// without limitation the rights to use, copy, modify, merge, publish,
15623// distribute, sublicense, and/or sell copies of the Software, and to permit
15624// persons to whom the Software is furnished to do so, subject to the
15625// following conditions:
15626//
15627// The above copyright notice and this permission notice shall be included
15628// in all copies or substantial portions of the Software.
15629//
15630// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15631// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15632// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15633// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15634// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15635// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15636// USE OR OTHER DEALINGS IN THE SOFTWARE.
15637
15638// a transform stream is a readable/writable stream where you do
15639// something with the data. Sometimes it's called a "filter",
15640// but that's not a great name for it, since that implies a thing where
15641// some bits pass through, and others are simply ignored. (That would
15642// be a valid example of a transform, of course.)
15643//
15644// While the output is causally related to the input, it's not a
15645// necessarily symmetric or synchronous transformation. For example,
15646// a zlib stream might take multiple plain-text writes(), and then
15647// emit a single compressed chunk some time in the future.
15648//
15649// Here's how this works:
15650//
15651// The Transform stream has all the aspects of the readable and writable
15652// stream classes. When you write(chunk), that calls _write(chunk,cb)
15653// internally, and returns false if there's a lot of pending writes
15654// buffered up. When you call read(), that calls _read(n) until
15655// there's enough pending readable data buffered up.
15656//
15657// In a transform stream, the written data is placed in a buffer. When
15658// _read(n) is called, it transforms the queued up data, calling the
15659// buffered _write cb's as it consumes chunks. If consuming a single
15660// written chunk would result in multiple output chunks, then the first
15661// outputted bit calls the readcb, and subsequent chunks just go into
15662// the read buffer, and will cause it to emit 'readable' if necessary.
15663//
15664// This way, back-pressure is actually determined by the reading side,
15665// since _read has to be called to start processing a new chunk. However,
15666// a pathological inflate type of transform can cause excessive buffering
15667// here. For example, imagine a stream where every byte of input is
15668// interpreted as an integer from 0-255, and then results in that many
15669// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
15670// 1kb of data being output. In this case, you could write a very small
15671// amount of input, and end up with a very large amount of output. In
15672// such a pathological inflating mechanism, there'd be no way to tell
15673// the system to stop doing the transform. A single 4MB write could
15674// cause the system to run out of memory.
15675//
15676// However, even in such a pathological case, only a single written chunk
15677// would be consumed, and then the rest would wait (un-transformed) until
15678// the results of the previous transformed chunk were consumed.
15679
15680'use strict';
15681
15682module.exports = Transform;
15683
15684var Duplex = _dereq_(85);
15685
15686/*<replacement>*/
15687var util = _dereq_(10);
15688util.inherits = _dereq_(25);
15689/*</replacement>*/
15690
15691util.inherits(Transform, Duplex);
15692
15693function afterTransform(er, data) {
15694 var ts = this._transformState;
15695 ts.transforming = false;
15696
15697 var cb = ts.writecb;
15698
15699 if (!cb) {
15700 return this.emit('error', new Error('write callback called multiple times'));
15701 }
15702
15703 ts.writechunk = null;
15704 ts.writecb = null;
15705
15706 if (data != null) // single equals check for both `null` and `undefined`
15707 this.push(data);
15708
15709 cb(er);
15710
15711 var rs = this._readableState;
15712 rs.reading = false;
15713 if (rs.needReadable || rs.length < rs.highWaterMark) {
15714 this._read(rs.highWaterMark);
15715 }
15716}
15717
15718function Transform(options) {
15719 if (!(this instanceof Transform)) return new Transform(options);
15720
15721 Duplex.call(this, options);
15722
15723 this._transformState = {
15724 afterTransform: afterTransform.bind(this),
15725 needTransform: false,
15726 transforming: false,
15727 writecb: null,
15728 writechunk: null,
15729 writeencoding: null
15730 };
15731
15732 // start out asking for a readable event once data is transformed.
15733 this._readableState.needReadable = true;
15734
15735 // we have implemented the _read method, and done the other things
15736 // that Readable wants before the first _read call, so unset the
15737 // sync guard flag.
15738 this._readableState.sync = false;
15739
15740 if (options) {
15741 if (typeof options.transform === 'function') this._transform = options.transform;
15742
15743 if (typeof options.flush === 'function') this._flush = options.flush;
15744 }
15745
15746 // When the writable side finishes, then flush out anything remaining.
15747 this.on('prefinish', prefinish);
15748}
15749
15750function prefinish() {
15751 var _this = this;
15752
15753 if (typeof this._flush === 'function') {
15754 this._flush(function (er, data) {
15755 done(_this, er, data);
15756 });
15757 } else {
15758 done(this, null, null);
15759 }
15760}
15761
15762Transform.prototype.push = function (chunk, encoding) {
15763 this._transformState.needTransform = false;
15764 return Duplex.prototype.push.call(this, chunk, encoding);
15765};
15766
15767// This is the part where you do stuff!
15768// override this function in implementation classes.
15769// 'chunk' is an input chunk.
15770//
15771// Call `push(newChunk)` to pass along transformed output
15772// to the readable side. You may call 'push' zero or more times.
15773//
15774// Call `cb(err)` when you are done with this chunk. If you pass
15775// an error, then that'll put the hurt on the whole operation. If you
15776// never call cb(), then you'll never get another chunk.
15777Transform.prototype._transform = function (chunk, encoding, cb) {
15778 throw new Error('_transform() is not implemented');
15779};
15780
15781Transform.prototype._write = function (chunk, encoding, cb) {
15782 var ts = this._transformState;
15783 ts.writecb = cb;
15784 ts.writechunk = chunk;
15785 ts.writeencoding = encoding;
15786 if (!ts.transforming) {
15787 var rs = this._readableState;
15788 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15789 }
15790};
15791
15792// Doesn't matter what the args are here.
15793// _transform does all the work.
15794// That we got here means that the readable side wants more data.
15795Transform.prototype._read = function (n) {
15796 var ts = this._transformState;
15797
15798 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15799 ts.transforming = true;
15800 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15801 } else {
15802 // mark that we need a transform, so that any data that comes in
15803 // will get processed, now that we've asked for it.
15804 ts.needTransform = true;
15805 }
15806};
15807
15808Transform.prototype._destroy = function (err, cb) {
15809 var _this2 = this;
15810
15811 Duplex.prototype._destroy.call(this, err, function (err2) {
15812 cb(err2);
15813 _this2.emit('close');
15814 });
15815};
15816
15817function done(stream, er, data) {
15818 if (er) return stream.emit('error', er);
15819
15820 if (data != null) // single equals check for both `null` and `undefined`
15821 stream.push(data);
15822
15823 // if there's nothing in the write buffer, then that means
15824 // that nothing more will ever be provided
15825 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
15826
15827 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
15828
15829 return stream.push(null);
15830}
15831},{"10":10,"25":25,"85":85}],89:[function(_dereq_,module,exports){
15832(function (process,global,setImmediate){
15833// Copyright Joyent, Inc. and other Node contributors.
15834//
15835// Permission is hereby granted, free of charge, to any person obtaining a
15836// copy of this software and associated documentation files (the
15837// "Software"), to deal in the Software without restriction, including
15838// without limitation the rights to use, copy, modify, merge, publish,
15839// distribute, sublicense, and/or sell copies of the Software, and to permit
15840// persons to whom the Software is furnished to do so, subject to the
15841// following conditions:
15842//
15843// The above copyright notice and this permission notice shall be included
15844// in all copies or substantial portions of the Software.
15845//
15846// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15847// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15848// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15849// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15850// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15851// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15852// USE OR OTHER DEALINGS IN THE SOFTWARE.
15853
15854// A bit simpler than readable streams.
15855// Implement an async ._write(chunk, encoding, cb), and it'll handle all
15856// the drain event emission and buffering.
15857
15858'use strict';
15859
15860/*<replacement>*/
15861
15862var pna = _dereq_(70);
15863/*</replacement>*/
15864
15865module.exports = Writable;
15866
15867/* <replacement> */
15868function WriteReq(chunk, encoding, cb) {
15869 this.chunk = chunk;
15870 this.encoding = encoding;
15871 this.callback = cb;
15872 this.next = null;
15873}
15874
15875// It seems a linked list but it is not
15876// there will be only 2 of these for each stream
15877function CorkedRequest(state) {
15878 var _this = this;
15879
15880 this.next = null;
15881 this.entry = null;
15882 this.finish = function () {
15883 onCorkedFinish(_this, state);
15884 };
15885}
15886/* </replacement> */
15887
15888/*<replacement>*/
15889var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
15890/*</replacement>*/
15891
15892/*<replacement>*/
15893var Duplex;
15894/*</replacement>*/
15895
15896Writable.WritableState = WritableState;
15897
15898/*<replacement>*/
15899var util = _dereq_(10);
15900util.inherits = _dereq_(25);
15901/*</replacement>*/
15902
15903/*<replacement>*/
15904var internalUtil = {
15905 deprecate: _dereq_(116)
15906};
15907/*</replacement>*/
15908
15909/*<replacement>*/
15910var Stream = _dereq_(92);
15911/*</replacement>*/
15912
15913/*<replacement>*/
15914
15915var Buffer = _dereq_(80).Buffer;
15916var OurUint8Array = global.Uint8Array || function () {};
15917function _uint8ArrayToBuffer(chunk) {
15918 return Buffer.from(chunk);
15919}
15920function _isUint8Array(obj) {
15921 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
15922}
15923
15924/*</replacement>*/
15925
15926var destroyImpl = _dereq_(91);
15927
15928util.inherits(Writable, Stream);
15929
15930function nop() {}
15931
15932function WritableState(options, stream) {
15933 Duplex = Duplex || _dereq_(85);
15934
15935 options = options || {};
15936
15937 // Duplex streams are both readable and writable, but share
15938 // the same options object.
15939 // However, some cases require setting options to different
15940 // values for the readable and the writable sides of the duplex stream.
15941 // These options can be provided separately as readableXXX and writableXXX.
15942 var isDuplex = stream instanceof Duplex;
15943
15944 // object stream flag to indicate whether or not this stream
15945 // contains buffers or objects.
15946 this.objectMode = !!options.objectMode;
15947
15948 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
15949
15950 // the point at which write() starts returning false
15951 // Note: 0 is a valid value, means that we always return false if
15952 // the entire buffer is not flushed immediately on write()
15953 var hwm = options.highWaterMark;
15954 var writableHwm = options.writableHighWaterMark;
15955 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
15956
15957 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
15958
15959 // cast to ints.
15960 this.highWaterMark = Math.floor(this.highWaterMark);
15961
15962 // if _final has been called
15963 this.finalCalled = false;
15964
15965 // drain event flag.
15966 this.needDrain = false;
15967 // at the start of calling end()
15968 this.ending = false;
15969 // when end() has been called, and returned
15970 this.ended = false;
15971 // when 'finish' is emitted
15972 this.finished = false;
15973
15974 // has it been destroyed
15975 this.destroyed = false;
15976
15977 // should we decode strings into buffers before passing to _write?
15978 // this is here so that some node-core streams can optimize string
15979 // handling at a lower level.
15980 var noDecode = options.decodeStrings === false;
15981 this.decodeStrings = !noDecode;
15982
15983 // Crypto is kind of old and crusty. Historically, its default string
15984 // encoding is 'binary' so we have to make this configurable.
15985 // Everything else in the universe uses 'utf8', though.
15986 this.defaultEncoding = options.defaultEncoding || 'utf8';
15987
15988 // not an actual buffer we keep track of, but a measurement
15989 // of how much we're waiting to get pushed to some underlying
15990 // socket or file.
15991 this.length = 0;
15992
15993 // a flag to see when we're in the middle of a write.
15994 this.writing = false;
15995
15996 // when true all writes will be buffered until .uncork() call
15997 this.corked = 0;
15998
15999 // a flag to be able to tell if the onwrite cb is called immediately,
16000 // or on a later tick. We set this to true at first, because any
16001 // actions that shouldn't happen until "later" should generally also
16002 // not happen before the first write call.
16003 this.sync = true;
16004
16005 // a flag to know if we're processing previously buffered items, which
16006 // may call the _write() callback in the same tick, so that we don't
16007 // end up in an overlapped onwrite situation.
16008 this.bufferProcessing = false;
16009
16010 // the callback that's passed to _write(chunk,cb)
16011 this.onwrite = function (er) {
16012 onwrite(stream, er);
16013 };
16014
16015 // the callback that the user supplies to write(chunk,encoding,cb)
16016 this.writecb = null;
16017
16018 // the amount that is being written when _write is called.
16019 this.writelen = 0;
16020
16021 this.bufferedRequest = null;
16022 this.lastBufferedRequest = null;
16023
16024 // number of pending user-supplied write callbacks
16025 // this must be 0 before 'finish' can be emitted
16026 this.pendingcb = 0;
16027
16028 // emit prefinish if the only thing we're waiting for is _write cbs
16029 // This is relevant for synchronous Transform streams
16030 this.prefinished = false;
16031
16032 // True if the error was already emitted and should not be thrown again
16033 this.errorEmitted = false;
16034
16035 // count buffered requests
16036 this.bufferedRequestCount = 0;
16037
16038 // allocate the first CorkedRequest, there is always
16039 // one allocated and free to use, and we maintain at most two
16040 this.corkedRequestsFree = new CorkedRequest(this);
16041}
16042
16043WritableState.prototype.getBuffer = function getBuffer() {
16044 var current = this.bufferedRequest;
16045 var out = [];
16046 while (current) {
16047 out.push(current);
16048 current = current.next;
16049 }
16050 return out;
16051};
16052
16053(function () {
16054 try {
16055 Object.defineProperty(WritableState.prototype, 'buffer', {
16056 get: internalUtil.deprecate(function () {
16057 return this.getBuffer();
16058 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
16059 });
16060 } catch (_) {}
16061})();
16062
16063// Test _writableState for inheritance to account for Duplex streams,
16064// whose prototype chain only points to Readable.
16065var realHasInstance;
16066if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
16067 realHasInstance = Function.prototype[Symbol.hasInstance];
16068 Object.defineProperty(Writable, Symbol.hasInstance, {
16069 value: function (object) {
16070 if (realHasInstance.call(this, object)) return true;
16071 if (this !== Writable) return false;
16072
16073 return object && object._writableState instanceof WritableState;
16074 }
16075 });
16076} else {
16077 realHasInstance = function (object) {
16078 return object instanceof this;
16079 };
16080}
16081
16082function Writable(options) {
16083 Duplex = Duplex || _dereq_(85);
16084
16085 // Writable ctor is applied to Duplexes, too.
16086 // `realHasInstance` is necessary because using plain `instanceof`
16087 // would return false, as no `_writableState` property is attached.
16088
16089 // Trying to use the custom `instanceof` for Writable here will also break the
16090 // Node.js LazyTransform implementation, which has a non-trivial getter for
16091 // `_writableState` that would lead to infinite recursion.
16092 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
16093 return new Writable(options);
16094 }
16095
16096 this._writableState = new WritableState(options, this);
16097
16098 // legacy.
16099 this.writable = true;
16100
16101 if (options) {
16102 if (typeof options.write === 'function') this._write = options.write;
16103
16104 if (typeof options.writev === 'function') this._writev = options.writev;
16105
16106 if (typeof options.destroy === 'function') this._destroy = options.destroy;
16107
16108 if (typeof options.final === 'function') this._final = options.final;
16109 }
16110
16111 Stream.call(this);
16112}
16113
16114// Otherwise people can pipe Writable streams, which is just wrong.
16115Writable.prototype.pipe = function () {
16116 this.emit('error', new Error('Cannot pipe, not readable'));
16117};
16118
16119function writeAfterEnd(stream, cb) {
16120 var er = new Error('write after end');
16121 // TODO: defer error events consistently everywhere, not just the cb
16122 stream.emit('error', er);
16123 pna.nextTick(cb, er);
16124}
16125
16126// Checks that a user-supplied chunk is valid, especially for the particular
16127// mode the stream is in. Currently this means that `null` is never accepted
16128// and undefined/non-string values are only allowed in object mode.
16129function validChunk(stream, state, chunk, cb) {
16130 var valid = true;
16131 var er = false;
16132
16133 if (chunk === null) {
16134 er = new TypeError('May not write null values to stream');
16135 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
16136 er = new TypeError('Invalid non-string/buffer chunk');
16137 }
16138 if (er) {
16139 stream.emit('error', er);
16140 pna.nextTick(cb, er);
16141 valid = false;
16142 }
16143 return valid;
16144}
16145
16146Writable.prototype.write = function (chunk, encoding, cb) {
16147 var state = this._writableState;
16148 var ret = false;
16149 var isBuf = !state.objectMode && _isUint8Array(chunk);
16150
16151 if (isBuf && !Buffer.isBuffer(chunk)) {
16152 chunk = _uint8ArrayToBuffer(chunk);
16153 }
16154
16155 if (typeof encoding === 'function') {
16156 cb = encoding;
16157 encoding = null;
16158 }
16159
16160 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
16161
16162 if (typeof cb !== 'function') cb = nop;
16163
16164 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
16165 state.pendingcb++;
16166 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
16167 }
16168
16169 return ret;
16170};
16171
16172Writable.prototype.cork = function () {
16173 var state = this._writableState;
16174
16175 state.corked++;
16176};
16177
16178Writable.prototype.uncork = function () {
16179 var state = this._writableState;
16180
16181 if (state.corked) {
16182 state.corked--;
16183
16184 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
16185 }
16186};
16187
16188Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
16189 // node::ParseEncoding() requires lower case.
16190 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
16191 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);
16192 this._writableState.defaultEncoding = encoding;
16193 return this;
16194};
16195
16196function decodeChunk(state, chunk, encoding) {
16197 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
16198 chunk = Buffer.from(chunk, encoding);
16199 }
16200 return chunk;
16201}
16202
16203Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
16204 // making it explicit this property is not enumerable
16205 // because otherwise some prototype manipulation in
16206 // userland will fail
16207 enumerable: false,
16208 get: function () {
16209 return this._writableState.highWaterMark;
16210 }
16211});
16212
16213// if we're already writing something, then just put this
16214// in the queue, and wait our turn. Otherwise, call _write
16215// If we return false, then we need a drain event, so set that flag.
16216function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
16217 if (!isBuf) {
16218 var newChunk = decodeChunk(state, chunk, encoding);
16219 if (chunk !== newChunk) {
16220 isBuf = true;
16221 encoding = 'buffer';
16222 chunk = newChunk;
16223 }
16224 }
16225 var len = state.objectMode ? 1 : chunk.length;
16226
16227 state.length += len;
16228
16229 var ret = state.length < state.highWaterMark;
16230 // we must ensure that previous needDrain will not be reset to false.
16231 if (!ret) state.needDrain = true;
16232
16233 if (state.writing || state.corked) {
16234 var last = state.lastBufferedRequest;
16235 state.lastBufferedRequest = {
16236 chunk: chunk,
16237 encoding: encoding,
16238 isBuf: isBuf,
16239 callback: cb,
16240 next: null
16241 };
16242 if (last) {
16243 last.next = state.lastBufferedRequest;
16244 } else {
16245 state.bufferedRequest = state.lastBufferedRequest;
16246 }
16247 state.bufferedRequestCount += 1;
16248 } else {
16249 doWrite(stream, state, false, len, chunk, encoding, cb);
16250 }
16251
16252 return ret;
16253}
16254
16255function doWrite(stream, state, writev, len, chunk, encoding, cb) {
16256 state.writelen = len;
16257 state.writecb = cb;
16258 state.writing = true;
16259 state.sync = true;
16260 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
16261 state.sync = false;
16262}
16263
16264function onwriteError(stream, state, sync, er, cb) {
16265 --state.pendingcb;
16266
16267 if (sync) {
16268 // defer the callback if we are being called synchronously
16269 // to avoid piling up things on the stack
16270 pna.nextTick(cb, er);
16271 // this can emit finish, and it will always happen
16272 // after error
16273 pna.nextTick(finishMaybe, stream, state);
16274 stream._writableState.errorEmitted = true;
16275 stream.emit('error', er);
16276 } else {
16277 // the caller expect this to happen before if
16278 // it is async
16279 cb(er);
16280 stream._writableState.errorEmitted = true;
16281 stream.emit('error', er);
16282 // this can emit finish, but finish must
16283 // always follow error
16284 finishMaybe(stream, state);
16285 }
16286}
16287
16288function onwriteStateUpdate(state) {
16289 state.writing = false;
16290 state.writecb = null;
16291 state.length -= state.writelen;
16292 state.writelen = 0;
16293}
16294
16295function onwrite(stream, er) {
16296 var state = stream._writableState;
16297 var sync = state.sync;
16298 var cb = state.writecb;
16299
16300 onwriteStateUpdate(state);
16301
16302 if (er) onwriteError(stream, state, sync, er, cb);else {
16303 // Check if we're actually ready to finish, but don't emit yet
16304 var finished = needFinish(state);
16305
16306 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
16307 clearBuffer(stream, state);
16308 }
16309
16310 if (sync) {
16311 /*<replacement>*/
16312 asyncWrite(afterWrite, stream, state, finished, cb);
16313 /*</replacement>*/
16314 } else {
16315 afterWrite(stream, state, finished, cb);
16316 }
16317 }
16318}
16319
16320function afterWrite(stream, state, finished, cb) {
16321 if (!finished) onwriteDrain(stream, state);
16322 state.pendingcb--;
16323 cb();
16324 finishMaybe(stream, state);
16325}
16326
16327// Must force callback to be called on nextTick, so that we don't
16328// emit 'drain' before the write() consumer gets the 'false' return
16329// value, and has a chance to attach a 'drain' listener.
16330function onwriteDrain(stream, state) {
16331 if (state.length === 0 && state.needDrain) {
16332 state.needDrain = false;
16333 stream.emit('drain');
16334 }
16335}
16336
16337// if there's something in the buffer waiting, then process it
16338function clearBuffer(stream, state) {
16339 state.bufferProcessing = true;
16340 var entry = state.bufferedRequest;
16341
16342 if (stream._writev && entry && entry.next) {
16343 // Fast case, write everything using _writev()
16344 var l = state.bufferedRequestCount;
16345 var buffer = new Array(l);
16346 var holder = state.corkedRequestsFree;
16347 holder.entry = entry;
16348
16349 var count = 0;
16350 var allBuffers = true;
16351 while (entry) {
16352 buffer[count] = entry;
16353 if (!entry.isBuf) allBuffers = false;
16354 entry = entry.next;
16355 count += 1;
16356 }
16357 buffer.allBuffers = allBuffers;
16358
16359 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
16360
16361 // doWrite is almost always async, defer these to save a bit of time
16362 // as the hot path ends with doWrite
16363 state.pendingcb++;
16364 state.lastBufferedRequest = null;
16365 if (holder.next) {
16366 state.corkedRequestsFree = holder.next;
16367 holder.next = null;
16368 } else {
16369 state.corkedRequestsFree = new CorkedRequest(state);
16370 }
16371 state.bufferedRequestCount = 0;
16372 } else {
16373 // Slow case, write chunks one-by-one
16374 while (entry) {
16375 var chunk = entry.chunk;
16376 var encoding = entry.encoding;
16377 var cb = entry.callback;
16378 var len = state.objectMode ? 1 : chunk.length;
16379
16380 doWrite(stream, state, false, len, chunk, encoding, cb);
16381 entry = entry.next;
16382 state.bufferedRequestCount--;
16383 // if we didn't call the onwrite immediately, then
16384 // it means that we need to wait until it does.
16385 // also, that means that the chunk and cb are currently
16386 // being processed, so move the buffer counter past them.
16387 if (state.writing) {
16388 break;
16389 }
16390 }
16391
16392 if (entry === null) state.lastBufferedRequest = null;
16393 }
16394
16395 state.bufferedRequest = entry;
16396 state.bufferProcessing = false;
16397}
16398
16399Writable.prototype._write = function (chunk, encoding, cb) {
16400 cb(new Error('_write() is not implemented'));
16401};
16402
16403Writable.prototype._writev = null;
16404
16405Writable.prototype.end = function (chunk, encoding, cb) {
16406 var state = this._writableState;
16407
16408 if (typeof chunk === 'function') {
16409 cb = chunk;
16410 chunk = null;
16411 encoding = null;
16412 } else if (typeof encoding === 'function') {
16413 cb = encoding;
16414 encoding = null;
16415 }
16416
16417 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
16418
16419 // .end() fully uncorks
16420 if (state.corked) {
16421 state.corked = 1;
16422 this.uncork();
16423 }
16424
16425 // ignore unnecessary end() calls.
16426 if (!state.ending && !state.finished) endWritable(this, state, cb);
16427};
16428
16429function needFinish(state) {
16430 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
16431}
16432function callFinal(stream, state) {
16433 stream._final(function (err) {
16434 state.pendingcb--;
16435 if (err) {
16436 stream.emit('error', err);
16437 }
16438 state.prefinished = true;
16439 stream.emit('prefinish');
16440 finishMaybe(stream, state);
16441 });
16442}
16443function prefinish(stream, state) {
16444 if (!state.prefinished && !state.finalCalled) {
16445 if (typeof stream._final === 'function') {
16446 state.pendingcb++;
16447 state.finalCalled = true;
16448 pna.nextTick(callFinal, stream, state);
16449 } else {
16450 state.prefinished = true;
16451 stream.emit('prefinish');
16452 }
16453 }
16454}
16455
16456function finishMaybe(stream, state) {
16457 var need = needFinish(state);
16458 if (need) {
16459 prefinish(stream, state);
16460 if (state.pendingcb === 0) {
16461 state.finished = true;
16462 stream.emit('finish');
16463 }
16464 }
16465 return need;
16466}
16467
16468function endWritable(stream, state, cb) {
16469 state.ending = true;
16470 finishMaybe(stream, state);
16471 if (cb) {
16472 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
16473 }
16474 state.ended = true;
16475 stream.writable = false;
16476}
16477
16478function onCorkedFinish(corkReq, state, err) {
16479 var entry = corkReq.entry;
16480 corkReq.entry = null;
16481 while (entry) {
16482 var cb = entry.callback;
16483 state.pendingcb--;
16484 cb(err);
16485 entry = entry.next;
16486 }
16487 if (state.corkedRequestsFree) {
16488 state.corkedRequestsFree.next = corkReq;
16489 } else {
16490 state.corkedRequestsFree = corkReq;
16491 }
16492}
16493
16494Object.defineProperty(Writable.prototype, 'destroyed', {
16495 get: function () {
16496 if (this._writableState === undefined) {
16497 return false;
16498 }
16499 return this._writableState.destroyed;
16500 },
16501 set: function (value) {
16502 // we ignore the value if the stream
16503 // has not been initialized yet
16504 if (!this._writableState) {
16505 return;
16506 }
16507
16508 // backward compatibility, the user is explicitly
16509 // managing destroyed
16510 this._writableState.destroyed = value;
16511 }
16512});
16513
16514Writable.prototype.destroy = destroyImpl.destroy;
16515Writable.prototype._undestroy = destroyImpl.undestroy;
16516Writable.prototype._destroy = function (err, cb) {
16517 this.end();
16518 cb(err);
16519};
16520}).call(this,_dereq_(71),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(115).setImmediate)
16521},{"10":10,"115":115,"116":116,"25":25,"70":70,"71":71,"80":80,"85":85,"91":91,"92":92}],90:[function(_dereq_,module,exports){
16522'use strict';
16523
16524function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16525
16526var Buffer = _dereq_(80).Buffer;
16527var util = _dereq_(7);
16528
16529function copyBuffer(src, target, offset) {
16530 src.copy(target, offset);
16531}
16532
16533module.exports = function () {
16534 function BufferList() {
16535 _classCallCheck(this, BufferList);
16536
16537 this.head = null;
16538 this.tail = null;
16539 this.length = 0;
16540 }
16541
16542 BufferList.prototype.push = function push(v) {
16543 var entry = { data: v, next: null };
16544 if (this.length > 0) this.tail.next = entry;else this.head = entry;
16545 this.tail = entry;
16546 ++this.length;
16547 };
16548
16549 BufferList.prototype.unshift = function unshift(v) {
16550 var entry = { data: v, next: this.head };
16551 if (this.length === 0) this.tail = entry;
16552 this.head = entry;
16553 ++this.length;
16554 };
16555
16556 BufferList.prototype.shift = function shift() {
16557 if (this.length === 0) return;
16558 var ret = this.head.data;
16559 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
16560 --this.length;
16561 return ret;
16562 };
16563
16564 BufferList.prototype.clear = function clear() {
16565 this.head = this.tail = null;
16566 this.length = 0;
16567 };
16568
16569 BufferList.prototype.join = function join(s) {
16570 if (this.length === 0) return '';
16571 var p = this.head;
16572 var ret = '' + p.data;
16573 while (p = p.next) {
16574 ret += s + p.data;
16575 }return ret;
16576 };
16577
16578 BufferList.prototype.concat = function concat(n) {
16579 if (this.length === 0) return Buffer.alloc(0);
16580 if (this.length === 1) return this.head.data;
16581 var ret = Buffer.allocUnsafe(n >>> 0);
16582 var p = this.head;
16583 var i = 0;
16584 while (p) {
16585 copyBuffer(p.data, ret, i);
16586 i += p.data.length;
16587 p = p.next;
16588 }
16589 return ret;
16590 };
16591
16592 return BufferList;
16593}();
16594
16595if (util && util.inspect && util.inspect.custom) {
16596 module.exports.prototype[util.inspect.custom] = function () {
16597 var obj = util.inspect({ length: this.length });
16598 return this.constructor.name + ' ' + obj;
16599 };
16600}
16601},{"7":7,"80":80}],91:[function(_dereq_,module,exports){
16602'use strict';
16603
16604/*<replacement>*/
16605
16606var pna = _dereq_(70);
16607/*</replacement>*/
16608
16609// undocumented cb() API, needed for core, not for public API
16610function destroy(err, cb) {
16611 var _this = this;
16612
16613 var readableDestroyed = this._readableState && this._readableState.destroyed;
16614 var writableDestroyed = this._writableState && this._writableState.destroyed;
16615
16616 if (readableDestroyed || writableDestroyed) {
16617 if (cb) {
16618 cb(err);
16619 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
16620 pna.nextTick(emitErrorNT, this, err);
16621 }
16622 return this;
16623 }
16624
16625 // we set destroyed to true before firing error callbacks in order
16626 // to make it re-entrance safe in case destroy() is called within callbacks
16627
16628 if (this._readableState) {
16629 this._readableState.destroyed = true;
16630 }
16631
16632 // if this is a duplex stream mark the writable part as destroyed as well
16633 if (this._writableState) {
16634 this._writableState.destroyed = true;
16635 }
16636
16637 this._destroy(err || null, function (err) {
16638 if (!cb && err) {
16639 pna.nextTick(emitErrorNT, _this, err);
16640 if (_this._writableState) {
16641 _this._writableState.errorEmitted = true;
16642 }
16643 } else if (cb) {
16644 cb(err);
16645 }
16646 });
16647
16648 return this;
16649}
16650
16651function undestroy() {
16652 if (this._readableState) {
16653 this._readableState.destroyed = false;
16654 this._readableState.reading = false;
16655 this._readableState.ended = false;
16656 this._readableState.endEmitted = false;
16657 }
16658
16659 if (this._writableState) {
16660 this._writableState.destroyed = false;
16661 this._writableState.ended = false;
16662 this._writableState.ending = false;
16663 this._writableState.finished = false;
16664 this._writableState.errorEmitted = false;
16665 }
16666}
16667
16668function emitErrorNT(self, err) {
16669 self.emit('error', err);
16670}
16671
16672module.exports = {
16673 destroy: destroy,
16674 undestroy: undestroy
16675};
16676},{"70":70}],92:[function(_dereq_,module,exports){
16677arguments[4][45][0].apply(exports,arguments)
16678},{"21":21,"45":45}],93:[function(_dereq_,module,exports){
16679module.exports = _dereq_(94).PassThrough
16680
16681},{"94":94}],94:[function(_dereq_,module,exports){
16682exports = module.exports = _dereq_(87);
16683exports.Stream = exports;
16684exports.Readable = exports;
16685exports.Writable = _dereq_(89);
16686exports.Duplex = _dereq_(85);
16687exports.Transform = _dereq_(88);
16688exports.PassThrough = _dereq_(86);
16689
16690},{"85":85,"86":86,"87":87,"88":88,"89":89}],95:[function(_dereq_,module,exports){
16691module.exports = _dereq_(94).Transform
16692
16693},{"94":94}],96:[function(_dereq_,module,exports){
16694module.exports = _dereq_(89);
16695
16696},{"89":89}],97:[function(_dereq_,module,exports){
16697// Copyright Joyent, Inc. and other Node contributors.
16698//
16699// Permission is hereby granted, free of charge, to any person obtaining a
16700// copy of this software and associated documentation files (the
16701// "Software"), to deal in the Software without restriction, including
16702// without limitation the rights to use, copy, modify, merge, publish,
16703// distribute, sublicense, and/or sell copies of the Software, and to permit
16704// persons to whom the Software is furnished to do so, subject to the
16705// following conditions:
16706//
16707// The above copyright notice and this permission notice shall be included
16708// in all copies or substantial portions of the Software.
16709//
16710// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16711// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16712// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16713// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16714// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16715// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16716// USE OR OTHER DEALINGS IN THE SOFTWARE.
16717
16718'use strict';
16719
16720/*<replacement>*/
16721
16722var Buffer = _dereq_(80).Buffer;
16723/*</replacement>*/
16724
16725var isEncoding = Buffer.isEncoding || function (encoding) {
16726 encoding = '' + encoding;
16727 switch (encoding && encoding.toLowerCase()) {
16728 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':
16729 return true;
16730 default:
16731 return false;
16732 }
16733};
16734
16735function _normalizeEncoding(enc) {
16736 if (!enc) return 'utf8';
16737 var retried;
16738 while (true) {
16739 switch (enc) {
16740 case 'utf8':
16741 case 'utf-8':
16742 return 'utf8';
16743 case 'ucs2':
16744 case 'ucs-2':
16745 case 'utf16le':
16746 case 'utf-16le':
16747 return 'utf16le';
16748 case 'latin1':
16749 case 'binary':
16750 return 'latin1';
16751 case 'base64':
16752 case 'ascii':
16753 case 'hex':
16754 return enc;
16755 default:
16756 if (retried) return; // undefined
16757 enc = ('' + enc).toLowerCase();
16758 retried = true;
16759 }
16760 }
16761};
16762
16763// Do not cache `Buffer.isEncoding` when checking encoding names as some
16764// modules monkey-patch it to support additional encodings
16765function normalizeEncoding(enc) {
16766 var nenc = _normalizeEncoding(enc);
16767 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16768 return nenc || enc;
16769}
16770
16771// StringDecoder provides an interface for efficiently splitting a series of
16772// buffers into a series of JS strings without breaking apart multi-byte
16773// characters.
16774exports.StringDecoder = StringDecoder;
16775function StringDecoder(encoding) {
16776 this.encoding = normalizeEncoding(encoding);
16777 var nb;
16778 switch (this.encoding) {
16779 case 'utf16le':
16780 this.text = utf16Text;
16781 this.end = utf16End;
16782 nb = 4;
16783 break;
16784 case 'utf8':
16785 this.fillLast = utf8FillLast;
16786 nb = 4;
16787 break;
16788 case 'base64':
16789 this.text = base64Text;
16790 this.end = base64End;
16791 nb = 3;
16792 break;
16793 default:
16794 this.write = simpleWrite;
16795 this.end = simpleEnd;
16796 return;
16797 }
16798 this.lastNeed = 0;
16799 this.lastTotal = 0;
16800 this.lastChar = Buffer.allocUnsafe(nb);
16801}
16802
16803StringDecoder.prototype.write = function (buf) {
16804 if (buf.length === 0) return '';
16805 var r;
16806 var i;
16807 if (this.lastNeed) {
16808 r = this.fillLast(buf);
16809 if (r === undefined) return '';
16810 i = this.lastNeed;
16811 this.lastNeed = 0;
16812 } else {
16813 i = 0;
16814 }
16815 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
16816 return r || '';
16817};
16818
16819StringDecoder.prototype.end = utf8End;
16820
16821// Returns only complete characters in a Buffer
16822StringDecoder.prototype.text = utf8Text;
16823
16824// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
16825StringDecoder.prototype.fillLast = function (buf) {
16826 if (this.lastNeed <= buf.length) {
16827 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
16828 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16829 }
16830 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
16831 this.lastNeed -= buf.length;
16832};
16833
16834// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
16835// continuation byte. If an invalid byte is detected, -2 is returned.
16836function utf8CheckByte(byte) {
16837 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;
16838 return byte >> 6 === 0x02 ? -1 : -2;
16839}
16840
16841// Checks at most 3 bytes at the end of a Buffer in order to detect an
16842// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
16843// needed to complete the UTF-8 character (if applicable) are returned.
16844function utf8CheckIncomplete(self, buf, i) {
16845 var j = buf.length - 1;
16846 if (j < i) return 0;
16847 var nb = utf8CheckByte(buf[j]);
16848 if (nb >= 0) {
16849 if (nb > 0) self.lastNeed = nb - 1;
16850 return nb;
16851 }
16852 if (--j < i || nb === -2) return 0;
16853 nb = utf8CheckByte(buf[j]);
16854 if (nb >= 0) {
16855 if (nb > 0) self.lastNeed = nb - 2;
16856 return nb;
16857 }
16858 if (--j < i || nb === -2) return 0;
16859 nb = utf8CheckByte(buf[j]);
16860 if (nb >= 0) {
16861 if (nb > 0) {
16862 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
16863 }
16864 return nb;
16865 }
16866 return 0;
16867}
16868
16869// Validates as many continuation bytes for a multi-byte UTF-8 character as
16870// needed or are available. If we see a non-continuation byte where we expect
16871// one, we "replace" the validated continuation bytes we've seen so far with
16872// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
16873// behavior. The continuation byte check is included three times in the case
16874// where all of the continuation bytes for a character exist in the same buffer.
16875// It is also done this way as a slight performance increase instead of using a
16876// loop.
16877function utf8CheckExtraBytes(self, buf, p) {
16878 if ((buf[0] & 0xC0) !== 0x80) {
16879 self.lastNeed = 0;
16880 return '\ufffd';
16881 }
16882 if (self.lastNeed > 1 && buf.length > 1) {
16883 if ((buf[1] & 0xC0) !== 0x80) {
16884 self.lastNeed = 1;
16885 return '\ufffd';
16886 }
16887 if (self.lastNeed > 2 && buf.length > 2) {
16888 if ((buf[2] & 0xC0) !== 0x80) {
16889 self.lastNeed = 2;
16890 return '\ufffd';
16891 }
16892 }
16893 }
16894}
16895
16896// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
16897function utf8FillLast(buf) {
16898 var p = this.lastTotal - this.lastNeed;
16899 var r = utf8CheckExtraBytes(this, buf, p);
16900 if (r !== undefined) return r;
16901 if (this.lastNeed <= buf.length) {
16902 buf.copy(this.lastChar, p, 0, this.lastNeed);
16903 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
16904 }
16905 buf.copy(this.lastChar, p, 0, buf.length);
16906 this.lastNeed -= buf.length;
16907}
16908
16909// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
16910// partial character, the character's bytes are buffered until the required
16911// number of bytes are available.
16912function utf8Text(buf, i) {
16913 var total = utf8CheckIncomplete(this, buf, i);
16914 if (!this.lastNeed) return buf.toString('utf8', i);
16915 this.lastTotal = total;
16916 var end = buf.length - (total - this.lastNeed);
16917 buf.copy(this.lastChar, 0, end);
16918 return buf.toString('utf8', i, end);
16919}
16920
16921// For UTF-8, a replacement character is added when ending on a partial
16922// character.
16923function utf8End(buf) {
16924 var r = buf && buf.length ? this.write(buf) : '';
16925 if (this.lastNeed) return r + '\ufffd';
16926 return r;
16927}
16928
16929// UTF-16LE typically needs two bytes per character, but even if we have an even
16930// number of bytes available, we need to check if we end on a leading/high
16931// surrogate. In that case, we need to wait for the next two bytes in order to
16932// decode the last character properly.
16933function utf16Text(buf, i) {
16934 if ((buf.length - i) % 2 === 0) {
16935 var r = buf.toString('utf16le', i);
16936 if (r) {
16937 var c = r.charCodeAt(r.length - 1);
16938 if (c >= 0xD800 && c <= 0xDBFF) {
16939 this.lastNeed = 2;
16940 this.lastTotal = 4;
16941 this.lastChar[0] = buf[buf.length - 2];
16942 this.lastChar[1] = buf[buf.length - 1];
16943 return r.slice(0, -1);
16944 }
16945 }
16946 return r;
16947 }
16948 this.lastNeed = 1;
16949 this.lastTotal = 2;
16950 this.lastChar[0] = buf[buf.length - 1];
16951 return buf.toString('utf16le', i, buf.length - 1);
16952}
16953
16954// For UTF-16LE we do not explicitly append special replacement characters if we
16955// end on a partial character, we simply let v8 handle that.
16956function utf16End(buf) {
16957 var r = buf && buf.length ? this.write(buf) : '';
16958 if (this.lastNeed) {
16959 var end = this.lastTotal - this.lastNeed;
16960 return r + this.lastChar.toString('utf16le', 0, end);
16961 }
16962 return r;
16963}
16964
16965function base64Text(buf, i) {
16966 var n = (buf.length - i) % 3;
16967 if (n === 0) return buf.toString('base64', i);
16968 this.lastNeed = 3 - n;
16969 this.lastTotal = 3;
16970 if (n === 1) {
16971 this.lastChar[0] = buf[buf.length - 1];
16972 } else {
16973 this.lastChar[0] = buf[buf.length - 2];
16974 this.lastChar[1] = buf[buf.length - 1];
16975 }
16976 return buf.toString('base64', i, buf.length - n);
16977}
16978
16979function base64End(buf) {
16980 var r = buf && buf.length ? this.write(buf) : '';
16981 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
16982 return r;
16983}
16984
16985// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
16986function simpleWrite(buf) {
16987 return buf.toString(this.encoding);
16988}
16989
16990function simpleEnd(buf) {
16991 return buf && buf.length ? this.write(buf) : '';
16992}
16993},{"80":80}],98:[function(_dereq_,module,exports){
16994arguments[4][97][0].apply(exports,arguments)
16995},{"80":80,"97":97}],99:[function(_dereq_,module,exports){
16996arguments[4][32][0].apply(exports,arguments)
16997},{"32":32}],100:[function(_dereq_,module,exports){
16998arguments[4][33][0].apply(exports,arguments)
16999},{"33":33,"71":71}],101:[function(_dereq_,module,exports){
17000arguments[4][34][0].apply(exports,arguments)
17001},{"103":103,"105":105,"25":25,"34":34,"71":71}],102:[function(_dereq_,module,exports){
17002arguments[4][35][0].apply(exports,arguments)
17003},{"104":104,"25":25,"35":35}],103:[function(_dereq_,module,exports){
17004arguments[4][36][0].apply(exports,arguments)
17005},{"100":100,"101":101,"106":106,"107":107,"108":108,"111":111,"112":112,"21":21,"25":25,"36":36,"7":7,"71":71,"9":9,"98":98,"99":99}],104:[function(_dereq_,module,exports){
17006arguments[4][37][0].apply(exports,arguments)
17007},{"101":101,"25":25,"37":37,"99":99}],105:[function(_dereq_,module,exports){
17008arguments[4][38][0].apply(exports,arguments)
17009},{"101":101,"108":108,"111":111,"112":112,"116":116,"25":25,"38":38,"71":71,"9":9,"99":99}],106:[function(_dereq_,module,exports){
17010arguments[4][39][0].apply(exports,arguments)
17011},{"109":109,"39":39,"71":71}],107:[function(_dereq_,module,exports){
17012arguments[4][40][0].apply(exports,arguments)
17013},{"40":40,"7":7,"9":9}],108:[function(_dereq_,module,exports){
17014arguments[4][41][0].apply(exports,arguments)
17015},{"41":41,"71":71}],109:[function(_dereq_,module,exports){
17016arguments[4][42][0].apply(exports,arguments)
17017},{"42":42,"99":99}],110:[function(_dereq_,module,exports){
17018arguments[4][43][0].apply(exports,arguments)
17019},{"109":109,"43":43,"99":99}],111:[function(_dereq_,module,exports){
17020arguments[4][44][0].apply(exports,arguments)
17021},{"44":44,"99":99}],112:[function(_dereq_,module,exports){
17022arguments[4][45][0].apply(exports,arguments)
17023},{"21":21,"45":45}],113:[function(_dereq_,module,exports){
17024arguments[4][46][0].apply(exports,arguments)
17025},{"101":101,"102":102,"103":103,"104":104,"105":105,"109":109,"110":110,"46":46}],114:[function(_dereq_,module,exports){
17026(function (process){
17027var Transform = _dereq_(113).Transform
17028 , inherits = _dereq_(118).inherits
17029
17030function DestroyableTransform(opts) {
17031 Transform.call(this, opts)
17032 this._destroyed = false
17033}
17034
17035inherits(DestroyableTransform, Transform)
17036
17037DestroyableTransform.prototype.destroy = function(err) {
17038 if (this._destroyed) return
17039 this._destroyed = true
17040
17041 var self = this
17042 process.nextTick(function() {
17043 if (err)
17044 self.emit('error', err)
17045 self.emit('close')
17046 })
17047}
17048
17049// a noop _transform function
17050function noop (chunk, enc, callback) {
17051 callback(null, chunk)
17052}
17053
17054
17055// create a new export function, used by both the main export and
17056// the .ctor export, contains common logic for dealing with arguments
17057function through2 (construct) {
17058 return function (options, transform, flush) {
17059 if (typeof options == 'function') {
17060 flush = transform
17061 transform = options
17062 options = {}
17063 }
17064
17065 if (typeof transform != 'function')
17066 transform = noop
17067
17068 if (typeof flush != 'function')
17069 flush = null
17070
17071 return construct(options, transform, flush)
17072 }
17073}
17074
17075
17076// main export, just make me a transform stream!
17077module.exports = through2(function (options, transform, flush) {
17078 var t2 = new DestroyableTransform(options)
17079
17080 t2._transform = transform
17081
17082 if (flush)
17083 t2._flush = flush
17084
17085 return t2
17086})
17087
17088
17089// make me a reusable prototype that I can `new`, or implicitly `new`
17090// with a constructor call
17091module.exports.ctor = through2(function (options, transform, flush) {
17092 function Through2 (override) {
17093 if (!(this instanceof Through2))
17094 return new Through2(override)
17095
17096 this.options = Object.assign({}, options, override)
17097
17098 DestroyableTransform.call(this, this.options)
17099 }
17100
17101 inherits(Through2, DestroyableTransform)
17102
17103 Through2.prototype._transform = transform
17104
17105 if (flush)
17106 Through2.prototype._flush = flush
17107
17108 return Through2
17109})
17110
17111
17112module.exports.obj = through2(function (options, transform, flush) {
17113 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
17114
17115 t2._transform = transform
17116
17117 if (flush)
17118 t2._flush = flush
17119
17120 return t2
17121})
17122
17123}).call(this,_dereq_(71))
17124},{"113":113,"118":118,"71":71}],115:[function(_dereq_,module,exports){
17125(function (setImmediate,clearImmediate){
17126var nextTick = _dereq_(71).nextTick;
17127var apply = Function.prototype.apply;
17128var slice = Array.prototype.slice;
17129var immediateIds = {};
17130var nextImmediateId = 0;
17131
17132// DOM APIs, for completeness
17133
17134exports.setTimeout = function() {
17135 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
17136};
17137exports.setInterval = function() {
17138 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
17139};
17140exports.clearTimeout =
17141exports.clearInterval = function(timeout) { timeout.close(); };
17142
17143function Timeout(id, clearFn) {
17144 this._id = id;
17145 this._clearFn = clearFn;
17146}
17147Timeout.prototype.unref = Timeout.prototype.ref = function() {};
17148Timeout.prototype.close = function() {
17149 this._clearFn.call(window, this._id);
17150};
17151
17152// Does not start the time, just sets up the members needed.
17153exports.enroll = function(item, msecs) {
17154 clearTimeout(item._idleTimeoutId);
17155 item._idleTimeout = msecs;
17156};
17157
17158exports.unenroll = function(item) {
17159 clearTimeout(item._idleTimeoutId);
17160 item._idleTimeout = -1;
17161};
17162
17163exports._unrefActive = exports.active = function(item) {
17164 clearTimeout(item._idleTimeoutId);
17165
17166 var msecs = item._idleTimeout;
17167 if (msecs >= 0) {
17168 item._idleTimeoutId = setTimeout(function onTimeout() {
17169 if (item._onTimeout)
17170 item._onTimeout();
17171 }, msecs);
17172 }
17173};
17174
17175// That's not how node.js implements it but the exposed api is the same.
17176exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
17177 var id = nextImmediateId++;
17178 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
17179
17180 immediateIds[id] = true;
17181
17182 nextTick(function onNextTick() {
17183 if (immediateIds[id]) {
17184 // fn.call() is faster so we optimize for the common use-case
17185 // @see http://jsperf.com/call-apply-segu
17186 if (args) {
17187 fn.apply(null, args);
17188 } else {
17189 fn.call(null);
17190 }
17191 // Prevent ids from leaking
17192 exports.clearImmediate(id);
17193 }
17194 });
17195
17196 return id;
17197};
17198
17199exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
17200 delete immediateIds[id];
17201};
17202}).call(this,_dereq_(115).setImmediate,_dereq_(115).clearImmediate)
17203},{"115":115,"71":71}],116:[function(_dereq_,module,exports){
17204(function (global){
17205
17206/**
17207 * Module exports.
17208 */
17209
17210module.exports = deprecate;
17211
17212/**
17213 * Mark that a method should not be used.
17214 * Returns a modified function which warns once by default.
17215 *
17216 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
17217 *
17218 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
17219 * will throw an Error when invoked.
17220 *
17221 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
17222 * will invoke `console.trace()` instead of `console.error()`.
17223 *
17224 * @param {Function} fn - the function to deprecate
17225 * @param {String} msg - the string to print to the console when `fn` is invoked
17226 * @returns {Function} a new "deprecated" version of `fn`
17227 * @api public
17228 */
17229
17230function deprecate (fn, msg) {
17231 if (config('noDeprecation')) {
17232 return fn;
17233 }
17234
17235 var warned = false;
17236 function deprecated() {
17237 if (!warned) {
17238 if (config('throwDeprecation')) {
17239 throw new Error(msg);
17240 } else if (config('traceDeprecation')) {
17241 console.trace(msg);
17242 } else {
17243 console.warn(msg);
17244 }
17245 warned = true;
17246 }
17247 return fn.apply(this, arguments);
17248 }
17249
17250 return deprecated;
17251}
17252
17253/**
17254 * Checks `localStorage` for boolean values for the given `name`.
17255 *
17256 * @param {String} name
17257 * @returns {Boolean}
17258 * @api private
17259 */
17260
17261function config (name) {
17262 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
17263 try {
17264 if (!global.localStorage) return false;
17265 } catch (_) {
17266 return false;
17267 }
17268 var val = global.localStorage[name];
17269 if (null == val) return false;
17270 return String(val).toLowerCase() === 'true';
17271}
17272
17273}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17274},{}],117:[function(_dereq_,module,exports){
17275arguments[4][4][0].apply(exports,arguments)
17276},{"4":4}],118:[function(_dereq_,module,exports){
17277arguments[4][5][0].apply(exports,arguments)
17278},{"117":117,"25":25,"5":5,"71":71}],119:[function(_dereq_,module,exports){
17279var v1 = _dereq_(122);
17280var v4 = _dereq_(123);
17281
17282var uuid = v4;
17283uuid.v1 = v1;
17284uuid.v4 = v4;
17285
17286module.exports = uuid;
17287
17288},{"122":122,"123":123}],120:[function(_dereq_,module,exports){
17289/**
17290 * Convert array of 16 byte values to UUID string format of the form:
17291 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
17292 */
17293var byteToHex = [];
17294for (var i = 0; i < 256; ++i) {
17295 byteToHex[i] = (i + 0x100).toString(16).substr(1);
17296}
17297
17298function bytesToUuid(buf, offset) {
17299 var i = offset || 0;
17300 var bth = byteToHex;
17301 return bth[buf[i++]] + bth[buf[i++]] +
17302 bth[buf[i++]] + bth[buf[i++]] + '-' +
17303 bth[buf[i++]] + bth[buf[i++]] + '-' +
17304 bth[buf[i++]] + bth[buf[i++]] + '-' +
17305 bth[buf[i++]] + bth[buf[i++]] + '-' +
17306 bth[buf[i++]] + bth[buf[i++]] +
17307 bth[buf[i++]] + bth[buf[i++]] +
17308 bth[buf[i++]] + bth[buf[i++]];
17309}
17310
17311module.exports = bytesToUuid;
17312
17313},{}],121:[function(_dereq_,module,exports){
17314// Unique ID creation requires a high quality random # generator. In the
17315// browser this is a little complicated due to unknown quality of Math.random()
17316// and inconsistent support for the `crypto` API. We do the best we can via
17317// feature-detection
17318
17319// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
17320var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||
17321 (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));
17322if (getRandomValues) {
17323 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
17324 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
17325
17326 module.exports = function whatwgRNG() {
17327 getRandomValues(rnds8);
17328 return rnds8;
17329 };
17330} else {
17331 // Math.random()-based (RNG)
17332 //
17333 // If all else fails, use Math.random(). It's fast, but is of unspecified
17334 // quality.
17335 var rnds = new Array(16);
17336
17337 module.exports = function mathRNG() {
17338 for (var i = 0, r; i < 16; i++) {
17339 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
17340 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
17341 }
17342
17343 return rnds;
17344 };
17345}
17346
17347},{}],122:[function(_dereq_,module,exports){
17348var rng = _dereq_(121);
17349var bytesToUuid = _dereq_(120);
17350
17351// **`v1()` - Generate time-based UUID**
17352//
17353// Inspired by https://github.com/LiosK/UUID.js
17354// and http://docs.python.org/library/uuid.html
17355
17356var _nodeId;
17357var _clockseq;
17358
17359// Previous uuid creation time
17360var _lastMSecs = 0;
17361var _lastNSecs = 0;
17362
17363// See https://github.com/broofa/node-uuid for API details
17364function v1(options, buf, offset) {
17365 var i = buf && offset || 0;
17366 var b = buf || [];
17367
17368 options = options || {};
17369 var node = options.node || _nodeId;
17370 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
17371
17372 // node and clockseq need to be initialized to random values if they're not
17373 // specified. We do this lazily to minimize issues related to insufficient
17374 // system entropy. See #189
17375 if (node == null || clockseq == null) {
17376 var seedBytes = rng();
17377 if (node == null) {
17378 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
17379 node = _nodeId = [
17380 seedBytes[0] | 0x01,
17381 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
17382 ];
17383 }
17384 if (clockseq == null) {
17385 // Per 4.2.2, randomize (14 bit) clockseq
17386 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
17387 }
17388 }
17389
17390 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
17391 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
17392 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
17393 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
17394 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
17395
17396 // Per 4.2.1.2, use count of uuid's generated during the current clock
17397 // cycle to simulate higher resolution clock
17398 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
17399
17400 // Time since last uuid creation (in msecs)
17401 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
17402
17403 // Per 4.2.1.2, Bump clockseq on clock regression
17404 if (dt < 0 && options.clockseq === undefined) {
17405 clockseq = clockseq + 1 & 0x3fff;
17406 }
17407
17408 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
17409 // time interval
17410 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
17411 nsecs = 0;
17412 }
17413
17414 // Per 4.2.1.2 Throw error if too many uuids are requested
17415 if (nsecs >= 10000) {
17416 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
17417 }
17418
17419 _lastMSecs = msecs;
17420 _lastNSecs = nsecs;
17421 _clockseq = clockseq;
17422
17423 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
17424 msecs += 12219292800000;
17425
17426 // `time_low`
17427 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
17428 b[i++] = tl >>> 24 & 0xff;
17429 b[i++] = tl >>> 16 & 0xff;
17430 b[i++] = tl >>> 8 & 0xff;
17431 b[i++] = tl & 0xff;
17432
17433 // `time_mid`
17434 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
17435 b[i++] = tmh >>> 8 & 0xff;
17436 b[i++] = tmh & 0xff;
17437
17438 // `time_high_and_version`
17439 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
17440 b[i++] = tmh >>> 16 & 0xff;
17441
17442 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
17443 b[i++] = clockseq >>> 8 | 0x80;
17444
17445 // `clock_seq_low`
17446 b[i++] = clockseq & 0xff;
17447
17448 // `node`
17449 for (var n = 0; n < 6; ++n) {
17450 b[i + n] = node[n];
17451 }
17452
17453 return buf ? buf : bytesToUuid(b);
17454}
17455
17456module.exports = v1;
17457
17458},{"120":120,"121":121}],123:[function(_dereq_,module,exports){
17459var rng = _dereq_(121);
17460var bytesToUuid = _dereq_(120);
17461
17462function v4(options, buf, offset) {
17463 var i = buf && offset || 0;
17464
17465 if (typeof(options) == 'string') {
17466 buf = options === 'binary' ? new Array(16) : null;
17467 options = null;
17468 }
17469 options = options || {};
17470
17471 var rnds = options.random || (options.rng || rng)();
17472
17473 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
17474 rnds[6] = (rnds[6] & 0x0f) | 0x40;
17475 rnds[8] = (rnds[8] & 0x3f) | 0x80;
17476
17477 // Copy bytes to buffer, if provided
17478 if (buf) {
17479 for (var ii = 0; ii < 16; ++ii) {
17480 buf[i + ii] = rnds[ii];
17481 }
17482 }
17483
17484 return buf || bytesToUuid(rnds);
17485}
17486
17487module.exports = v4;
17488
17489},{"120":120,"121":121}],124:[function(_dereq_,module,exports){
17490'use strict';
17491
17492/**
17493 * Stringify/parse functions that don't operate
17494 * recursively, so they avoid call stack exceeded
17495 * errors.
17496 */
17497exports.stringify = function stringify(input) {
17498 var queue = [];
17499 queue.push({obj: input});
17500
17501 var res = '';
17502 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
17503 while ((next = queue.pop())) {
17504 obj = next.obj;
17505 prefix = next.prefix || '';
17506 val = next.val || '';
17507 res += prefix;
17508 if (val) {
17509 res += val;
17510 } else if (typeof obj !== 'object') {
17511 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
17512 } else if (obj === null) {
17513 res += 'null';
17514 } else if (Array.isArray(obj)) {
17515 queue.push({val: ']'});
17516 for (i = obj.length - 1; i >= 0; i--) {
17517 arrayPrefix = i === 0 ? '' : ',';
17518 queue.push({obj: obj[i], prefix: arrayPrefix});
17519 }
17520 queue.push({val: '['});
17521 } else { // object
17522 keys = [];
17523 for (k in obj) {
17524 if (obj.hasOwnProperty(k)) {
17525 keys.push(k);
17526 }
17527 }
17528 queue.push({val: '}'});
17529 for (i = keys.length - 1; i >= 0; i--) {
17530 key = keys[i];
17531 value = obj[key];
17532 objPrefix = (i > 0 ? ',' : '');
17533 objPrefix += JSON.stringify(key) + ':';
17534 queue.push({obj: value, prefix: objPrefix});
17535 }
17536 queue.push({val: '{'});
17537 }
17538 }
17539 return res;
17540};
17541
17542// Convenience function for the parse function.
17543// This pop function is basically copied from
17544// pouchCollate.parseIndexableString
17545function pop(obj, stack, metaStack) {
17546 var lastMetaElement = metaStack[metaStack.length - 1];
17547 if (obj === lastMetaElement.element) {
17548 // popping a meta-element, e.g. an object whose value is another object
17549 metaStack.pop();
17550 lastMetaElement = metaStack[metaStack.length - 1];
17551 }
17552 var element = lastMetaElement.element;
17553 var lastElementIndex = lastMetaElement.index;
17554 if (Array.isArray(element)) {
17555 element.push(obj);
17556 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
17557 var key = stack.pop();
17558 element[key] = obj;
17559 } else {
17560 stack.push(obj); // obj with key only
17561 }
17562}
17563
17564exports.parse = function (str) {
17565 var stack = [];
17566 var metaStack = []; // stack for arrays and objects
17567 var i = 0;
17568 var collationIndex,parsedNum,numChar;
17569 var parsedString,lastCh,numConsecutiveSlashes,ch;
17570 var arrayElement, objElement;
17571 while (true) {
17572 collationIndex = str[i++];
17573 if (collationIndex === '}' ||
17574 collationIndex === ']' ||
17575 typeof collationIndex === 'undefined') {
17576 if (stack.length === 1) {
17577 return stack.pop();
17578 } else {
17579 pop(stack.pop(), stack, metaStack);
17580 continue;
17581 }
17582 }
17583 switch (collationIndex) {
17584 case ' ':
17585 case '\t':
17586 case '\n':
17587 case ':':
17588 case ',':
17589 break;
17590 case 'n':
17591 i += 3; // 'ull'
17592 pop(null, stack, metaStack);
17593 break;
17594 case 't':
17595 i += 3; // 'rue'
17596 pop(true, stack, metaStack);
17597 break;
17598 case 'f':
17599 i += 4; // 'alse'
17600 pop(false, stack, metaStack);
17601 break;
17602 case '0':
17603 case '1':
17604 case '2':
17605 case '3':
17606 case '4':
17607 case '5':
17608 case '6':
17609 case '7':
17610 case '8':
17611 case '9':
17612 case '-':
17613 parsedNum = '';
17614 i--;
17615 while (true) {
17616 numChar = str[i++];
17617 if (/[\d\.\-e\+]/.test(numChar)) {
17618 parsedNum += numChar;
17619 } else {
17620 i--;
17621 break;
17622 }
17623 }
17624 pop(parseFloat(parsedNum), stack, metaStack);
17625 break;
17626 case '"':
17627 parsedString = '';
17628 lastCh = void 0;
17629 numConsecutiveSlashes = 0;
17630 while (true) {
17631 ch = str[i++];
17632 if (ch !== '"' || (lastCh === '\\' &&
17633 numConsecutiveSlashes % 2 === 1)) {
17634 parsedString += ch;
17635 lastCh = ch;
17636 if (lastCh === '\\') {
17637 numConsecutiveSlashes++;
17638 } else {
17639 numConsecutiveSlashes = 0;
17640 }
17641 } else {
17642 break;
17643 }
17644 }
17645 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
17646 break;
17647 case '[':
17648 arrayElement = { element: [], index: stack.length };
17649 stack.push(arrayElement.element);
17650 metaStack.push(arrayElement);
17651 break;
17652 case '{':
17653 objElement = { element: {}, index: stack.length };
17654 stack.push(objElement.element);
17655 metaStack.push(objElement);
17656 break;
17657 default:
17658 throw new Error(
17659 'unexpectedly reached end of input: ' + collationIndex);
17660 }
17661 }
17662};
17663
17664},{}],125:[function(_dereq_,module,exports){
17665(function (global){
17666'use strict';
17667
17668function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
17669
17670var immediate = _interopDefault(_dereq_(24));
17671var uuidV4 = _interopDefault(_dereq_(119));
17672var Md5 = _interopDefault(_dereq_(81));
17673var levelup = _interopDefault(_dereq_(50));
17674var ltgt = _interopDefault(_dereq_(53));
17675var events = _dereq_(21);
17676var events__default = _interopDefault(events);
17677var Codec = _interopDefault(_dereq_(28));
17678var ReadableStreamCore = _interopDefault(_dereq_(79));
17679var inherits = _interopDefault(_dereq_(25));
17680var through2 = _dereq_(114);
17681var getArguments = _interopDefault(_dereq_(1));
17682var Deque = _interopDefault(_dereq_(18));
17683var bufferFrom = _interopDefault(_dereq_(8));
17684var vuvuzela = _interopDefault(_dereq_(124));
17685var memdown = _interopDefault(_dereq_(55));
17686
17687function isBinaryObject(object) {
17688 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
17689 (typeof Blob !== 'undefined' && object instanceof Blob);
17690}
17691
17692function cloneArrayBuffer(buff) {
17693 if (typeof buff.slice === 'function') {
17694 return buff.slice(0);
17695 }
17696 // IE10-11 slice() polyfill
17697 var target = new ArrayBuffer(buff.byteLength);
17698 var targetArray = new Uint8Array(target);
17699 var sourceArray = new Uint8Array(buff);
17700 targetArray.set(sourceArray);
17701 return target;
17702}
17703
17704function cloneBinaryObject(object) {
17705 if (object instanceof ArrayBuffer) {
17706 return cloneArrayBuffer(object);
17707 }
17708 var size = object.size;
17709 var type = object.type;
17710 // Blob
17711 if (typeof object.slice === 'function') {
17712 return object.slice(0, size, type);
17713 }
17714 // PhantomJS slice() replacement
17715 return object.webkitSlice(0, size, type);
17716}
17717
17718// most of this is borrowed from lodash.isPlainObject:
17719// https://github.com/fis-components/lodash.isplainobject/
17720// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
17721
17722var funcToString = Function.prototype.toString;
17723var objectCtorString = funcToString.call(Object);
17724
17725function isPlainObject(value) {
17726 var proto = Object.getPrototypeOf(value);
17727 /* istanbul ignore if */
17728 if (proto === null) { // not sure when this happens, but I guess it can
17729 return true;
17730 }
17731 var Ctor = proto.constructor;
17732 return (typeof Ctor == 'function' &&
17733 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
17734}
17735
17736function clone(object) {
17737 var newObject;
17738 var i;
17739 var len;
17740
17741 if (!object || typeof object !== 'object') {
17742 return object;
17743 }
17744
17745 if (Array.isArray(object)) {
17746 newObject = [];
17747 for (i = 0, len = object.length; i < len; i++) {
17748 newObject[i] = clone(object[i]);
17749 }
17750 return newObject;
17751 }
17752
17753 // special case: to avoid inconsistencies between IndexedDB
17754 // and other backends, we automatically stringify Dates
17755 if (object instanceof Date) {
17756 return object.toISOString();
17757 }
17758
17759 if (isBinaryObject(object)) {
17760 return cloneBinaryObject(object);
17761 }
17762
17763 if (!isPlainObject(object)) {
17764 return object; // don't clone objects like Workers
17765 }
17766
17767 newObject = {};
17768 for (i in object) {
17769 /* istanbul ignore else */
17770 if (Object.prototype.hasOwnProperty.call(object, i)) {
17771 var value = clone(object[i]);
17772 if (typeof value !== 'undefined') {
17773 newObject[i] = value;
17774 }
17775 }
17776 }
17777 return newObject;
17778}
17779
17780function mangle(key) {
17781 return '$' + key;
17782}
17783function unmangle(key) {
17784 return key.substring(1);
17785}
17786function Map$1() {
17787 this._store = {};
17788}
17789Map$1.prototype.get = function (key) {
17790 var mangled = mangle(key);
17791 return this._store[mangled];
17792};
17793Map$1.prototype.set = function (key, value) {
17794 var mangled = mangle(key);
17795 this._store[mangled] = value;
17796 return true;
17797};
17798Map$1.prototype.has = function (key) {
17799 var mangled = mangle(key);
17800 return mangled in this._store;
17801};
17802Map$1.prototype["delete"] = function (key) {
17803 var mangled = mangle(key);
17804 var res = mangled in this._store;
17805 delete this._store[mangled];
17806 return res;
17807};
17808Map$1.prototype.forEach = function (cb) {
17809 var keys = Object.keys(this._store);
17810 for (var i = 0, len = keys.length; i < len; i++) {
17811 var key = keys[i];
17812 var value = this._store[key];
17813 key = unmangle(key);
17814 cb(value, key);
17815 }
17816};
17817Object.defineProperty(Map$1.prototype, 'size', {
17818 get: function () {
17819 return Object.keys(this._store).length;
17820 }
17821});
17822
17823function Set$1(array) {
17824 this._store = new Map$1();
17825
17826 // init with an array
17827 if (array && Array.isArray(array)) {
17828 for (var i = 0, len = array.length; i < len; i++) {
17829 this.add(array[i]);
17830 }
17831 }
17832}
17833Set$1.prototype.add = function (key) {
17834 return this._store.set(key, true);
17835};
17836Set$1.prototype.has = function (key) {
17837 return this._store.has(key);
17838};
17839Set$1.prototype.forEach = function (cb) {
17840 this._store.forEach(function (value, key) {
17841 cb(key);
17842 });
17843};
17844Object.defineProperty(Set$1.prototype, 'size', {
17845 get: function () {
17846 return this._store.size;
17847 }
17848});
17849
17850/* global Map,Set,Symbol */
17851// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
17852// incomplete Map/Set implementations which would otherwise cause our tests to fail.
17853// Notably they fail in IE11 and iOS 8.4, which this prevents.
17854function supportsMapAndSet() {
17855 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
17856 return false;
17857 }
17858 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
17859 return prop && 'get' in prop && Map[Symbol.species] === Map;
17860}
17861
17862// based on https://github.com/montagejs/collections
17863
17864var ExportedSet;
17865var ExportedMap;
17866
17867{
17868 if (supportsMapAndSet()) { // prefer built-in Map/Set
17869 ExportedSet = Set;
17870 ExportedMap = Map;
17871 } else { // fall back to our polyfill
17872 ExportedSet = Set$1;
17873 ExportedMap = Map$1;
17874 }
17875}
17876
17877// like underscore/lodash _.pick()
17878function pick(obj, arr) {
17879 var res = {};
17880 for (var i = 0, len = arr.length; i < len; i++) {
17881 var prop = arr[i];
17882 if (prop in obj) {
17883 res[prop] = obj[prop];
17884 }
17885 }
17886 return res;
17887}
17888
17889var hasLocal;
17890
17891try {
17892 localStorage.setItem('_pouch_check_localstorage', 1);
17893 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
17894} catch (e) {
17895 hasLocal = false;
17896}
17897
17898function hasLocalStorage() {
17899 return hasLocal;
17900}
17901
17902// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
17903
17904inherits(Changes, events.EventEmitter);
17905
17906/* istanbul ignore next */
17907function attachBrowserEvents(self) {
17908 if (hasLocalStorage()) {
17909 addEventListener("storage", function (e) {
17910 self.emit(e.key);
17911 });
17912 }
17913}
17914
17915function Changes() {
17916 events.EventEmitter.call(this);
17917 this._listeners = {};
17918
17919 attachBrowserEvents(this);
17920}
17921Changes.prototype.addListener = function (dbName, id, db, opts) {
17922 /* istanbul ignore if */
17923 if (this._listeners[id]) {
17924 return;
17925 }
17926 var self = this;
17927 var inprogress = false;
17928 function eventFunction() {
17929 /* istanbul ignore if */
17930 if (!self._listeners[id]) {
17931 return;
17932 }
17933 if (inprogress) {
17934 inprogress = 'waiting';
17935 return;
17936 }
17937 inprogress = true;
17938 var changesOpts = pick(opts, [
17939 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
17940 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
17941 ]);
17942
17943 /* istanbul ignore next */
17944 function onError() {
17945 inprogress = false;
17946 }
17947
17948 db.changes(changesOpts).on('change', function (c) {
17949 if (c.seq > opts.since && !opts.cancelled) {
17950 opts.since = c.seq;
17951 opts.onChange(c);
17952 }
17953 }).on('complete', function () {
17954 if (inprogress === 'waiting') {
17955 immediate(eventFunction);
17956 }
17957 inprogress = false;
17958 }).on('error', onError);
17959 }
17960 this._listeners[id] = eventFunction;
17961 this.on(dbName, eventFunction);
17962};
17963
17964Changes.prototype.removeListener = function (dbName, id) {
17965 /* istanbul ignore if */
17966 if (!(id in this._listeners)) {
17967 return;
17968 }
17969 events.EventEmitter.prototype.removeListener.call(this, dbName,
17970 this._listeners[id]);
17971 delete this._listeners[id];
17972};
17973
17974
17975/* istanbul ignore next */
17976Changes.prototype.notifyLocalWindows = function (dbName) {
17977 //do a useless change on a storage thing
17978 //in order to get other windows's listeners to activate
17979 if (hasLocalStorage()) {
17980 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
17981 }
17982};
17983
17984Changes.prototype.notify = function (dbName) {
17985 this.emit(dbName);
17986 this.notifyLocalWindows(dbName);
17987};
17988
17989function guardedConsole(method) {
17990 /* istanbul ignore else */
17991 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
17992 var args = Array.prototype.slice.call(arguments, 1);
17993 console[method].apply(console, args);
17994 }
17995}
17996
17997var assign;
17998{
17999 if (typeof Object.assign === 'function') {
18000 assign = Object.assign;
18001 } else {
18002 // lite Object.assign polyfill based on
18003 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
18004 assign = function (target) {
18005 var to = Object(target);
18006
18007 for (var index = 1; index < arguments.length; index++) {
18008 var nextSource = arguments[index];
18009
18010 if (nextSource != null) { // Skip over if undefined or null
18011 for (var nextKey in nextSource) {
18012 // Avoid bugs when hasOwnProperty is shadowed
18013 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
18014 to[nextKey] = nextSource[nextKey];
18015 }
18016 }
18017 }
18018 }
18019 return to;
18020 };
18021 }
18022}
18023
18024var $inject_Object_assign = assign;
18025
18026inherits(PouchError, Error);
18027
18028function PouchError(status, error, reason) {
18029 Error.call(this, reason);
18030 this.status = status;
18031 this.name = error;
18032 this.message = reason;
18033 this.error = true;
18034}
18035
18036PouchError.prototype.toString = function () {
18037 return JSON.stringify({
18038 status: this.status,
18039 name: this.name,
18040 message: this.message,
18041 reason: this.reason
18042 });
18043};
18044
18045var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
18046var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
18047var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
18048var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
18049var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
18050var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
18051var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
18052var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
18053var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
18054var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
18055var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
18056var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
18057var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
18058var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
18059var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
18060var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
18061var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
18062var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
18063var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
18064var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
18065var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
18066var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
18067var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
18068var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
18069
18070function createError(error, reason) {
18071 function CustomPouchError(reason) {
18072 // inherit error properties from our parent error manually
18073 // so as to allow proper JSON parsing.
18074 /* jshint ignore:start */
18075 for (var p in error) {
18076 if (typeof error[p] !== 'function') {
18077 this[p] = error[p];
18078 }
18079 }
18080 /* jshint ignore:end */
18081 if (reason !== undefined) {
18082 this.reason = reason;
18083 }
18084 }
18085 CustomPouchError.prototype = PouchError.prototype;
18086 return new CustomPouchError(reason);
18087}
18088
18089function tryFilter(filter, doc, req) {
18090 try {
18091 return !filter(doc, req);
18092 } catch (err) {
18093 var msg = 'Filter function threw: ' + err.toString();
18094 return createError(BAD_REQUEST, msg);
18095 }
18096}
18097
18098function filterChange(opts) {
18099 var req = {};
18100 var hasFilter = opts.filter && typeof opts.filter === 'function';
18101 req.query = opts.query_params;
18102
18103 return function filter(change) {
18104 if (!change.doc) {
18105 // CSG sends events on the changes feed that don't have documents,
18106 // this hack makes a whole lot of existing code robust.
18107 change.doc = {};
18108 }
18109
18110 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
18111
18112 if (typeof filterReturn === 'object') {
18113 return filterReturn;
18114 }
18115
18116 if (filterReturn) {
18117 return false;
18118 }
18119
18120 if (!opts.include_docs) {
18121 delete change.doc;
18122 } else if (!opts.attachments) {
18123 for (var att in change.doc._attachments) {
18124 /* istanbul ignore else */
18125 if (change.doc._attachments.hasOwnProperty(att)) {
18126 change.doc._attachments[att].stub = true;
18127 }
18128 }
18129 }
18130 return true;
18131 };
18132}
18133
18134// shim for Function.prototype.name,
18135// for browsers that don't support it like IE
18136
18137/* istanbul ignore next */
18138function f() {}
18139
18140var hasName = f.name;
18141var res;
18142
18143// We dont run coverage in IE
18144/* istanbul ignore else */
18145if (hasName) {
18146 res = function (fun) {
18147 return fun.name;
18148 };
18149} else {
18150 res = function (fun) {
18151 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
18152 if (match && match[1]) {
18153 return match[1];
18154 }
18155 else {
18156 return '';
18157 }
18158 };
18159}
18160
18161var functionName = res;
18162
18163// Determine id an ID is valid
18164// - invalid IDs begin with an underescore that does not begin '_design' or
18165// '_local'
18166// - any other string value is a valid id
18167// Returns the specific error object for each case
18168function invalidIdError(id) {
18169 var err;
18170 if (!id) {
18171 err = createError(MISSING_ID);
18172 } else if (typeof id !== 'string') {
18173 err = createError(INVALID_ID);
18174 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
18175 err = createError(RESERVED_ID);
18176 }
18177 if (err) {
18178 throw err;
18179 }
18180}
18181
18182// Checks if a PouchDB object is "remote" or not. This is
18183
18184// originally parseUri 1.2.2, now patched by us
18185
18186// Based on https://github.com/alexdavid/scope-eval v0.0.3
18187
18188var thisAtob = function (str) {
18189 return atob(str);
18190};
18191
18192var thisBtoa = function (str) {
18193 return btoa(str);
18194};
18195
18196// Abstracts constructing a Blob object, so it also works in older
18197// browsers that don't support the native Blob constructor (e.g.
18198// old QtWebKit versions, Android < 4.4).
18199function createBlob(parts, properties) {
18200 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
18201 parts = parts || [];
18202 properties = properties || {};
18203 try {
18204 return new Blob(parts, properties);
18205 } catch (e) {
18206 if (e.name !== "TypeError") {
18207 throw e;
18208 }
18209 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
18210 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
18211 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
18212 WebKitBlobBuilder;
18213 var builder = new Builder();
18214 for (var i = 0; i < parts.length; i += 1) {
18215 builder.append(parts[i]);
18216 }
18217 return builder.getBlob(properties.type);
18218 }
18219}
18220
18221// From http://stackoverflow.com/questions/14967647/ (continues on next line)
18222// encode-decode-image-with-base64-breaks-image (2013-04-21)
18223function binaryStringToArrayBuffer(bin) {
18224 var length = bin.length;
18225 var buf = new ArrayBuffer(length);
18226 var arr = new Uint8Array(buf);
18227 for (var i = 0; i < length; i++) {
18228 arr[i] = bin.charCodeAt(i);
18229 }
18230 return buf;
18231}
18232
18233function binStringToBluffer(binString, type) {
18234 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
18235}
18236
18237//Can't find original post, but this is close
18238//http://stackoverflow.com/questions/6965107/ (continues on next line)
18239//converting-between-strings-and-arraybuffers
18240function arrayBufferToBinaryString(buffer) {
18241 var binary = '';
18242 var bytes = new Uint8Array(buffer);
18243 var length = bytes.byteLength;
18244 for (var i = 0; i < length; i++) {
18245 binary += String.fromCharCode(bytes[i]);
18246 }
18247 return binary;
18248}
18249
18250// shim for browsers that don't support it
18251function readAsBinaryString(blob, callback) {
18252 var reader = new FileReader();
18253 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
18254 reader.onloadend = function (e) {
18255 var result = e.target.result || '';
18256 if (hasBinaryString) {
18257 return callback(result);
18258 }
18259 callback(arrayBufferToBinaryString(result));
18260 };
18261 if (hasBinaryString) {
18262 reader.readAsBinaryString(blob);
18263 } else {
18264 reader.readAsArrayBuffer(blob);
18265 }
18266}
18267
18268// simplified API. universal browser support is assumed
18269function readAsArrayBuffer(blob, callback) {
18270 var reader = new FileReader();
18271 reader.onloadend = function (e) {
18272 var result = e.target.result || new ArrayBuffer(0);
18273 callback(result);
18274 };
18275 reader.readAsArrayBuffer(blob);
18276}
18277
18278// this is not used in the browser
18279
18280var setImmediateShim = global.setImmediate || global.setTimeout;
18281var MD5_CHUNK_SIZE = 32768;
18282
18283function rawToBase64(raw) {
18284 return thisBtoa(raw);
18285}
18286
18287function sliceBlob(blob, start, end) {
18288 if (blob.webkitSlice) {
18289 return blob.webkitSlice(start, end);
18290 }
18291 return blob.slice(start, end);
18292}
18293
18294function appendBlob(buffer, blob, start, end, callback) {
18295 if (start > 0 || end < blob.size) {
18296 // only slice blob if we really need to
18297 blob = sliceBlob(blob, start, end);
18298 }
18299 readAsArrayBuffer(blob, function (arrayBuffer) {
18300 buffer.append(arrayBuffer);
18301 callback();
18302 });
18303}
18304
18305function appendString(buffer, string, start, end, callback) {
18306 if (start > 0 || end < string.length) {
18307 // only create a substring if we really need to
18308 string = string.substring(start, end);
18309 }
18310 buffer.appendBinary(string);
18311 callback();
18312}
18313
18314function binaryMd5(data, callback) {
18315 var inputIsString = typeof data === 'string';
18316 var len = inputIsString ? data.length : data.size;
18317 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
18318 var chunks = Math.ceil(len / chunkSize);
18319 var currentChunk = 0;
18320 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
18321
18322 var append = inputIsString ? appendString : appendBlob;
18323
18324 function next() {
18325 setImmediateShim(loadNextChunk);
18326 }
18327
18328 function done() {
18329 var raw = buffer.end(true);
18330 var base64 = rawToBase64(raw);
18331 callback(base64);
18332 buffer.destroy();
18333 }
18334
18335 function loadNextChunk() {
18336 var start = currentChunk * chunkSize;
18337 var end = start + chunkSize;
18338 currentChunk++;
18339 if (currentChunk < chunks) {
18340 append(buffer, data, start, end, next);
18341 } else {
18342 append(buffer, data, start, end, done);
18343 }
18344 }
18345 loadNextChunk();
18346}
18347
18348function stringMd5(string) {
18349 return Md5.hash(string);
18350}
18351
18352function rev(doc, deterministic_revs) {
18353 var clonedDoc = clone(doc);
18354 if (!deterministic_revs) {
18355 return uuidV4.v4().replace(/-/g, '').toLowerCase();
18356 }
18357
18358 delete clonedDoc._rev_tree;
18359 return stringMd5(JSON.stringify(clonedDoc));
18360}
18361
18362var uuid = uuidV4.v4;
18363
18364function isFunction(f) {
18365 return 'function' === typeof f;
18366}
18367
18368function getPrefix(db) {
18369 if (isFunction(db.prefix)) {
18370 return db.prefix();
18371 }
18372 return db;
18373}
18374
18375function clone$1(_obj) {
18376 var obj = {};
18377 for (var k in _obj) {
18378 obj[k] = _obj[k];
18379 }
18380 return obj;
18381}
18382
18383function nut(db, precodec, codec) {
18384 function encodePrefix(prefix, key, opts1, opts2) {
18385 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
18386 }
18387
18388 function addEncodings(op, prefix) {
18389 if (prefix && prefix.options) {
18390 op.keyEncoding =
18391 op.keyEncoding || prefix.options.keyEncoding;
18392 op.valueEncoding =
18393 op.valueEncoding || prefix.options.valueEncoding;
18394 }
18395 return op;
18396 }
18397
18398 db.open(function () { /* no-op */});
18399
18400 return {
18401 apply: function (ops, opts, cb) {
18402 opts = opts || {};
18403
18404 var batch = [];
18405 var i = -1;
18406 var len = ops.length;
18407
18408 while (++i < len) {
18409 var op = ops[i];
18410 addEncodings(op, op.prefix);
18411 op.prefix = getPrefix(op.prefix);
18412 batch.push({
18413 key: encodePrefix(op.prefix, op.key, opts, op),
18414 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
18415 type: op.type
18416 });
18417 }
18418 db.db.batch(batch, opts, cb);
18419 },
18420 get: function (key, prefix, opts, cb) {
18421 opts.asBuffer = codec.valueAsBuffer(opts);
18422 return db.db.get(
18423 encodePrefix(prefix, key, opts),
18424 opts,
18425 function (err, value) {
18426 if (err) {
18427 cb(err);
18428 } else {
18429 cb(null, codec.decodeValue(value, opts));
18430 }
18431 }
18432 );
18433 },
18434 createDecoder: function (opts) {
18435 return function (key, value) {
18436 return {
18437 key: codec.decodeKey(precodec.decode(key)[1], opts),
18438 value: codec.decodeValue(value, opts)
18439 };
18440 };
18441 },
18442 isClosed: function isClosed() {
18443 return db.isClosed();
18444 },
18445 close: function close(cb) {
18446 return db.close(cb);
18447 },
18448 iterator: function (_opts) {
18449 var opts = clone$1(_opts || {});
18450 var prefix = _opts.prefix || [];
18451
18452 function encodeKey(key) {
18453 return encodePrefix(prefix, key, opts, {});
18454 }
18455
18456 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
18457
18458 // if these legacy values are in the options, remove them
18459
18460 opts.prefix = null;
18461
18462 //************************************************
18463 //hard coded defaults, for now...
18464 //TODO: pull defaults and encoding out of levelup.
18465 opts.keyAsBuffer = opts.valueAsBuffer = false;
18466 //************************************************
18467
18468
18469 //this is vital, otherwise limit: undefined will
18470 //create an empty stream.
18471 /* istanbul ignore next */
18472 if ('number' !== typeof opts.limit) {
18473 opts.limit = -1;
18474 }
18475
18476 opts.keyAsBuffer = precodec.buffer;
18477 opts.valueAsBuffer = codec.valueAsBuffer(opts);
18478
18479 function wrapIterator(iterator) {
18480 return {
18481 next: function (cb) {
18482 return iterator.next(cb);
18483 },
18484 end: function (cb) {
18485 iterator.end(cb);
18486 }
18487 };
18488 }
18489
18490 return wrapIterator(db.db.iterator(opts));
18491 }
18492 };
18493}
18494
18495function NotFoundError() {
18496 Error.call(this);
18497}
18498
18499inherits(NotFoundError, Error);
18500
18501NotFoundError.prototype.name = 'NotFoundError';
18502
18503var EventEmitter = events__default.EventEmitter;
18504var version = "6.5.4";
18505
18506var NOT_FOUND_ERROR = new NotFoundError();
18507
18508var sublevel = function (nut, prefix, createStream, options) {
18509 var emitter = new EventEmitter();
18510 emitter.sublevels = {};
18511 emitter.options = options;
18512
18513 emitter.version = version;
18514
18515 emitter.methods = {};
18516 prefix = prefix || [];
18517
18518 function mergeOpts(opts) {
18519 var o = {};
18520 var k;
18521 if (options) {
18522 for (k in options) {
18523 if (typeof options[k] !== 'undefined') {
18524 o[k] = options[k];
18525 }
18526 }
18527 }
18528 if (opts) {
18529 for (k in opts) {
18530 if (typeof opts[k] !== 'undefined') {
18531 o[k] = opts[k];
18532 }
18533 }
18534 }
18535 return o;
18536 }
18537
18538 emitter.put = function (key, value, opts, cb) {
18539 if ('function' === typeof opts) {
18540 cb = opts;
18541 opts = {};
18542 }
18543
18544 nut.apply([{
18545 key: key, value: value,
18546 prefix: prefix.slice(), type: 'put'
18547 }], mergeOpts(opts), function (err) {
18548 /* istanbul ignore next */
18549 if (err) {
18550 return cb(err);
18551 }
18552 emitter.emit('put', key, value);
18553 cb(null);
18554 });
18555 };
18556
18557 emitter.prefix = function () {
18558 return prefix.slice();
18559 };
18560
18561 emitter.batch = function (ops, opts, cb) {
18562 if ('function' === typeof opts) {
18563 cb = opts;
18564 opts = {};
18565 }
18566
18567 ops = ops.map(function (op) {
18568 return {
18569 key: op.key,
18570 value: op.value,
18571 prefix: op.prefix || prefix,
18572 keyEncoding: op.keyEncoding, // *
18573 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
18574 type: op.type
18575 };
18576 });
18577
18578 nut.apply(ops, mergeOpts(opts), function (err) {
18579 /* istanbul ignore next */
18580 if (err) {
18581 return cb(err);
18582 }
18583 emitter.emit('batch', ops);
18584 cb(null);
18585 });
18586 };
18587
18588 emitter.get = function (key, opts, cb) {
18589 /* istanbul ignore else */
18590 if ('function' === typeof opts) {
18591 cb = opts;
18592 opts = {};
18593 }
18594 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
18595 if (err) {
18596 cb(NOT_FOUND_ERROR);
18597 } else {
18598 cb(null, value);
18599 }
18600 });
18601 };
18602
18603 emitter.sublevel = function (name, opts) {
18604 return emitter.sublevels[name] =
18605 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
18606 };
18607
18608 emitter.readStream = emitter.createReadStream = function (opts) {
18609 opts = mergeOpts(opts);
18610 opts.prefix = prefix;
18611 var stream;
18612 var it = nut.iterator(opts);
18613
18614 stream = createStream(opts, nut.createDecoder(opts));
18615 stream.setIterator(it);
18616
18617 return stream;
18618 };
18619
18620 emitter.close = function (cb) {
18621 nut.close(cb);
18622 };
18623
18624 emitter.isOpen = nut.isOpen;
18625 emitter.isClosed = nut.isClosed;
18626
18627 return emitter;
18628};
18629
18630/* Copyright (c) 2012-2014 LevelUP contributors
18631 * See list at <https://github.com/rvagg/node-levelup#contributing>
18632 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
18633 */
18634
18635var Readable = ReadableStreamCore.Readable;
18636
18637function ReadStream(options, makeData) {
18638 if (!(this instanceof ReadStream)) {
18639 return new ReadStream(options, makeData);
18640 }
18641
18642 Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });
18643
18644 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
18645
18646 this._waiting = false;
18647 this._options = options;
18648 this._makeData = makeData;
18649}
18650
18651inherits(ReadStream, Readable);
18652
18653ReadStream.prototype.setIterator = function (it) {
18654 this._iterator = it;
18655 /* istanbul ignore if */
18656 if (this._destroyed) {
18657 return it.end(function () {});
18658 }
18659 /* istanbul ignore if */
18660 if (this._waiting) {
18661 this._waiting = false;
18662 return this._read();
18663 }
18664 return this;
18665};
18666
18667ReadStream.prototype._read = function read() {
18668 var self = this;
18669 /* istanbul ignore if */
18670 if (self._destroyed) {
18671 return;
18672 }
18673 /* istanbul ignore if */
18674 if (!self._iterator) {
18675 return this._waiting = true;
18676 }
18677
18678 self._iterator.next(function (err, key, value) {
18679 if (err || (key === undefined && value === undefined)) {
18680 if (!err && !self._destroyed) {
18681 self.push(null);
18682 }
18683 return self._cleanup(err);
18684 }
18685
18686
18687 value = self._makeData(key, value);
18688 if (!self._destroyed) {
18689 self.push(value);
18690 }
18691 });
18692};
18693
18694ReadStream.prototype._cleanup = function (err) {
18695 if (this._destroyed) {
18696 return;
18697 }
18698
18699 this._destroyed = true;
18700
18701 var self = this;
18702 /* istanbul ignore if */
18703 if (err && err.message !== 'iterator has ended') {
18704 self.emit('error', err);
18705 }
18706
18707 /* istanbul ignore else */
18708 if (self._iterator) {
18709 self._iterator.end(function () {
18710 self._iterator = null;
18711 self.emit('close');
18712 });
18713 } else {
18714 self.emit('close');
18715 }
18716};
18717
18718ReadStream.prototype.destroy = function () {
18719 this._cleanup();
18720};
18721
18722var precodec = {
18723 encode: function (decodedKey) {
18724 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
18725 },
18726 decode: function (encodedKeyAsBuffer) {
18727 var str = encodedKeyAsBuffer.toString();
18728 var idx = str.indexOf('\xff', 1);
18729 return [str.substring(1, idx), str.substring(idx + 1)];
18730 },
18731 lowerBound: '\x00',
18732 upperBound: '\xff'
18733};
18734
18735var codec = new Codec();
18736
18737function sublevelPouch(db) {
18738 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
18739}
18740
18741function allDocsKeysQuery(api, opts) {
18742 var keys = opts.keys;
18743 var finalResults = {
18744 offset: opts.skip
18745 };
18746 return Promise.all(keys.map(function (key) {
18747 var subOpts = $inject_Object_assign({key: key, deleted: 'ok'}, opts);
18748 ['limit', 'skip', 'keys'].forEach(function (optKey) {
18749 delete subOpts[optKey];
18750 });
18751 return new Promise(function (resolve, reject) {
18752 api._allDocs(subOpts, function (err, res) {
18753 /* istanbul ignore if */
18754 if (err) {
18755 return reject(err);
18756 }
18757 /* istanbul ignore if */
18758 if (opts.update_seq && res.update_seq !== undefined) {
18759 finalResults.update_seq = res.update_seq;
18760 }
18761 finalResults.total_rows = res.total_rows;
18762 resolve(res.rows[0] || {key: key, error: 'not_found'});
18763 });
18764 });
18765 })).then(function (results) {
18766 finalResults.rows = results;
18767 return finalResults;
18768 });
18769}
18770
18771function toObject(array) {
18772 return array.reduce(function (obj, item) {
18773 obj[item] = true;
18774 return obj;
18775 }, {});
18776}
18777// List of top level reserved words for doc
18778var reservedWords = toObject([
18779 '_id',
18780 '_rev',
18781 '_attachments',
18782 '_deleted',
18783 '_revisions',
18784 '_revs_info',
18785 '_conflicts',
18786 '_deleted_conflicts',
18787 '_local_seq',
18788 '_rev_tree',
18789 //replication documents
18790 '_replication_id',
18791 '_replication_state',
18792 '_replication_state_time',
18793 '_replication_state_reason',
18794 '_replication_stats',
18795 // Specific to Couchbase Sync Gateway
18796 '_removed'
18797]);
18798
18799// List of reserved words that should end up the document
18800var dataWords = toObject([
18801 '_attachments',
18802 //replication documents
18803 '_replication_id',
18804 '_replication_state',
18805 '_replication_state_time',
18806 '_replication_state_reason',
18807 '_replication_stats'
18808]);
18809
18810function parseRevisionInfo(rev$$1) {
18811 if (!/^\d+-./.test(rev$$1)) {
18812 return createError(INVALID_REV);
18813 }
18814 var idx = rev$$1.indexOf('-');
18815 var left = rev$$1.substring(0, idx);
18816 var right = rev$$1.substring(idx + 1);
18817 return {
18818 prefix: parseInt(left, 10),
18819 id: right
18820 };
18821}
18822
18823function makeRevTreeFromRevisions(revisions, opts) {
18824 var pos = revisions.start - revisions.ids.length + 1;
18825
18826 var revisionIds = revisions.ids;
18827 var ids = [revisionIds[0], opts, []];
18828
18829 for (var i = 1, len = revisionIds.length; i < len; i++) {
18830 ids = [revisionIds[i], {status: 'missing'}, [ids]];
18831 }
18832
18833 return [{
18834 pos: pos,
18835 ids: ids
18836 }];
18837}
18838
18839// Preprocess documents, parse their revisions, assign an id and a
18840// revision for new writes that are missing them, etc
18841function parseDoc(doc, newEdits, dbOpts) {
18842 if (!dbOpts) {
18843 dbOpts = {
18844 deterministic_revs: true
18845 };
18846 }
18847
18848 var nRevNum;
18849 var newRevId;
18850 var revInfo;
18851 var opts = {status: 'available'};
18852 if (doc._deleted) {
18853 opts.deleted = true;
18854 }
18855
18856 if (newEdits) {
18857 if (!doc._id) {
18858 doc._id = uuid();
18859 }
18860 newRevId = rev(doc, dbOpts.deterministic_revs);
18861 if (doc._rev) {
18862 revInfo = parseRevisionInfo(doc._rev);
18863 if (revInfo.error) {
18864 return revInfo;
18865 }
18866 doc._rev_tree = [{
18867 pos: revInfo.prefix,
18868 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
18869 }];
18870 nRevNum = revInfo.prefix + 1;
18871 } else {
18872 doc._rev_tree = [{
18873 pos: 1,
18874 ids : [newRevId, opts, []]
18875 }];
18876 nRevNum = 1;
18877 }
18878 } else {
18879 if (doc._revisions) {
18880 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
18881 nRevNum = doc._revisions.start;
18882 newRevId = doc._revisions.ids[0];
18883 }
18884 if (!doc._rev_tree) {
18885 revInfo = parseRevisionInfo(doc._rev);
18886 if (revInfo.error) {
18887 return revInfo;
18888 }
18889 nRevNum = revInfo.prefix;
18890 newRevId = revInfo.id;
18891 doc._rev_tree = [{
18892 pos: nRevNum,
18893 ids: [newRevId, opts, []]
18894 }];
18895 }
18896 }
18897
18898 invalidIdError(doc._id);
18899
18900 doc._rev = nRevNum + '-' + newRevId;
18901
18902 var result = {metadata : {}, data : {}};
18903 for (var key in doc) {
18904 /* istanbul ignore else */
18905 if (Object.prototype.hasOwnProperty.call(doc, key)) {
18906 var specialKey = key[0] === '_';
18907 if (specialKey && !reservedWords[key]) {
18908 var error = createError(DOC_VALIDATION, key);
18909 error.message = DOC_VALIDATION.message + ': ' + key;
18910 throw error;
18911 } else if (specialKey && !dataWords[key]) {
18912 result.metadata[key.slice(1)] = doc[key];
18913 } else {
18914 result.data[key] = doc[key];
18915 }
18916 }
18917 }
18918 return result;
18919}
18920
18921// We fetch all leafs of the revision tree, and sort them based on tree length
18922// and whether they were deleted, undeleted documents with the longest revision
18923// tree (most edits) win
18924// The final sort algorithm is slightly documented in a sidebar here:
18925// http://guide.couchdb.org/draft/conflicts.html
18926function winningRev(metadata) {
18927 var winningId;
18928 var winningPos;
18929 var winningDeleted;
18930 var toVisit = metadata.rev_tree.slice();
18931 var node;
18932 while ((node = toVisit.pop())) {
18933 var tree = node.ids;
18934 var branches = tree[2];
18935 var pos = node.pos;
18936 if (branches.length) { // non-leaf
18937 for (var i = 0, len = branches.length; i < len; i++) {
18938 toVisit.push({pos: pos + 1, ids: branches[i]});
18939 }
18940 continue;
18941 }
18942 var deleted = !!tree[1].deleted;
18943 var id = tree[0];
18944 // sort by deleted, then pos, then id
18945 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
18946 winningPos !== pos ? winningPos < pos : winningId < id)) {
18947 winningId = id;
18948 winningPos = pos;
18949 winningDeleted = deleted;
18950 }
18951 }
18952
18953 return winningPos + '-' + winningId;
18954}
18955
18956// Pretty much all below can be combined into a higher order function to
18957// traverse revisions
18958// The return value from the callback will be passed as context to all
18959// children of that node
18960function traverseRevTree(revs, callback) {
18961 var toVisit = revs.slice();
18962
18963 var node;
18964 while ((node = toVisit.pop())) {
18965 var pos = node.pos;
18966 var tree = node.ids;
18967 var branches = tree[2];
18968 var newCtx =
18969 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
18970 for (var i = 0, len = branches.length; i < len; i++) {
18971 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
18972 }
18973 }
18974}
18975
18976function sortByPos(a, b) {
18977 return a.pos - b.pos;
18978}
18979
18980function collectLeaves(revs) {
18981 var leaves = [];
18982 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
18983 if (isLeaf) {
18984 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
18985 }
18986 });
18987 leaves.sort(sortByPos).reverse();
18988 for (var i = 0, len = leaves.length; i < len; i++) {
18989 delete leaves[i].pos;
18990 }
18991 return leaves;
18992}
18993
18994// returns revs of all conflicts that is leaves such that
18995// 1. are not deleted and
18996// 2. are different than winning revision
18997function collectConflicts(metadata) {
18998 var win = winningRev(metadata);
18999 var leaves = collectLeaves(metadata.rev_tree);
19000 var conflicts = [];
19001 for (var i = 0, len = leaves.length; i < len; i++) {
19002 var leaf = leaves[i];
19003 if (leaf.rev !== win && !leaf.opts.deleted) {
19004 conflicts.push(leaf.rev);
19005 }
19006 }
19007 return conflicts;
19008}
19009
19010// compact a tree by marking its non-leafs as missing,
19011// and return a list of revs to delete
19012function compactTree(metadata) {
19013 var revs = [];
19014 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
19015 revHash, ctx, opts) {
19016 if (opts.status === 'available' && !isLeaf) {
19017 revs.push(pos + '-' + revHash);
19018 opts.status = 'missing';
19019 }
19020 });
19021 return revs;
19022}
19023
19024// build up a list of all the paths to the leafs in this revision tree
19025function rootToLeaf(revs) {
19026 var paths = [];
19027 var toVisit = revs.slice();
19028 var node;
19029 while ((node = toVisit.pop())) {
19030 var pos = node.pos;
19031 var tree = node.ids;
19032 var id = tree[0];
19033 var opts = tree[1];
19034 var branches = tree[2];
19035 var isLeaf = branches.length === 0;
19036
19037 var history = node.history ? node.history.slice() : [];
19038 history.push({id: id, opts: opts});
19039 if (isLeaf) {
19040 paths.push({pos: (pos + 1 - history.length), ids: history});
19041 }
19042 for (var i = 0, len = branches.length; i < len; i++) {
19043 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
19044 }
19045 }
19046 return paths.reverse();
19047}
19048
19049// for a better overview of what this is doing, read:
19050
19051function sortByPos$1(a, b) {
19052 return a.pos - b.pos;
19053}
19054
19055// classic binary search
19056function binarySearch(arr, item, comparator) {
19057 var low = 0;
19058 var high = arr.length;
19059 var mid;
19060 while (low < high) {
19061 mid = (low + high) >>> 1;
19062 if (comparator(arr[mid], item) < 0) {
19063 low = mid + 1;
19064 } else {
19065 high = mid;
19066 }
19067 }
19068 return low;
19069}
19070
19071// assuming the arr is sorted, insert the item in the proper place
19072function insertSorted(arr, item, comparator) {
19073 var idx = binarySearch(arr, item, comparator);
19074 arr.splice(idx, 0, item);
19075}
19076
19077// Turn a path as a flat array into a tree with a single branch.
19078// If any should be stemmed from the beginning of the array, that's passed
19079// in as the second argument
19080function pathToTree(path, numStemmed) {
19081 var root;
19082 var leaf;
19083 for (var i = numStemmed, len = path.length; i < len; i++) {
19084 var node = path[i];
19085 var currentLeaf = [node.id, node.opts, []];
19086 if (leaf) {
19087 leaf[2].push(currentLeaf);
19088 leaf = currentLeaf;
19089 } else {
19090 root = leaf = currentLeaf;
19091 }
19092 }
19093 return root;
19094}
19095
19096// compare the IDs of two trees
19097function compareTree(a, b) {
19098 return a[0] < b[0] ? -1 : 1;
19099}
19100
19101// Merge two trees together
19102// The roots of tree1 and tree2 must be the same revision
19103function mergeTree(in_tree1, in_tree2) {
19104 var queue = [{tree1: in_tree1, tree2: in_tree2}];
19105 var conflicts = false;
19106 while (queue.length > 0) {
19107 var item = queue.pop();
19108 var tree1 = item.tree1;
19109 var tree2 = item.tree2;
19110
19111 if (tree1[1].status || tree2[1].status) {
19112 tree1[1].status =
19113 (tree1[1].status === 'available' ||
19114 tree2[1].status === 'available') ? 'available' : 'missing';
19115 }
19116
19117 for (var i = 0; i < tree2[2].length; i++) {
19118 if (!tree1[2][0]) {
19119 conflicts = 'new_leaf';
19120 tree1[2][0] = tree2[2][i];
19121 continue;
19122 }
19123
19124 var merged = false;
19125 for (var j = 0; j < tree1[2].length; j++) {
19126 if (tree1[2][j][0] === tree2[2][i][0]) {
19127 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
19128 merged = true;
19129 }
19130 }
19131 if (!merged) {
19132 conflicts = 'new_branch';
19133 insertSorted(tree1[2], tree2[2][i], compareTree);
19134 }
19135 }
19136 }
19137 return {conflicts: conflicts, tree: in_tree1};
19138}
19139
19140function doMerge(tree, path, dontExpand) {
19141 var restree = [];
19142 var conflicts = false;
19143 var merged = false;
19144 var res;
19145
19146 if (!tree.length) {
19147 return {tree: [path], conflicts: 'new_leaf'};
19148 }
19149
19150 for (var i = 0, len = tree.length; i < len; i++) {
19151 var branch = tree[i];
19152 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
19153 // Paths start at the same position and have the same root, so they need
19154 // merged
19155 res = mergeTree(branch.ids, path.ids);
19156 restree.push({pos: branch.pos, ids: res.tree});
19157 conflicts = conflicts || res.conflicts;
19158 merged = true;
19159 } else if (dontExpand !== true) {
19160 // The paths start at a different position, take the earliest path and
19161 // traverse up until it as at the same point from root as the path we
19162 // want to merge. If the keys match we return the longer path with the
19163 // other merged After stemming we dont want to expand the trees
19164
19165 var t1 = branch.pos < path.pos ? branch : path;
19166 var t2 = branch.pos < path.pos ? path : branch;
19167 var diff = t2.pos - t1.pos;
19168
19169 var candidateParents = [];
19170
19171 var trees = [];
19172 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
19173 while (trees.length > 0) {
19174 var item = trees.pop();
19175 if (item.diff === 0) {
19176 if (item.ids[0] === t2.ids[0]) {
19177 candidateParents.push(item);
19178 }
19179 continue;
19180 }
19181 var elements = item.ids[2];
19182 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
19183 trees.push({
19184 ids: elements[j],
19185 diff: item.diff - 1,
19186 parent: item.ids,
19187 parentIdx: j
19188 });
19189 }
19190 }
19191
19192 var el = candidateParents[0];
19193
19194 if (!el) {
19195 restree.push(branch);
19196 } else {
19197 res = mergeTree(el.ids, t2.ids);
19198 el.parent[2][el.parentIdx] = res.tree;
19199 restree.push({pos: t1.pos, ids: t1.ids});
19200 conflicts = conflicts || res.conflicts;
19201 merged = true;
19202 }
19203 } else {
19204 restree.push(branch);
19205 }
19206 }
19207
19208 // We didnt find
19209 if (!merged) {
19210 restree.push(path);
19211 }
19212
19213 restree.sort(sortByPos$1);
19214
19215 return {
19216 tree: restree,
19217 conflicts: conflicts || 'internal_node'
19218 };
19219}
19220
19221// To ensure we dont grow the revision tree infinitely, we stem old revisions
19222function stem(tree, depth) {
19223 // First we break out the tree into a complete list of root to leaf paths
19224 var paths = rootToLeaf(tree);
19225 var stemmedRevs;
19226
19227 var result;
19228 for (var i = 0, len = paths.length; i < len; i++) {
19229 // Then for each path, we cut off the start of the path based on the
19230 // `depth` to stem to, and generate a new set of flat trees
19231 var path = paths[i];
19232 var stemmed = path.ids;
19233 var node;
19234 if (stemmed.length > depth) {
19235 // only do the stemming work if we actually need to stem
19236 if (!stemmedRevs) {
19237 stemmedRevs = {}; // avoid allocating this object unnecessarily
19238 }
19239 var numStemmed = stemmed.length - depth;
19240 node = {
19241 pos: path.pos + numStemmed,
19242 ids: pathToTree(stemmed, numStemmed)
19243 };
19244
19245 for (var s = 0; s < numStemmed; s++) {
19246 var rev = (path.pos + s) + '-' + stemmed[s].id;
19247 stemmedRevs[rev] = true;
19248 }
19249 } else { // no need to actually stem
19250 node = {
19251 pos: path.pos,
19252 ids: pathToTree(stemmed, 0)
19253 };
19254 }
19255
19256 // Then we remerge all those flat trees together, ensuring that we dont
19257 // connect trees that would go beyond the depth limit
19258 if (result) {
19259 result = doMerge(result, node, true).tree;
19260 } else {
19261 result = [node];
19262 }
19263 }
19264
19265 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
19266 if (stemmedRevs) {
19267 traverseRevTree(result, function (isLeaf, pos, revHash) {
19268 // some revisions may have been removed in a branch but not in another
19269 delete stemmedRevs[pos + '-' + revHash];
19270 });
19271 }
19272
19273 return {
19274 tree: result,
19275 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
19276 };
19277}
19278
19279function merge(tree, path, depth) {
19280 var newTree = doMerge(tree, path);
19281 var stemmed = stem(newTree.tree, depth);
19282 return {
19283 tree: stemmed.tree,
19284 stemmedRevs: stemmed.revs,
19285 conflicts: newTree.conflicts
19286 };
19287}
19288
19289// return true if a rev exists in the rev tree, false otherwise
19290function revExists(revs, rev) {
19291 var toVisit = revs.slice();
19292 var splitRev = rev.split('-');
19293 var targetPos = parseInt(splitRev[0], 10);
19294 var targetId = splitRev[1];
19295
19296 var node;
19297 while ((node = toVisit.pop())) {
19298 if (node.pos === targetPos && node.ids[0] === targetId) {
19299 return true;
19300 }
19301 var branches = node.ids[2];
19302 for (var i = 0, len = branches.length; i < len; i++) {
19303 toVisit.push({pos: node.pos + 1, ids: branches[i]});
19304 }
19305 }
19306 return false;
19307}
19308
19309function getTrees(node) {
19310 return node.ids;
19311}
19312
19313// check if a specific revision of a doc has been deleted
19314// - metadata: the metadata object from the doc store
19315// - rev: (optional) the revision to check. defaults to winning revision
19316function isDeleted(metadata, rev) {
19317 if (!rev) {
19318 rev = winningRev(metadata);
19319 }
19320 var id = rev.substring(rev.indexOf('-') + 1);
19321 var toVisit = metadata.rev_tree.map(getTrees);
19322
19323 var tree;
19324 while ((tree = toVisit.pop())) {
19325 if (tree[0] === id) {
19326 return !!tree[1].deleted;
19327 }
19328 toVisit = toVisit.concat(tree[2]);
19329 }
19330}
19331
19332function isLocalId(id) {
19333 return (/^_local/).test(id);
19334}
19335
19336// returns the current leaf node for a given revision
19337function latest(rev, metadata) {
19338 var toVisit = metadata.rev_tree.slice();
19339 var node;
19340 while ((node = toVisit.pop())) {
19341 var pos = node.pos;
19342 var tree = node.ids;
19343 var id = tree[0];
19344 var opts = tree[1];
19345 var branches = tree[2];
19346 var isLeaf = branches.length === 0;
19347
19348 var history = node.history ? node.history.slice() : [];
19349 history.push({id: id, pos: pos, opts: opts});
19350
19351 if (isLeaf) {
19352 for (var i = 0, len = history.length; i < len; i++) {
19353 var historyNode = history[i];
19354 var historyRev = historyNode.pos + '-' + historyNode.id;
19355
19356 if (historyRev === rev) {
19357 // return the rev of this leaf
19358 return pos + '-' + id;
19359 }
19360 }
19361 }
19362
19363 for (var j = 0, l = branches.length; j < l; j++) {
19364 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
19365 }
19366 }
19367
19368 /* istanbul ignore next */
19369 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
19370}
19371
19372function updateDoc(revLimit, prev, docInfo, results,
19373 i, cb, writeDoc, newEdits) {
19374
19375 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
19376 results[i] = docInfo;
19377 return cb();
19378 }
19379
19380 // sometimes this is pre-calculated. historically not always
19381 var previousWinningRev = prev.winningRev || winningRev(prev);
19382 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
19383 isDeleted(prev, previousWinningRev);
19384 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
19385 isDeleted(docInfo.metadata);
19386 var isRoot = /^1-/.test(docInfo.metadata.rev);
19387
19388 if (previouslyDeleted && !deleted && newEdits && isRoot) {
19389 var newDoc = docInfo.data;
19390 newDoc._rev = previousWinningRev;
19391 newDoc._id = docInfo.metadata.id;
19392 docInfo = parseDoc(newDoc, newEdits);
19393 }
19394
19395 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
19396
19397 var inConflict = newEdits && ((
19398 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
19399 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
19400 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
19401
19402 if (inConflict) {
19403 var err = createError(REV_CONFLICT);
19404 results[i] = err;
19405 return cb();
19406 }
19407
19408 var newRev = docInfo.metadata.rev;
19409 docInfo.metadata.rev_tree = merged.tree;
19410 docInfo.stemmedRevs = merged.stemmedRevs || [];
19411 /* istanbul ignore else */
19412 if (prev.rev_map) {
19413 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
19414 }
19415
19416 // recalculate
19417 var winningRev$$1 = winningRev(docInfo.metadata);
19418 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
19419
19420 // calculate the total number of documents that were added/removed,
19421 // from the perspective of total_rows/doc_count
19422 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
19423 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
19424
19425 var newRevIsDeleted;
19426 if (newRev === winningRev$$1) {
19427 // if the new rev is the same as the winning rev, we can reuse that value
19428 newRevIsDeleted = winningRevIsDeleted;
19429 } else {
19430 // if they're not the same, then we need to recalculate
19431 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
19432 }
19433
19434 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
19435 true, delta, i, cb);
19436}
19437
19438function rootIsMissing(docInfo) {
19439 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
19440}
19441
19442function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
19443 writeDoc, opts, overallCallback) {
19444
19445 // Default to 1000 locally
19446 revLimit = revLimit || 1000;
19447
19448 function insertDoc(docInfo, resultsIdx, callback) {
19449 // Cant insert new deleted documents
19450 var winningRev$$1 = winningRev(docInfo.metadata);
19451 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
19452 if ('was_delete' in opts && deleted) {
19453 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
19454 return callback();
19455 }
19456
19457 // 4712 - detect whether a new document was inserted with a _rev
19458 var inConflict = newEdits && rootIsMissing(docInfo);
19459
19460 if (inConflict) {
19461 var err = createError(REV_CONFLICT);
19462 results[resultsIdx] = err;
19463 return callback();
19464 }
19465
19466 var delta = deleted ? 0 : 1;
19467
19468 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
19469 delta, resultsIdx, callback);
19470 }
19471
19472 var newEdits = opts.new_edits;
19473 var idsToDocs = new ExportedMap();
19474
19475 var docsDone = 0;
19476 var docsToDo = docInfos.length;
19477
19478 function checkAllDocsDone() {
19479 if (++docsDone === docsToDo && overallCallback) {
19480 overallCallback();
19481 }
19482 }
19483
19484 docInfos.forEach(function (currentDoc, resultsIdx) {
19485
19486 if (currentDoc._id && isLocalId(currentDoc._id)) {
19487 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
19488 api[fun](currentDoc, {ctx: tx}, function (err, res) {
19489 results[resultsIdx] = err || res;
19490 checkAllDocsDone();
19491 });
19492 return;
19493 }
19494
19495 var id = currentDoc.metadata.id;
19496 if (idsToDocs.has(id)) {
19497 docsToDo--; // duplicate
19498 idsToDocs.get(id).push([currentDoc, resultsIdx]);
19499 } else {
19500 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
19501 }
19502 });
19503
19504 // in the case of new_edits, the user can provide multiple docs
19505 // with the same id. these need to be processed sequentially
19506 idsToDocs.forEach(function (docs, id) {
19507 var numDone = 0;
19508
19509 function docWritten() {
19510 if (++numDone < docs.length) {
19511 nextDoc();
19512 } else {
19513 checkAllDocsDone();
19514 }
19515 }
19516 function nextDoc() {
19517 var value = docs[numDone];
19518 var currentDoc = value[0];
19519 var resultsIdx = value[1];
19520
19521 if (fetchedDocs.has(id)) {
19522 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
19523 resultsIdx, docWritten, writeDoc, newEdits);
19524 } else {
19525 // Ensure stemming applies to new writes as well
19526 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
19527 currentDoc.metadata.rev_tree = merged.tree;
19528 currentDoc.stemmedRevs = merged.stemmedRevs || [];
19529 insertDoc(currentDoc, resultsIdx, docWritten);
19530 }
19531 }
19532 nextDoc();
19533 });
19534}
19535
19536function safeJsonParse(str) {
19537 // This try/catch guards against stack overflow errors.
19538 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
19539 // cannot overflow.
19540 try {
19541 return JSON.parse(str);
19542 } catch (e) {
19543 /* istanbul ignore next */
19544 return vuvuzela.parse(str);
19545 }
19546}
19547
19548function safeJsonStringify(json) {
19549 try {
19550 return JSON.stringify(json);
19551 } catch (e) {
19552 /* istanbul ignore next */
19553 return vuvuzela.stringify(json);
19554 }
19555}
19556
19557function readAsBlobOrBuffer(storedObject, type) {
19558 // In the browser, we've stored a binary string. This now comes back as a
19559 // browserified Node-style Buffer (implemented as a typed array),
19560 // but we want a Blob instead.
19561 var byteArray = new Uint8Array(storedObject);
19562 return createBlob([byteArray], {type: type});
19563}
19564
19565// In the browser, we store a binary string
19566function prepareAttachmentForStorage(attData, cb) {
19567 readAsBinaryString(attData, cb);
19568}
19569
19570function createEmptyBlobOrBuffer(type) {
19571 return createBlob([''], {type: type});
19572}
19573
19574function getCacheFor(transaction, store) {
19575 var prefix = store.prefix()[0];
19576 var cache = transaction._cache;
19577 var subCache = cache.get(prefix);
19578 if (!subCache) {
19579 subCache = new ExportedMap();
19580 cache.set(prefix, subCache);
19581 }
19582 return subCache;
19583}
19584
19585function LevelTransaction() {
19586 this._batch = [];
19587 this._cache = new ExportedMap();
19588}
19589
19590LevelTransaction.prototype.get = function (store, key, callback) {
19591 var cache = getCacheFor(this, store);
19592 var exists = cache.get(key);
19593 if (exists) {
19594 return immediate(function () {
19595 callback(null, exists);
19596 });
19597 } else if (exists === null) { // deleted marker
19598 /* istanbul ignore next */
19599 return immediate(function () {
19600 callback({name: 'NotFoundError'});
19601 });
19602 }
19603 store.get(key, function (err, res) {
19604 if (err) {
19605 /* istanbul ignore else */
19606 if (err.name === 'NotFoundError') {
19607 cache.set(key, null);
19608 }
19609 return callback(err);
19610 }
19611 cache.set(key, res);
19612 callback(null, res);
19613 });
19614};
19615
19616LevelTransaction.prototype.batch = function (batch) {
19617 for (var i = 0, len = batch.length; i < len; i++) {
19618 var operation = batch[i];
19619
19620 var cache = getCacheFor(this, operation.prefix);
19621
19622 if (operation.type === 'put') {
19623 cache.set(operation.key, operation.value);
19624 } else {
19625 cache.set(operation.key, null);
19626 }
19627 }
19628 this._batch = this._batch.concat(batch);
19629};
19630
19631LevelTransaction.prototype.execute = function (db, callback) {
19632
19633 var keys = new ExportedSet();
19634 var uniqBatches = [];
19635
19636 // remove duplicates; last one wins
19637 for (var i = this._batch.length - 1; i >= 0; i--) {
19638 var operation = this._batch[i];
19639 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
19640 if (keys.has(lookupKey)) {
19641 continue;
19642 }
19643 keys.add(lookupKey);
19644 uniqBatches.push(operation);
19645 }
19646
19647 db.batch(uniqBatches, callback);
19648};
19649
19650var DOC_STORE = 'document-store';
19651var BY_SEQ_STORE = 'by-sequence';
19652var ATTACHMENT_STORE = 'attach-store';
19653var BINARY_STORE = 'attach-binary-store';
19654var LOCAL_STORE = 'local-store';
19655var META_STORE = 'meta-store';
19656
19657// leveldb barks if we try to open a db multiple times
19658// so we cache opened connections here for initstore()
19659var dbStores = new ExportedMap();
19660
19661// store the value of update_seq in the by-sequence store the key name will
19662// never conflict, since the keys in the by-sequence store are integers
19663var UPDATE_SEQ_KEY = '_local_last_update_seq';
19664var DOC_COUNT_KEY = '_local_doc_count';
19665var UUID_KEY = '_local_uuid';
19666
19667var MD5_PREFIX = 'md5-';
19668
19669var safeJsonEncoding = {
19670 encode: safeJsonStringify,
19671 decode: safeJsonParse,
19672 buffer: false,
19673 type: 'cheap-json'
19674};
19675
19676var levelChanges = new Changes();
19677
19678// winningRev and deleted are performance-killers, but
19679// in newer versions of PouchDB, they are cached on the metadata
19680function getWinningRev(metadata) {
19681 return 'winningRev' in metadata ?
19682 metadata.winningRev : winningRev(metadata);
19683}
19684
19685function getIsDeleted(metadata, winningRev$$1) {
19686 return 'deleted' in metadata ?
19687 metadata.deleted : isDeleted(metadata, winningRev$$1);
19688}
19689
19690function fetchAttachment(att, stores, opts) {
19691 var type = att.content_type;
19692 return new Promise(function (resolve, reject) {
19693 stores.binaryStore.get(att.digest, function (err, buffer) {
19694 var data;
19695 if (err) {
19696 /* istanbul ignore if */
19697 if (err.name !== 'NotFoundError') {
19698 return reject(err);
19699 } else {
19700 // empty
19701 if (!opts.binary) {
19702 data = '';
19703 } else {
19704 data = binStringToBluffer('', type);
19705 }
19706 }
19707 } else { // non-empty
19708 if (opts.binary) {
19709 data = readAsBlobOrBuffer(buffer, type);
19710 } else {
19711 data = buffer.toString('base64');
19712 }
19713 }
19714 delete att.stub;
19715 delete att.length;
19716 att.data = data;
19717 resolve();
19718 });
19719 });
19720}
19721
19722function fetchAttachments(results, stores, opts) {
19723 var atts = [];
19724 results.forEach(function (row) {
19725 if (!(row.doc && row.doc._attachments)) {
19726 return;
19727 }
19728 var attNames = Object.keys(row.doc._attachments);
19729 attNames.forEach(function (attName) {
19730 var att = row.doc._attachments[attName];
19731 if (!('data' in att)) {
19732 atts.push(att);
19733 }
19734 });
19735 });
19736
19737 return Promise.all(atts.map(function (att) {
19738 return fetchAttachment(att, stores, opts);
19739 }));
19740}
19741
19742function LevelPouch(opts, callback) {
19743 opts = clone(opts);
19744 var api = this;
19745 var instanceId;
19746 var stores = {};
19747 var revLimit = opts.revs_limit;
19748 var db;
19749 var name = opts.name;
19750 // TODO: this is undocumented and unused probably
19751 /* istanbul ignore else */
19752 if (typeof opts.createIfMissing === 'undefined') {
19753 opts.createIfMissing = true;
19754 }
19755
19756 var leveldown = opts.db;
19757
19758 var dbStore;
19759 var leveldownName = functionName(leveldown);
19760 if (dbStores.has(leveldownName)) {
19761 dbStore = dbStores.get(leveldownName);
19762 } else {
19763 dbStore = new ExportedMap();
19764 dbStores.set(leveldownName, dbStore);
19765 }
19766 if (dbStore.has(name)) {
19767 db = dbStore.get(name);
19768 afterDBCreated();
19769 } else {
19770 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
19771 /* istanbul ignore if */
19772 if (err) {
19773 dbStore["delete"](name);
19774 return callback(err);
19775 }
19776 db = dbStore.get(name);
19777 db._docCount = -1;
19778 db._queue = new Deque();
19779 /* istanbul ignore else */
19780 if (typeof opts.migrate === 'object') { // migration for leveldown
19781 opts.migrate.doMigrationOne(name, db, afterDBCreated);
19782 } else {
19783 afterDBCreated();
19784 }
19785 })));
19786 }
19787
19788 function afterDBCreated() {
19789 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
19790 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
19791 stores.attachmentStore =
19792 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
19793 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
19794 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
19795 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
19796 /* istanbul ignore else */
19797 if (typeof opts.migrate === 'object') { // migration for leveldown
19798 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
19799 } else {
19800 afterLastMigration();
19801 }
19802 }
19803
19804 function afterLastMigration() {
19805 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
19806 if (typeof db._updateSeq === 'undefined') {
19807 db._updateSeq = value || 0;
19808 }
19809 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
19810 db._docCount = !err ? value : 0;
19811 stores.metaStore.get(UUID_KEY, function (err, value) {
19812 instanceId = !err ? value : uuid();
19813 stores.metaStore.put(UUID_KEY, instanceId, function () {
19814 immediate(function () {
19815 callback(null, api);
19816 });
19817 });
19818 });
19819 });
19820 });
19821 }
19822
19823 function countDocs(callback) {
19824 /* istanbul ignore if */
19825 if (db.isClosed()) {
19826 return callback(new Error('database is closed'));
19827 }
19828 return callback(null, db._docCount); // use cached value
19829 }
19830
19831 api._remote = false;
19832 /* istanbul ignore next */
19833 api.type = function () {
19834 return 'leveldb';
19835 };
19836
19837 api._id = function (callback) {
19838 callback(null, instanceId);
19839 };
19840
19841 api._info = function (callback) {
19842 var res = {
19843 doc_count: db._docCount,
19844 update_seq: db._updateSeq,
19845 backend_adapter: functionName(leveldown)
19846 };
19847 return immediate(function () {
19848 callback(null, res);
19849 });
19850 };
19851
19852 function tryCode(fun, args) {
19853 try {
19854 fun.apply(null, args);
19855 } catch (err) {
19856 args[args.length - 1](err);
19857 }
19858 }
19859
19860 function executeNext() {
19861 var firstTask = db._queue.peekFront();
19862
19863 if (firstTask.type === 'read') {
19864 runReadOperation(firstTask);
19865 } else { // write, only do one at a time
19866 runWriteOperation(firstTask);
19867 }
19868 }
19869
19870 function runReadOperation(firstTask) {
19871 // do multiple reads at once simultaneously, because it's safe
19872
19873 var readTasks = [firstTask];
19874 var i = 1;
19875 var nextTask = db._queue.get(i);
19876 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
19877 readTasks.push(nextTask);
19878 i++;
19879 nextTask = db._queue.get(i);
19880 }
19881
19882 var numDone = 0;
19883
19884 readTasks.forEach(function (readTask) {
19885 var args = readTask.args;
19886 var callback = args[args.length - 1];
19887 args[args.length - 1] = getArguments(function (cbArgs) {
19888 callback.apply(null, cbArgs);
19889 if (++numDone === readTasks.length) {
19890 immediate(function () {
19891 // all read tasks have finished
19892 readTasks.forEach(function () {
19893 db._queue.shift();
19894 });
19895 if (db._queue.length) {
19896 executeNext();
19897 }
19898 });
19899 }
19900 });
19901 tryCode(readTask.fun, args);
19902 });
19903 }
19904
19905 function runWriteOperation(firstTask) {
19906 var args = firstTask.args;
19907 var callback = args[args.length - 1];
19908 args[args.length - 1] = getArguments(function (cbArgs) {
19909 callback.apply(null, cbArgs);
19910 immediate(function () {
19911 db._queue.shift();
19912 if (db._queue.length) {
19913 executeNext();
19914 }
19915 });
19916 });
19917 tryCode(firstTask.fun, args);
19918 }
19919
19920 // all read/write operations to the database are done in a queue,
19921 // similar to how websql/idb works. this avoids problems such
19922 // as e.g. compaction needing to have a lock on the database while
19923 // it updates stuff. in the future we can revisit this.
19924 function writeLock(fun) {
19925 return getArguments(function (args) {
19926 db._queue.push({
19927 fun: fun,
19928 args: args,
19929 type: 'write'
19930 });
19931
19932 if (db._queue.length === 1) {
19933 immediate(executeNext);
19934 }
19935 });
19936 }
19937
19938 // same as the writelock, but multiple can run at once
19939 function readLock(fun) {
19940 return getArguments(function (args) {
19941 db._queue.push({
19942 fun: fun,
19943 args: args,
19944 type: 'read'
19945 });
19946
19947 if (db._queue.length === 1) {
19948 immediate(executeNext);
19949 }
19950 });
19951 }
19952
19953 function formatSeq(n) {
19954 return ('0000000000000000' + n).slice(-16);
19955 }
19956
19957 function parseSeq(s) {
19958 return parseInt(s, 10);
19959 }
19960
19961 api._get = readLock(function (id, opts, callback) {
19962 opts = clone(opts);
19963
19964 stores.docStore.get(id, function (err, metadata) {
19965
19966 if (err || !metadata) {
19967 return callback(createError(MISSING_DOC, 'missing'));
19968 }
19969
19970 var rev$$1;
19971 if (!opts.rev) {
19972 rev$$1 = getWinningRev(metadata);
19973 var deleted = getIsDeleted(metadata, rev$$1);
19974 if (deleted) {
19975 return callback(createError(MISSING_DOC, "deleted"));
19976 }
19977 } else {
19978 rev$$1 = opts.latest ? latest(opts.rev, metadata) : opts.rev;
19979 }
19980
19981 var seq = metadata.rev_map[rev$$1];
19982
19983 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
19984 if (!doc) {
19985 return callback(createError(MISSING_DOC));
19986 }
19987 /* istanbul ignore if */
19988 if ('_id' in doc && doc._id !== metadata.id) {
19989 // this failing implies something very wrong
19990 return callback(new Error('wrong doc returned'));
19991 }
19992 doc._id = metadata.id;
19993 if ('_rev' in doc) {
19994 /* istanbul ignore if */
19995 if (doc._rev !== rev$$1) {
19996 // this failing implies something very wrong
19997 return callback(new Error('wrong doc returned'));
19998 }
19999 } else {
20000 // we didn't always store this
20001 doc._rev = rev$$1;
20002 }
20003 return callback(null, {doc: doc, metadata: metadata});
20004 });
20005 });
20006 });
20007
20008 // not technically part of the spec, but if putAttachment has its own
20009 // method...
20010 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
20011 var digest = attachment.digest;
20012 var type = attachment.content_type;
20013
20014 stores.binaryStore.get(digest, function (err, attach) {
20015 if (err) {
20016 /* istanbul ignore if */
20017 if (err.name !== 'NotFoundError') {
20018 return callback(err);
20019 }
20020 // Empty attachment
20021 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
20022 }
20023
20024 if (opts.binary) {
20025 callback(null, readAsBlobOrBuffer(attach, type));
20026 } else {
20027 callback(null, attach.toString('base64'));
20028 }
20029 });
20030 };
20031
20032 api._bulkDocs = writeLock(function (req, opts, callback) {
20033 var newEdits = opts.new_edits;
20034 var results = new Array(req.docs.length);
20035 var fetchedDocs = new ExportedMap();
20036 var stemmedRevs = new ExportedMap();
20037
20038 var txn = new LevelTransaction();
20039 var docCountDelta = 0;
20040 var newUpdateSeq = db._updateSeq;
20041
20042 // parse the docs and give each a sequence number
20043 var userDocs = req.docs;
20044 var docInfos = userDocs.map(function (doc) {
20045 if (doc._id && isLocalId(doc._id)) {
20046 return doc;
20047 }
20048 var newDoc = parseDoc(doc, newEdits, api.__opts);
20049
20050 if (newDoc.metadata && !newDoc.metadata.rev_map) {
20051 newDoc.metadata.rev_map = {};
20052 }
20053
20054 return newDoc;
20055 });
20056 var infoErrors = docInfos.filter(function (doc) {
20057 return doc.error;
20058 });
20059
20060 if (infoErrors.length) {
20061 return callback(infoErrors[0]);
20062 }
20063
20064 // verify any stub attachments as a precondition test
20065
20066 function verifyAttachment(digest, callback) {
20067 txn.get(stores.attachmentStore, digest, function (levelErr) {
20068 if (levelErr) {
20069 var err = createError(MISSING_STUB,
20070 'unknown stub attachment with digest ' +
20071 digest);
20072 callback(err);
20073 } else {
20074 callback();
20075 }
20076 });
20077 }
20078
20079 function verifyAttachments(finish) {
20080 var digests = [];
20081 userDocs.forEach(function (doc) {
20082 if (doc && doc._attachments) {
20083 Object.keys(doc._attachments).forEach(function (filename) {
20084 var att = doc._attachments[filename];
20085 if (att.stub) {
20086 digests.push(att.digest);
20087 }
20088 });
20089 }
20090 });
20091 if (!digests.length) {
20092 return finish();
20093 }
20094 var numDone = 0;
20095 var err;
20096
20097 digests.forEach(function (digest) {
20098 verifyAttachment(digest, function (attErr) {
20099 if (attErr && !err) {
20100 err = attErr;
20101 }
20102
20103 if (++numDone === digests.length) {
20104 finish(err);
20105 }
20106 });
20107 });
20108 }
20109
20110 function fetchExistingDocs(finish) {
20111 var numDone = 0;
20112 var overallErr;
20113 function checkDone() {
20114 if (++numDone === userDocs.length) {
20115 return finish(overallErr);
20116 }
20117 }
20118
20119 userDocs.forEach(function (doc) {
20120 if (doc._id && isLocalId(doc._id)) {
20121 // skip local docs
20122 return checkDone();
20123 }
20124 txn.get(stores.docStore, doc._id, function (err, info) {
20125 if (err) {
20126 /* istanbul ignore if */
20127 if (err.name !== 'NotFoundError') {
20128 overallErr = err;
20129 }
20130 } else {
20131 fetchedDocs.set(doc._id, info);
20132 }
20133 checkDone();
20134 });
20135 });
20136 }
20137
20138 function compact(revsMap, callback) {
20139 var promise = Promise.resolve();
20140 revsMap.forEach(function (revs, docId) {
20141 // TODO: parallelize, for now need to be sequential to
20142 // pass orphaned attachment tests
20143 promise = promise.then(function () {
20144 return new Promise(function (resolve, reject) {
20145 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
20146 /* istanbul ignore if */
20147 if (err) {
20148 return reject(err);
20149 }
20150 resolve();
20151 });
20152 });
20153 });
20154 });
20155
20156 promise.then(function () {
20157 callback();
20158 }, callback);
20159 }
20160
20161 function autoCompact(callback) {
20162 var revsMap = new ExportedMap();
20163 fetchedDocs.forEach(function (metadata, docId) {
20164 revsMap.set(docId, compactTree(metadata));
20165 });
20166 compact(revsMap, callback);
20167 }
20168
20169 function finish() {
20170 compact(stemmedRevs, function (error) {
20171 /* istanbul ignore if */
20172 if (error) {
20173 complete(error);
20174 }
20175 if (api.auto_compaction) {
20176 return autoCompact(complete);
20177 }
20178 complete();
20179 });
20180 }
20181
20182 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
20183 isUpdate, delta, resultsIdx, callback2) {
20184 docCountDelta += delta;
20185
20186 var err = null;
20187 var recv = 0;
20188
20189 docInfo.metadata.winningRev = winningRev$$1;
20190 docInfo.metadata.deleted = winningRevIsDeleted;
20191
20192 docInfo.data._id = docInfo.metadata.id;
20193 docInfo.data._rev = docInfo.metadata.rev;
20194
20195 if (newRevIsDeleted) {
20196 docInfo.data._deleted = true;
20197 }
20198
20199 if (docInfo.stemmedRevs.length) {
20200 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
20201 }
20202
20203 var attachments = docInfo.data._attachments ?
20204 Object.keys(docInfo.data._attachments) :
20205 [];
20206
20207 function attachmentSaved(attachmentErr) {
20208 recv++;
20209 if (!err) {
20210 /* istanbul ignore if */
20211 if (attachmentErr) {
20212 err = attachmentErr;
20213 callback2(err);
20214 } else if (recv === attachments.length) {
20215 finish();
20216 }
20217 }
20218 }
20219
20220 function onMD5Load(doc, key, data, attachmentSaved) {
20221 return function (result) {
20222 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
20223 };
20224 }
20225
20226 function doMD5(doc, key, attachmentSaved) {
20227 return function (data) {
20228 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
20229 };
20230 }
20231
20232 for (var i = 0; i < attachments.length; i++) {
20233 var key = attachments[i];
20234 var att = docInfo.data._attachments[key];
20235
20236 if (att.stub) {
20237 // still need to update the refs mapping
20238 var id = docInfo.data._id;
20239 var rev$$1 = docInfo.data._rev;
20240 saveAttachmentRefs(id, rev$$1, att.digest, attachmentSaved);
20241 continue;
20242 }
20243 var data;
20244 if (typeof att.data === 'string') {
20245 // input is assumed to be a base64 string
20246 try {
20247 data = thisAtob(att.data);
20248 } catch (e) {
20249 callback(createError(BAD_ARG,
20250 'Attachment is not a valid base64 string'));
20251 return;
20252 }
20253 doMD5(docInfo, key, attachmentSaved)(data);
20254 } else {
20255 prepareAttachmentForStorage(att.data,
20256 doMD5(docInfo, key, attachmentSaved));
20257 }
20258 }
20259
20260 function finish() {
20261 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
20262 /* istanbul ignore if */
20263 if (seq) {
20264 // check that there aren't any existing revisions with the same
20265 // revision id, else we shouldn't do anything
20266 return callback2();
20267 }
20268 seq = ++newUpdateSeq;
20269 docInfo.metadata.rev_map[docInfo.metadata.rev] =
20270 docInfo.metadata.seq = seq;
20271 var seqKey = formatSeq(seq);
20272 var batch = [{
20273 key: seqKey,
20274 value: docInfo.data,
20275 prefix: stores.bySeqStore,
20276 type: 'put'
20277 }, {
20278 key: docInfo.metadata.id,
20279 value: docInfo.metadata,
20280 prefix: stores.docStore,
20281 type: 'put'
20282 }];
20283 txn.batch(batch);
20284 results[resultsIdx] = {
20285 ok: true,
20286 id: docInfo.metadata.id,
20287 rev: docInfo.metadata.rev
20288 };
20289 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
20290 callback2();
20291 }
20292
20293 if (!attachments.length) {
20294 finish();
20295 }
20296 }
20297
20298 // attachments are queued per-digest, otherwise the refs could be
20299 // overwritten by concurrent writes in the same bulkDocs session
20300 var attachmentQueues = {};
20301
20302 function saveAttachmentRefs(id, rev$$1, digest, callback) {
20303
20304 function fetchAtt() {
20305 return new Promise(function (resolve, reject) {
20306 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
20307 /* istanbul ignore if */
20308 if (err && err.name !== 'NotFoundError') {
20309 return reject(err);
20310 }
20311 resolve(oldAtt);
20312 });
20313 });
20314 }
20315
20316 function saveAtt(oldAtt) {
20317 var ref = [id, rev$$1].join('@');
20318 var newAtt = {};
20319
20320 if (oldAtt) {
20321 if (oldAtt.refs) {
20322 // only update references if this attachment already has them
20323 // since we cannot migrate old style attachments here without
20324 // doing a full db scan for references
20325 newAtt.refs = oldAtt.refs;
20326 newAtt.refs[ref] = true;
20327 }
20328 } else {
20329 newAtt.refs = {};
20330 newAtt.refs[ref] = true;
20331 }
20332
20333 return new Promise(function (resolve) {
20334 txn.batch([{
20335 type: 'put',
20336 prefix: stores.attachmentStore,
20337 key: digest,
20338 value: newAtt
20339 }]);
20340 resolve(!oldAtt);
20341 });
20342 }
20343
20344 // put attachments in a per-digest queue, to avoid two docs with the same
20345 // attachment overwriting each other
20346 var queue = attachmentQueues[digest] || Promise.resolve();
20347 attachmentQueues[digest] = queue.then(function () {
20348 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
20349 callback(null, isNewAttachment);
20350 }, callback);
20351 });
20352 }
20353
20354 function saveAttachment(docInfo, digest, key, data, callback) {
20355 var att = docInfo.data._attachments[key];
20356 delete att.data;
20357 att.digest = digest;
20358 att.length = data.length;
20359 var id = docInfo.metadata.id;
20360 var rev$$1 = docInfo.metadata.rev;
20361 att.revpos = parseInt(rev$$1, 10);
20362
20363 saveAttachmentRefs(id, rev$$1, digest, function (err, isNewAttachment) {
20364 /* istanbul ignore if */
20365 if (err) {
20366 return callback(err);
20367 }
20368 // do not try to store empty attachments
20369 if (data.length === 0) {
20370 return callback(err);
20371 }
20372 if (!isNewAttachment) {
20373 // small optimization - don't bother writing it again
20374 return callback(err);
20375 }
20376 txn.batch([{
20377 type: 'put',
20378 prefix: stores.binaryStore,
20379 key: digest,
20380 value: bufferFrom(data, 'binary')
20381 }]);
20382 callback();
20383 });
20384 }
20385
20386 function complete(err) {
20387 /* istanbul ignore if */
20388 if (err) {
20389 return immediate(function () {
20390 callback(err);
20391 });
20392 }
20393 txn.batch([
20394 {
20395 prefix: stores.metaStore,
20396 type: 'put',
20397 key: UPDATE_SEQ_KEY,
20398 value: newUpdateSeq
20399 },
20400 {
20401 prefix: stores.metaStore,
20402 type: 'put',
20403 key: DOC_COUNT_KEY,
20404 value: db._docCount + docCountDelta
20405 }
20406 ]);
20407 txn.execute(db, function (err) {
20408 /* istanbul ignore if */
20409 if (err) {
20410 return callback(err);
20411 }
20412 db._docCount += docCountDelta;
20413 db._updateSeq = newUpdateSeq;
20414 levelChanges.notify(name);
20415 immediate(function () {
20416 callback(null, results);
20417 });
20418 });
20419 }
20420
20421 if (!docInfos.length) {
20422 return callback(null, []);
20423 }
20424
20425 verifyAttachments(function (err) {
20426 if (err) {
20427 return callback(err);
20428 }
20429 fetchExistingDocs(function (err) {
20430 /* istanbul ignore if */
20431 if (err) {
20432 return callback(err);
20433 }
20434 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
20435 writeDoc, opts, finish);
20436 });
20437 });
20438 });
20439 api._allDocs = function (opts, callback) {
20440 if ('keys' in opts) {
20441 return allDocsKeysQuery(this, opts);
20442 }
20443 return readLock(function (opts, callback) {
20444 opts = clone(opts);
20445 countDocs(function (err, docCount) {
20446 /* istanbul ignore if */
20447 if (err) {
20448 return callback(err);
20449 }
20450 var readstreamOpts = {};
20451 var skip = opts.skip || 0;
20452 if (opts.startkey) {
20453 readstreamOpts.gte = opts.startkey;
20454 }
20455 if (opts.endkey) {
20456 readstreamOpts.lte = opts.endkey;
20457 }
20458 if (opts.key) {
20459 readstreamOpts.gte = readstreamOpts.lte = opts.key;
20460 }
20461 if (opts.descending) {
20462 readstreamOpts.reverse = true;
20463 // switch start and ends
20464 var tmp = readstreamOpts.lte;
20465 readstreamOpts.lte = readstreamOpts.gte;
20466 readstreamOpts.gte = tmp;
20467 }
20468 var limit;
20469 if (typeof opts.limit === 'number') {
20470 limit = opts.limit;
20471 }
20472 if (limit === 0 ||
20473 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
20474 readstreamOpts.gte > readstreamOpts.lte)) {
20475 // should return 0 results when start is greater than end.
20476 // normally level would "fix" this for us by reversing the order,
20477 // so short-circuit instead
20478 var returnVal = {
20479 total_rows: docCount,
20480 offset: opts.skip,
20481 rows: []
20482 };
20483 /* istanbul ignore if */
20484 if (opts.update_seq) {
20485 returnVal.update_seq = db._updateSeq;
20486 }
20487 return callback(null, returnVal);
20488 }
20489 var results = [];
20490 var docstream = stores.docStore.readStream(readstreamOpts);
20491
20492 var throughStream = through2.obj(function (entry, _, next) {
20493 var metadata = entry.value;
20494 // winningRev and deleted are performance-killers, but
20495 // in newer versions of PouchDB, they are cached on the metadata
20496 var winningRev$$1 = getWinningRev(metadata);
20497 var deleted = getIsDeleted(metadata, winningRev$$1);
20498 if (!deleted) {
20499 if (skip-- > 0) {
20500 next();
20501 return;
20502 } else if (typeof limit === 'number' && limit-- <= 0) {
20503 docstream.unpipe();
20504 docstream.destroy();
20505 next();
20506 return;
20507 }
20508 } else if (opts.deleted !== 'ok') {
20509 next();
20510 return;
20511 }
20512 function allDocsInner(data) {
20513 var doc = {
20514 id: metadata.id,
20515 key: metadata.id,
20516 value: {
20517 rev: winningRev$$1
20518 }
20519 };
20520 if (opts.include_docs) {
20521 doc.doc = data;
20522 doc.doc._rev = doc.value.rev;
20523 if (opts.conflicts) {
20524 var conflicts = collectConflicts(metadata);
20525 if (conflicts.length) {
20526 doc.doc._conflicts = conflicts;
20527 }
20528 }
20529 for (var att in doc.doc._attachments) {
20530 if (doc.doc._attachments.hasOwnProperty(att)) {
20531 doc.doc._attachments[att].stub = true;
20532 }
20533 }
20534 }
20535 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
20536 return next();
20537 } else if (deleted) {
20538 if (opts.deleted === 'ok') {
20539 doc.value.deleted = true;
20540 doc.doc = null;
20541 } else {
20542 /* istanbul ignore next */
20543 return next();
20544 }
20545 }
20546 results.push(doc);
20547 next();
20548 }
20549 if (opts.include_docs) {
20550 var seq = metadata.rev_map[winningRev$$1];
20551 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
20552 allDocsInner(data);
20553 });
20554 }
20555 else {
20556 allDocsInner();
20557 }
20558 }, function (next) {
20559 Promise.resolve().then(function () {
20560 if (opts.include_docs && opts.attachments) {
20561 return fetchAttachments(results, stores, opts);
20562 }
20563 }).then(function () {
20564 var returnVal = {
20565 total_rows: docCount,
20566 offset: opts.skip,
20567 rows: results
20568 };
20569
20570 /* istanbul ignore if */
20571 if (opts.update_seq) {
20572 returnVal.update_seq = db._updateSeq;
20573 }
20574 callback(null, returnVal);
20575 }, callback);
20576 next();
20577 }).on('unpipe', function () {
20578 throughStream.end();
20579 });
20580
20581 docstream.on('error', callback);
20582
20583 docstream.pipe(throughStream);
20584 });
20585 })(opts, callback);
20586 };
20587
20588 api._changes = function (opts) {
20589 opts = clone(opts);
20590
20591 if (opts.continuous) {
20592 var id = name + ':' + uuid();
20593 levelChanges.addListener(name, id, api, opts);
20594 levelChanges.notify(name);
20595 return {
20596 cancel: function () {
20597 levelChanges.removeListener(name, id);
20598 }
20599 };
20600 }
20601
20602 var descending = opts.descending;
20603 var results = [];
20604 var lastSeq = opts.since || 0;
20605 var called = 0;
20606 var streamOpts = {
20607 reverse: descending
20608 };
20609 var limit;
20610 if ('limit' in opts && opts.limit > 0) {
20611 limit = opts.limit;
20612 }
20613 if (!streamOpts.reverse) {
20614 streamOpts.start = formatSeq(opts.since || 0);
20615 }
20616
20617 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
20618 var filter = filterChange(opts);
20619 var docIdsToMetadata = new ExportedMap();
20620
20621 function complete() {
20622 opts.done = true;
20623 if (opts.return_docs && opts.limit) {
20624 /* istanbul ignore if */
20625 if (opts.limit < results.length) {
20626 results.length = opts.limit;
20627 }
20628 }
20629 changeStream.unpipe(throughStream);
20630 changeStream.destroy();
20631 if (!opts.continuous && !opts.cancelled) {
20632 if (opts.include_docs && opts.attachments && opts.return_docs) {
20633 fetchAttachments(results, stores, opts).then(function () {
20634 opts.complete(null, {results: results, last_seq: lastSeq});
20635 });
20636 } else {
20637 opts.complete(null, {results: results, last_seq: lastSeq});
20638 }
20639 }
20640 }
20641 var changeStream = stores.bySeqStore.readStream(streamOpts);
20642 var throughStream = through2.obj(function (data, _, next) {
20643 if (limit && called >= limit) {
20644 complete();
20645 return next();
20646 }
20647 if (opts.cancelled || opts.done) {
20648 return next();
20649 }
20650
20651 var seq = parseSeq(data.key);
20652 var doc = data.value;
20653
20654 if (seq === opts.since && !descending) {
20655 // couchdb ignores `since` if descending=true
20656 return next();
20657 }
20658
20659 if (docIds && !docIds.has(doc._id)) {
20660 return next();
20661 }
20662
20663 var metadata;
20664
20665 function onGetMetadata(metadata) {
20666 var winningRev$$1 = getWinningRev(metadata);
20667
20668 function onGetWinningDoc(winningDoc) {
20669
20670 var change = opts.processChange(winningDoc, metadata, opts);
20671 change.seq = metadata.seq;
20672
20673 var filtered = filter(change);
20674 if (typeof filtered === 'object') {
20675 return opts.complete(filtered);
20676 }
20677
20678 if (filtered) {
20679 called++;
20680
20681 if (opts.attachments && opts.include_docs) {
20682 // fetch attachment immediately for the benefit
20683 // of live listeners
20684 fetchAttachments([change], stores, opts).then(function () {
20685 opts.onChange(change);
20686 });
20687 } else {
20688 opts.onChange(change);
20689 }
20690
20691 if (opts.return_docs) {
20692 results.push(change);
20693 }
20694 }
20695 next();
20696 }
20697
20698 if (metadata.seq !== seq) {
20699 // some other seq is later
20700 return next();
20701 }
20702
20703 lastSeq = seq;
20704
20705 if (winningRev$$1 === doc._rev) {
20706 return onGetWinningDoc(doc);
20707 }
20708
20709 // fetch the winner
20710
20711 var winningSeq = metadata.rev_map[winningRev$$1];
20712
20713 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
20714 onGetWinningDoc(doc);
20715 });
20716 }
20717
20718 metadata = docIdsToMetadata.get(doc._id);
20719 if (metadata) { // cached
20720 return onGetMetadata(metadata);
20721 }
20722 // metadata not cached, have to go fetch it
20723 stores.docStore.get(doc._id, function (err, metadata) {
20724 /* istanbul ignore if */
20725 if (opts.cancelled || opts.done || db.isClosed() ||
20726 isLocalId(metadata.id)) {
20727 return next();
20728 }
20729 docIdsToMetadata.set(doc._id, metadata);
20730 onGetMetadata(metadata);
20731 });
20732 }, function (next) {
20733 if (opts.cancelled) {
20734 return next();
20735 }
20736 if (opts.return_docs && opts.limit) {
20737 /* istanbul ignore if */
20738 if (opts.limit < results.length) {
20739 results.length = opts.limit;
20740 }
20741 }
20742
20743 next();
20744 }).on('unpipe', function () {
20745 throughStream.end();
20746 complete();
20747 });
20748 changeStream.pipe(throughStream);
20749 return {
20750 cancel: function () {
20751 opts.cancelled = true;
20752 complete();
20753 }
20754 };
20755 };
20756
20757 api._close = function (callback) {
20758 /* istanbul ignore if */
20759 if (db.isClosed()) {
20760 return callback(createError(NOT_OPEN));
20761 }
20762 db.close(function (err) {
20763 /* istanbul ignore if */
20764 if (err) {
20765 callback(err);
20766 } else {
20767 dbStore["delete"](name);
20768 callback();
20769 }
20770 });
20771 };
20772
20773 api._getRevisionTree = function (docId, callback) {
20774 stores.docStore.get(docId, function (err, metadata) {
20775 if (err) {
20776 callback(createError(MISSING_DOC));
20777 } else {
20778 callback(null, metadata.rev_tree);
20779 }
20780 });
20781 };
20782
20783 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
20784 api._doCompactionNoLock(docId, revs, opts, callback);
20785 });
20786
20787 // the NoLock version is for use by bulkDocs
20788 api._doCompactionNoLock = function (docId, revs, opts, callback) {
20789 if (typeof opts === 'function') {
20790 callback = opts;
20791 opts = {};
20792 }
20793
20794 if (!revs.length) {
20795 return callback();
20796 }
20797 var txn = opts.ctx || new LevelTransaction();
20798
20799 txn.get(stores.docStore, docId, function (err, metadata) {
20800 /* istanbul ignore if */
20801 if (err) {
20802 return callback(err);
20803 }
20804 var seqs = revs.map(function (rev$$1) {
20805 var seq = metadata.rev_map[rev$$1];
20806 delete metadata.rev_map[rev$$1];
20807 return seq;
20808 });
20809 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
20810 revHash, ctx, opts) {
20811 var rev$$1 = pos + '-' + revHash;
20812 if (revs.indexOf(rev$$1) !== -1) {
20813 opts.status = 'missing';
20814 }
20815 });
20816
20817 var batch = [];
20818 batch.push({
20819 key: metadata.id,
20820 value: metadata,
20821 type: 'put',
20822 prefix: stores.docStore
20823 });
20824
20825 var digestMap = {};
20826 var numDone = 0;
20827 var overallErr;
20828 function checkDone(err) {
20829 /* istanbul ignore if */
20830 if (err) {
20831 overallErr = err;
20832 }
20833 if (++numDone === revs.length) { // done
20834 /* istanbul ignore if */
20835 if (overallErr) {
20836 return callback(overallErr);
20837 }
20838 deleteOrphanedAttachments();
20839 }
20840 }
20841
20842 function finish(err) {
20843 /* istanbul ignore if */
20844 if (err) {
20845 return callback(err);
20846 }
20847 txn.batch(batch);
20848 if (opts.ctx) {
20849 // don't execute immediately
20850 return callback();
20851 }
20852 txn.execute(db, callback);
20853 }
20854
20855 function deleteOrphanedAttachments() {
20856 var possiblyOrphanedAttachments = Object.keys(digestMap);
20857 if (!possiblyOrphanedAttachments.length) {
20858 return finish();
20859 }
20860 var numDone = 0;
20861 var overallErr;
20862 function checkDone(err) {
20863 /* istanbul ignore if */
20864 if (err) {
20865 overallErr = err;
20866 }
20867 if (++numDone === possiblyOrphanedAttachments.length) {
20868 finish(overallErr);
20869 }
20870 }
20871 var refsToDelete = new ExportedMap();
20872 revs.forEach(function (rev$$1) {
20873 refsToDelete.set(docId + '@' + rev$$1, true);
20874 });
20875 possiblyOrphanedAttachments.forEach(function (digest) {
20876 txn.get(stores.attachmentStore, digest, function (err, attData) {
20877 /* istanbul ignore if */
20878 if (err) {
20879 if (err.name === 'NotFoundError') {
20880 return checkDone();
20881 } else {
20882 return checkDone(err);
20883 }
20884 }
20885 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
20886 return !refsToDelete.has(ref);
20887 });
20888 var newRefs = {};
20889 refs.forEach(function (ref) {
20890 newRefs[ref] = true;
20891 });
20892 if (refs.length) { // not orphaned
20893 batch.push({
20894 key: digest,
20895 type: 'put',
20896 value: {refs: newRefs},
20897 prefix: stores.attachmentStore
20898 });
20899 } else { // orphaned, can safely delete
20900 batch = batch.concat([{
20901 key: digest,
20902 type: 'del',
20903 prefix: stores.attachmentStore
20904 }, {
20905 key: digest,
20906 type: 'del',
20907 prefix: stores.binaryStore
20908 }]);
20909 }
20910 checkDone();
20911 });
20912 });
20913 }
20914
20915 seqs.forEach(function (seq) {
20916 batch.push({
20917 key: formatSeq(seq),
20918 type: 'del',
20919 prefix: stores.bySeqStore
20920 });
20921 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
20922 /* istanbul ignore if */
20923 if (err) {
20924 if (err.name === 'NotFoundError') {
20925 return checkDone();
20926 } else {
20927 return checkDone(err);
20928 }
20929 }
20930 var atts = Object.keys(doc._attachments || {});
20931 atts.forEach(function (attName) {
20932 var digest = doc._attachments[attName].digest;
20933 digestMap[digest] = true;
20934 });
20935 checkDone();
20936 });
20937 });
20938 });
20939 };
20940
20941 api._getLocal = function (id, callback) {
20942 stores.localStore.get(id, function (err, doc) {
20943 if (err) {
20944 callback(createError(MISSING_DOC));
20945 } else {
20946 callback(null, doc);
20947 }
20948 });
20949 };
20950
20951 api._putLocal = function (doc, opts, callback) {
20952 if (typeof opts === 'function') {
20953 callback = opts;
20954 opts = {};
20955 }
20956 if (opts.ctx) {
20957 api._putLocalNoLock(doc, opts, callback);
20958 } else {
20959 api._putLocalWithLock(doc, opts, callback);
20960 }
20961 };
20962
20963 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
20964 api._putLocalNoLock(doc, opts, callback);
20965 });
20966
20967 // the NoLock version is for use by bulkDocs
20968 api._putLocalNoLock = function (doc, opts, callback) {
20969 delete doc._revisions; // ignore this, trust the rev
20970 var oldRev = doc._rev;
20971 var id = doc._id;
20972
20973 var txn = opts.ctx || new LevelTransaction();
20974
20975 txn.get(stores.localStore, id, function (err, resp) {
20976 if (err && oldRev) {
20977 return callback(createError(REV_CONFLICT));
20978 }
20979 if (resp && resp._rev !== oldRev) {
20980 return callback(createError(REV_CONFLICT));
20981 }
20982 doc._rev =
20983 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
20984 var batch = [
20985 {
20986 type: 'put',
20987 prefix: stores.localStore,
20988 key: id,
20989 value: doc
20990 }
20991 ];
20992
20993 txn.batch(batch);
20994 var ret = {ok: true, id: doc._id, rev: doc._rev};
20995
20996 if (opts.ctx) {
20997 // don't execute immediately
20998 return callback(null, ret);
20999 }
21000 txn.execute(db, function (err) {
21001 /* istanbul ignore if */
21002 if (err) {
21003 return callback(err);
21004 }
21005 callback(null, ret);
21006 });
21007 });
21008 };
21009
21010 api._removeLocal = function (doc, opts, callback) {
21011 if (typeof opts === 'function') {
21012 callback = opts;
21013 opts = {};
21014 }
21015 if (opts.ctx) {
21016 api._removeLocalNoLock(doc, opts, callback);
21017 } else {
21018 api._removeLocalWithLock(doc, opts, callback);
21019 }
21020 };
21021
21022 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
21023 api._removeLocalNoLock(doc, opts, callback);
21024 });
21025
21026 // the NoLock version is for use by bulkDocs
21027 api._removeLocalNoLock = function (doc, opts, callback) {
21028 var txn = opts.ctx || new LevelTransaction();
21029 txn.get(stores.localStore, doc._id, function (err, resp) {
21030 if (err) {
21031 /* istanbul ignore if */
21032 if (err.name !== 'NotFoundError') {
21033 return callback(err);
21034 } else {
21035 return callback(createError(MISSING_DOC));
21036 }
21037 }
21038 if (resp._rev !== doc._rev) {
21039 return callback(createError(REV_CONFLICT));
21040 }
21041 txn.batch([{
21042 prefix: stores.localStore,
21043 type: 'del',
21044 key: doc._id
21045 }]);
21046 var ret = {ok: true, id: doc._id, rev: '0-0'};
21047 if (opts.ctx) {
21048 // don't execute immediately
21049 return callback(null, ret);
21050 }
21051 txn.execute(db, function (err) {
21052 /* istanbul ignore if */
21053 if (err) {
21054 return callback(err);
21055 }
21056 callback(null, ret);
21057 });
21058 });
21059 };
21060
21061 // close and delete open leveldb stores
21062 api._destroy = function (opts, callback) {
21063 var dbStore;
21064 var leveldownName = functionName(leveldown);
21065 /* istanbul ignore else */
21066 if (dbStores.has(leveldownName)) {
21067 dbStore = dbStores.get(leveldownName);
21068 } else {
21069 return callDestroy(name, callback);
21070 }
21071
21072 /* istanbul ignore else */
21073 if (dbStore.has(name)) {
21074 levelChanges.removeAllListeners(name);
21075
21076 dbStore.get(name).close(function () {
21077 dbStore["delete"](name);
21078 callDestroy(name, callback);
21079 });
21080 } else {
21081 callDestroy(name, callback);
21082 }
21083 };
21084 function callDestroy(name, cb) {
21085 // May not exist if leveldown is backed by memory adapter
21086 /* istanbul ignore else */
21087 if ('destroy' in leveldown) {
21088 leveldown.destroy(name, cb);
21089 } else {
21090 cb(null);
21091 }
21092 }
21093}
21094
21095function MemDownPouch(opts, callback) {
21096 var _opts = $inject_Object_assign({
21097 db: memdown
21098 }, opts);
21099
21100 LevelPouch.call(this, _opts, callback);
21101}
21102
21103// overrides for normal LevelDB behavior on Node
21104MemDownPouch.valid = function () {
21105 return true;
21106};
21107MemDownPouch.use_prefix = false;
21108
21109function MemoryPouchPlugin (PouchDB) {
21110 PouchDB.adapter('memory', MemDownPouch, true);
21111}
21112
21113/* global PouchDB */
21114
21115if (typeof PouchDB === 'undefined') {
21116 guardedConsole('error', 'memory adapter plugin error: ' +
21117 'Cannot find global "PouchDB" object! ' +
21118 'Did you remember to include pouchdb.js?');
21119} else {
21120 PouchDB.plugin(MemoryPouchPlugin);
21121}
21122
21123}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
21124},{"1":1,"114":114,"119":119,"124":124,"18":18,"21":21,"24":24,"25":25,"28":28,"50":50,"53":53,"55":55,"79":79,"8":8,"81":81}]},{},[125]);
21125
\No newline at end of file