· 8 years ago · Jun 06, 2018, 07:28 PM
1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.png = f()}})(function(){var define,module,exports;return (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(require,module,exports){
2(function (global){
3'use strict';
4
5// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
6// original notice:
7
8/*!
9 * The buffer module from node.js, for the browser.
10 *
11 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
12 * @license MIT
13 */
14function compare(a, b) {
15 if (a === b) {
16 return 0;
17 }
18
19 var x = a.length;
20 var y = b.length;
21
22 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
23 if (a[i] !== b[i]) {
24 x = a[i];
25 y = b[i];
26 break;
27 }
28 }
29
30 if (x < y) {
31 return -1;
32 }
33 if (y < x) {
34 return 1;
35 }
36 return 0;
37}
38function isBuffer(b) {
39 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
40 return global.Buffer.isBuffer(b);
41 }
42 return !!(b != null && b._isBuffer);
43}
44
45// based on node assert, original notice:
46
47// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
48//
49// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
50//
51// Originally from narwhal.js (http://narwhaljs.org)
52// Copyright (c) 2009 Thomas Robinson <280north.com>
53//
54// Permission is hereby granted, free of charge, to any person obtaining a copy
55// of this software and associated documentation files (the 'Software'), to
56// deal in the Software without restriction, including without limitation the
57// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
58// sell copies of the Software, and to permit persons to whom the Software is
59// furnished to do so, subject to the following conditions:
60//
61// The above copyright notice and this permission notice shall be included in
62// all copies or substantial portions of the Software.
63//
64// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
65// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
66// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
67// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
68// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
69// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
70
71var util = require('util/');
72var hasOwn = Object.prototype.hasOwnProperty;
73var pSlice = Array.prototype.slice;
74var functionsHaveNames = (function () {
75 return function foo() {}.name === 'foo';
76}());
77function pToString (obj) {
78 return Object.prototype.toString.call(obj);
79}
80function isView(arrbuf) {
81 if (isBuffer(arrbuf)) {
82 return false;
83 }
84 if (typeof global.ArrayBuffer !== 'function') {
85 return false;
86 }
87 if (typeof ArrayBuffer.isView === 'function') {
88 return ArrayBuffer.isView(arrbuf);
89 }
90 if (!arrbuf) {
91 return false;
92 }
93 if (arrbuf instanceof DataView) {
94 return true;
95 }
96 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
97 return true;
98 }
99 return false;
100}
101// 1. The assert module provides functions that throw
102// AssertionError's when particular conditions are not met. The
103// assert module must conform to the following interface.
104
105var assert = module.exports = ok;
106
107// 2. The AssertionError is defined in assert.
108// new assert.AssertionError({ message: message,
109// actual: actual,
110// expected: expected })
111
112var regex = /\s*function\s+([^\(\s]*)\s*/;
113// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
114function getName(func) {
115 if (!util.isFunction(func)) {
116 return;
117 }
118 if (functionsHaveNames) {
119 return func.name;
120 }
121 var str = func.toString();
122 var match = str.match(regex);
123 return match && match[1];
124}
125assert.AssertionError = function AssertionError(options) {
126 this.name = 'AssertionError';
127 this.actual = options.actual;
128 this.expected = options.expected;
129 this.operator = options.operator;
130 if (options.message) {
131 this.message = options.message;
132 this.generatedMessage = false;
133 } else {
134 this.message = getMessage(this);
135 this.generatedMessage = true;
136 }
137 var stackStartFunction = options.stackStartFunction || fail;
138 if (Error.captureStackTrace) {
139 Error.captureStackTrace(this, stackStartFunction);
140 } else {
141 // non v8 browsers so we can have a stacktrace
142 var err = new Error();
143 if (err.stack) {
144 var out = err.stack;
145
146 // try to strip useless frames
147 var fn_name = getName(stackStartFunction);
148 var idx = out.indexOf('\n' + fn_name);
149 if (idx >= 0) {
150 // once we have located the function frame
151 // we need to strip out everything before it (and its line)
152 var next_line = out.indexOf('\n', idx + 1);
153 out = out.substring(next_line + 1);
154 }
155
156 this.stack = out;
157 }
158 }
159};
160
161// assert.AssertionError instanceof Error
162util.inherits(assert.AssertionError, Error);
163
164function truncate(s, n) {
165 if (typeof s === 'string') {
166 return s.length < n ? s : s.slice(0, n);
167 } else {
168 return s;
169 }
170}
171function inspect(something) {
172 if (functionsHaveNames || !util.isFunction(something)) {
173 return util.inspect(something);
174 }
175 var rawname = getName(something);
176 var name = rawname ? ': ' + rawname : '';
177 return '[Function' + name + ']';
178}
179function getMessage(self) {
180 return truncate(inspect(self.actual), 128) + ' ' +
181 self.operator + ' ' +
182 truncate(inspect(self.expected), 128);
183}
184
185// At present only the three keys mentioned above are used and
186// understood by the spec. Implementations or sub modules can pass
187// other keys to the AssertionError's constructor - they will be
188// ignored.
189
190// 3. All of the following functions must throw an AssertionError
191// when a corresponding condition is not met, with a message that
192// may be undefined if not provided. All assertion methods provide
193// both the actual and expected values to the assertion error for
194// display purposes.
195
196function fail(actual, expected, message, operator, stackStartFunction) {
197 throw new assert.AssertionError({
198 message: message,
199 actual: actual,
200 expected: expected,
201 operator: operator,
202 stackStartFunction: stackStartFunction
203 });
204}
205
206// EXTENSION! allows for well behaved errors defined elsewhere.
207assert.fail = fail;
208
209// 4. Pure assertion tests whether a value is truthy, as determined
210// by !!guard.
211// assert.ok(guard, message_opt);
212// This statement is equivalent to assert.equal(true, !!guard,
213// message_opt);. To test strictly for the value true, use
214// assert.strictEqual(true, guard, message_opt);.
215
216function ok(value, message) {
217 if (!value) fail(value, true, message, '==', assert.ok);
218}
219assert.ok = ok;
220
221// 5. The equality assertion tests shallow, coercive equality with
222// ==.
223// assert.equal(actual, expected, message_opt);
224
225assert.equal = function equal(actual, expected, message) {
226 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
227};
228
229// 6. The non-equality assertion tests for whether two objects are not equal
230// with != assert.notEqual(actual, expected, message_opt);
231
232assert.notEqual = function notEqual(actual, expected, message) {
233 if (actual == expected) {
234 fail(actual, expected, message, '!=', assert.notEqual);
235 }
236};
237
238// 7. The equivalence assertion tests a deep equality relation.
239// assert.deepEqual(actual, expected, message_opt);
240
241assert.deepEqual = function deepEqual(actual, expected, message) {
242 if (!_deepEqual(actual, expected, false)) {
243 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
244 }
245};
246
247assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
248 if (!_deepEqual(actual, expected, true)) {
249 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
250 }
251};
252
253function _deepEqual(actual, expected, strict, memos) {
254 // 7.1. All identical values are equivalent, as determined by ===.
255 if (actual === expected) {
256 return true;
257 } else if (isBuffer(actual) && isBuffer(expected)) {
258 return compare(actual, expected) === 0;
259
260 // 7.2. If the expected value is a Date object, the actual value is
261 // equivalent if it is also a Date object that refers to the same time.
262 } else if (util.isDate(actual) && util.isDate(expected)) {
263 return actual.getTime() === expected.getTime();
264
265 // 7.3 If the expected value is a RegExp object, the actual value is
266 // equivalent if it is also a RegExp object with the same source and
267 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
268 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
269 return actual.source === expected.source &&
270 actual.global === expected.global &&
271 actual.multiline === expected.multiline &&
272 actual.lastIndex === expected.lastIndex &&
273 actual.ignoreCase === expected.ignoreCase;
274
275 // 7.4. Other pairs that do not both pass typeof value == 'object',
276 // equivalence is determined by ==.
277 } else if ((actual === null || typeof actual !== 'object') &&
278 (expected === null || typeof expected !== 'object')) {
279 return strict ? actual === expected : actual == expected;
280
281 // If both values are instances of typed arrays, wrap their underlying
282 // ArrayBuffers in a Buffer each to increase performance
283 // This optimization requires the arrays to have the same type as checked by
284 // Object.prototype.toString (aka pToString). Never perform binary
285 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
286 // bit patterns are not identical.
287 } else if (isView(actual) && isView(expected) &&
288 pToString(actual) === pToString(expected) &&
289 !(actual instanceof Float32Array ||
290 actual instanceof Float64Array)) {
291 return compare(new Uint8Array(actual.buffer),
292 new Uint8Array(expected.buffer)) === 0;
293
294 // 7.5 For all other Object pairs, including Array objects, equivalence is
295 // determined by having the same number of owned properties (as verified
296 // with Object.prototype.hasOwnProperty.call), the same set of keys
297 // (although not necessarily the same order), equivalent values for every
298 // corresponding key, and an identical 'prototype' property. Note: this
299 // accounts for both named and indexed properties on Arrays.
300 } else if (isBuffer(actual) !== isBuffer(expected)) {
301 return false;
302 } else {
303 memos = memos || {actual: [], expected: []};
304
305 var actualIndex = memos.actual.indexOf(actual);
306 if (actualIndex !== -1) {
307 if (actualIndex === memos.expected.indexOf(expected)) {
308 return true;
309 }
310 }
311
312 memos.actual.push(actual);
313 memos.expected.push(expected);
314
315 return objEquiv(actual, expected, strict, memos);
316 }
317}
318
319function isArguments(object) {
320 return Object.prototype.toString.call(object) == '[object Arguments]';
321}
322
323function objEquiv(a, b, strict, actualVisitedObjects) {
324 if (a === null || a === undefined || b === null || b === undefined)
325 return false;
326 // if one is a primitive, the other must be same
327 if (util.isPrimitive(a) || util.isPrimitive(b))
328 return a === b;
329 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
330 return false;
331 var aIsArgs = isArguments(a);
332 var bIsArgs = isArguments(b);
333 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
334 return false;
335 if (aIsArgs) {
336 a = pSlice.call(a);
337 b = pSlice.call(b);
338 return _deepEqual(a, b, strict);
339 }
340 var ka = objectKeys(a);
341 var kb = objectKeys(b);
342 var key, i;
343 // having the same number of owned properties (keys incorporates
344 // hasOwnProperty)
345 if (ka.length !== kb.length)
346 return false;
347 //the same set of keys (although not necessarily the same order),
348 ka.sort();
349 kb.sort();
350 //~~~cheap key test
351 for (i = ka.length - 1; i >= 0; i--) {
352 if (ka[i] !== kb[i])
353 return false;
354 }
355 //equivalent values for every corresponding key, and
356 //~~~possibly expensive deep test
357 for (i = ka.length - 1; i >= 0; i--) {
358 key = ka[i];
359 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
360 return false;
361 }
362 return true;
363}
364
365// 8. The non-equivalence assertion tests for any deep inequality.
366// assert.notDeepEqual(actual, expected, message_opt);
367
368assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
369 if (_deepEqual(actual, expected, false)) {
370 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
371 }
372};
373
374assert.notDeepStrictEqual = notDeepStrictEqual;
375function notDeepStrictEqual(actual, expected, message) {
376 if (_deepEqual(actual, expected, true)) {
377 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
378 }
379}
380
381
382// 9. The strict equality assertion tests strict equality, as determined by ===.
383// assert.strictEqual(actual, expected, message_opt);
384
385assert.strictEqual = function strictEqual(actual, expected, message) {
386 if (actual !== expected) {
387 fail(actual, expected, message, '===', assert.strictEqual);
388 }
389};
390
391// 10. The strict non-equality assertion tests for strict inequality, as
392// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
393
394assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
395 if (actual === expected) {
396 fail(actual, expected, message, '!==', assert.notStrictEqual);
397 }
398};
399
400function expectedException(actual, expected) {
401 if (!actual || !expected) {
402 return false;
403 }
404
405 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
406 return expected.test(actual);
407 }
408
409 try {
410 if (actual instanceof expected) {
411 return true;
412 }
413 } catch (e) {
414 // Ignore. The instanceof check doesn't work for arrow functions.
415 }
416
417 if (Error.isPrototypeOf(expected)) {
418 return false;
419 }
420
421 return expected.call({}, actual) === true;
422}
423
424function _tryBlock(block) {
425 var error;
426 try {
427 block();
428 } catch (e) {
429 error = e;
430 }
431 return error;
432}
433
434function _throws(shouldThrow, block, expected, message) {
435 var actual;
436
437 if (typeof block !== 'function') {
438 throw new TypeError('"block" argument must be a function');
439 }
440
441 if (typeof expected === 'string') {
442 message = expected;
443 expected = null;
444 }
445
446 actual = _tryBlock(block);
447
448 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
449 (message ? ' ' + message : '.');
450
451 if (shouldThrow && !actual) {
452 fail(actual, expected, 'Missing expected exception' + message);
453 }
454
455 var userProvidedMessage = typeof message === 'string';
456 var isUnwantedException = !shouldThrow && util.isError(actual);
457 var isUnexpectedException = !shouldThrow && actual && !expected;
458
459 if ((isUnwantedException &&
460 userProvidedMessage &&
461 expectedException(actual, expected)) ||
462 isUnexpectedException) {
463 fail(actual, expected, 'Got unwanted exception' + message);
464 }
465
466 if ((shouldThrow && actual && expected &&
467 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
468 throw actual;
469 }
470}
471
472// 11. Expected to throw an error:
473// assert.throws(block, Error_opt, message_opt);
474
475assert.throws = function(block, /*optional*/error, /*optional*/message) {
476 _throws(true, block, error, message);
477};
478
479// EXTENSION! This is annoying to write outside this module.
480assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
481 _throws(false, block, error, message);
482};
483
484assert.ifError = function(err) { if (err) throw err; };
485
486var objectKeys = Object.keys || function (obj) {
487 var keys = [];
488 for (var key in obj) {
489 if (hasOwn.call(obj, key)) keys.push(key);
490 }
491 return keys;
492};
493
494}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
495},{"util/":4}],2:[function(require,module,exports){
496if (typeof Object.create === 'function') {
497 // implementation from standard node.js 'util' module
498 module.exports = function inherits(ctor, superCtor) {
499 ctor.super_ = superCtor
500 ctor.prototype = Object.create(superCtor.prototype, {
501 constructor: {
502 value: ctor,
503 enumerable: false,
504 writable: true,
505 configurable: true
506 }
507 });
508 };
509} else {
510 // old school shim for old browsers
511 module.exports = function inherits(ctor, superCtor) {
512 ctor.super_ = superCtor
513 var TempCtor = function () {}
514 TempCtor.prototype = superCtor.prototype
515 ctor.prototype = new TempCtor()
516 ctor.prototype.constructor = ctor
517 }
518}
519
520},{}],3:[function(require,module,exports){
521module.exports = function isBuffer(arg) {
522 return arg && typeof arg === 'object'
523 && typeof arg.copy === 'function'
524 && typeof arg.fill === 'function'
525 && typeof arg.readUInt8 === 'function';
526}
527},{}],4:[function(require,module,exports){
528(function (process,global){
529// Copyright Joyent, Inc. and other Node contributors.
530//
531// Permission is hereby granted, free of charge, to any person obtaining a
532// copy of this software and associated documentation files (the
533// "Software"), to deal in the Software without restriction, including
534// without limitation the rights to use, copy, modify, merge, publish,
535// distribute, sublicense, and/or sell copies of the Software, and to permit
536// persons to whom the Software is furnished to do so, subject to the
537// following conditions:
538//
539// The above copyright notice and this permission notice shall be included
540// in all copies or substantial portions of the Software.
541//
542// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
543// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
544// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
545// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
546// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
547// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
548// USE OR OTHER DEALINGS IN THE SOFTWARE.
549
550var formatRegExp = /%[sdj%]/g;
551exports.format = function(f) {
552 if (!isString(f)) {
553 var objects = [];
554 for (var i = 0; i < arguments.length; i++) {
555 objects.push(inspect(arguments[i]));
556 }
557 return objects.join(' ');
558 }
559
560 var i = 1;
561 var args = arguments;
562 var len = args.length;
563 var str = String(f).replace(formatRegExp, function(x) {
564 if (x === '%%') return '%';
565 if (i >= len) return x;
566 switch (x) {
567 case '%s': return String(args[i++]);
568 case '%d': return Number(args[i++]);
569 case '%j':
570 try {
571 return JSON.stringify(args[i++]);
572 } catch (_) {
573 return '[Circular]';
574 }
575 default:
576 return x;
577 }
578 });
579 for (var x = args[i]; i < len; x = args[++i]) {
580 if (isNull(x) || !isObject(x)) {
581 str += ' ' + x;
582 } else {
583 str += ' ' + inspect(x);
584 }
585 }
586 return str;
587};
588
589
590// Mark that a method should not be used.
591// Returns a modified function which warns once by default.
592// If --no-deprecation is set, then it is a no-op.
593exports.deprecate = function(fn, msg) {
594 // Allow for deprecating things in the process of starting up.
595 if (isUndefined(global.process)) {
596 return function() {
597 return exports.deprecate(fn, msg).apply(this, arguments);
598 };
599 }
600
601 if (process.noDeprecation === true) {
602 return fn;
603 }
604
605 var warned = false;
606 function deprecated() {
607 if (!warned) {
608 if (process.throwDeprecation) {
609 throw new Error(msg);
610 } else if (process.traceDeprecation) {
611 console.trace(msg);
612 } else {
613 console.error(msg);
614 }
615 warned = true;
616 }
617 return fn.apply(this, arguments);
618 }
619
620 return deprecated;
621};
622
623
624var debugs = {};
625var debugEnviron;
626exports.debuglog = function(set) {
627 if (isUndefined(debugEnviron))
628 debugEnviron = process.env.NODE_DEBUG || '';
629 set = set.toUpperCase();
630 if (!debugs[set]) {
631 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
632 var pid = process.pid;
633 debugs[set] = function() {
634 var msg = exports.format.apply(exports, arguments);
635 console.error('%s %d: %s', set, pid, msg);
636 };
637 } else {
638 debugs[set] = function() {};
639 }
640 }
641 return debugs[set];
642};
643
644
645/**
646 * Echos the value of a value. Trys to print the value out
647 * in the best way possible given the different types.
648 *
649 * @param {Object} obj The object to print out.
650 * @param {Object} opts Optional options object that alters the output.
651 */
652/* legacy: obj, showHidden, depth, colors*/
653function inspect(obj, opts) {
654 // default options
655 var ctx = {
656 seen: [],
657 stylize: stylizeNoColor
658 };
659 // legacy...
660 if (arguments.length >= 3) ctx.depth = arguments[2];
661 if (arguments.length >= 4) ctx.colors = arguments[3];
662 if (isBoolean(opts)) {
663 // legacy...
664 ctx.showHidden = opts;
665 } else if (opts) {
666 // got an "options" object
667 exports._extend(ctx, opts);
668 }
669 // set default options
670 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
671 if (isUndefined(ctx.depth)) ctx.depth = 2;
672 if (isUndefined(ctx.colors)) ctx.colors = false;
673 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
674 if (ctx.colors) ctx.stylize = stylizeWithColor;
675 return formatValue(ctx, obj, ctx.depth);
676}
677exports.inspect = inspect;
678
679
680// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
681inspect.colors = {
682 'bold' : [1, 22],
683 'italic' : [3, 23],
684 'underline' : [4, 24],
685 'inverse' : [7, 27],
686 'white' : [37, 39],
687 'grey' : [90, 39],
688 'black' : [30, 39],
689 'blue' : [34, 39],
690 'cyan' : [36, 39],
691 'green' : [32, 39],
692 'magenta' : [35, 39],
693 'red' : [31, 39],
694 'yellow' : [33, 39]
695};
696
697// Don't use 'blue' not visible on cmd.exe
698inspect.styles = {
699 'special': 'cyan',
700 'number': 'yellow',
701 'boolean': 'yellow',
702 'undefined': 'grey',
703 'null': 'bold',
704 'string': 'green',
705 'date': 'magenta',
706 // "name": intentionally not styling
707 'regexp': 'red'
708};
709
710
711function stylizeWithColor(str, styleType) {
712 var style = inspect.styles[styleType];
713
714 if (style) {
715 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
716 '\u001b[' + inspect.colors[style][1] + 'm';
717 } else {
718 return str;
719 }
720}
721
722
723function stylizeNoColor(str, styleType) {
724 return str;
725}
726
727
728function arrayToHash(array) {
729 var hash = {};
730
731 array.forEach(function(val, idx) {
732 hash[val] = true;
733 });
734
735 return hash;
736}
737
738
739function formatValue(ctx, value, recurseTimes) {
740 // Provide a hook for user-specified inspect functions.
741 // Check that value is an object with an inspect function on it
742 if (ctx.customInspect &&
743 value &&
744 isFunction(value.inspect) &&
745 // Filter out the util module, it's inspect function is special
746 value.inspect !== exports.inspect &&
747 // Also filter out any prototype objects using the circular check.
748 !(value.constructor && value.constructor.prototype === value)) {
749 var ret = value.inspect(recurseTimes, ctx);
750 if (!isString(ret)) {
751 ret = formatValue(ctx, ret, recurseTimes);
752 }
753 return ret;
754 }
755
756 // Primitive types cannot have properties
757 var primitive = formatPrimitive(ctx, value);
758 if (primitive) {
759 return primitive;
760 }
761
762 // Look up the keys of the object.
763 var keys = Object.keys(value);
764 var visibleKeys = arrayToHash(keys);
765
766 if (ctx.showHidden) {
767 keys = Object.getOwnPropertyNames(value);
768 }
769
770 // IE doesn't make error fields non-enumerable
771 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
772 if (isError(value)
773 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
774 return formatError(value);
775 }
776
777 // Some type of object without properties can be shortcutted.
778 if (keys.length === 0) {
779 if (isFunction(value)) {
780 var name = value.name ? ': ' + value.name : '';
781 return ctx.stylize('[Function' + name + ']', 'special');
782 }
783 if (isRegExp(value)) {
784 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
785 }
786 if (isDate(value)) {
787 return ctx.stylize(Date.prototype.toString.call(value), 'date');
788 }
789 if (isError(value)) {
790 return formatError(value);
791 }
792 }
793
794 var base = '', array = false, braces = ['{', '}'];
795
796 // Make Array say that they are Array
797 if (isArray(value)) {
798 array = true;
799 braces = ['[', ']'];
800 }
801
802 // Make functions say that they are functions
803 if (isFunction(value)) {
804 var n = value.name ? ': ' + value.name : '';
805 base = ' [Function' + n + ']';
806 }
807
808 // Make RegExps say that they are RegExps
809 if (isRegExp(value)) {
810 base = ' ' + RegExp.prototype.toString.call(value);
811 }
812
813 // Make dates with properties first say the date
814 if (isDate(value)) {
815 base = ' ' + Date.prototype.toUTCString.call(value);
816 }
817
818 // Make error with message first say the error
819 if (isError(value)) {
820 base = ' ' + formatError(value);
821 }
822
823 if (keys.length === 0 && (!array || value.length == 0)) {
824 return braces[0] + base + braces[1];
825 }
826
827 if (recurseTimes < 0) {
828 if (isRegExp(value)) {
829 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
830 } else {
831 return ctx.stylize('[Object]', 'special');
832 }
833 }
834
835 ctx.seen.push(value);
836
837 var output;
838 if (array) {
839 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
840 } else {
841 output = keys.map(function(key) {
842 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
843 });
844 }
845
846 ctx.seen.pop();
847
848 return reduceToSingleString(output, base, braces);
849}
850
851
852function formatPrimitive(ctx, value) {
853 if (isUndefined(value))
854 return ctx.stylize('undefined', 'undefined');
855 if (isString(value)) {
856 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
857 .replace(/'/g, "\\'")
858 .replace(/\\"/g, '"') + '\'';
859 return ctx.stylize(simple, 'string');
860 }
861 if (isNumber(value))
862 return ctx.stylize('' + value, 'number');
863 if (isBoolean(value))
864 return ctx.stylize('' + value, 'boolean');
865 // For some reason typeof null is "object", so special case here.
866 if (isNull(value))
867 return ctx.stylize('null', 'null');
868}
869
870
871function formatError(value) {
872 return '[' + Error.prototype.toString.call(value) + ']';
873}
874
875
876function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
877 var output = [];
878 for (var i = 0, l = value.length; i < l; ++i) {
879 if (hasOwnProperty(value, String(i))) {
880 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
881 String(i), true));
882 } else {
883 output.push('');
884 }
885 }
886 keys.forEach(function(key) {
887 if (!key.match(/^\d+$/)) {
888 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
889 key, true));
890 }
891 });
892 return output;
893}
894
895
896function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
897 var name, str, desc;
898 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
899 if (desc.get) {
900 if (desc.set) {
901 str = ctx.stylize('[Getter/Setter]', 'special');
902 } else {
903 str = ctx.stylize('[Getter]', 'special');
904 }
905 } else {
906 if (desc.set) {
907 str = ctx.stylize('[Setter]', 'special');
908 }
909 }
910 if (!hasOwnProperty(visibleKeys, key)) {
911 name = '[' + key + ']';
912 }
913 if (!str) {
914 if (ctx.seen.indexOf(desc.value) < 0) {
915 if (isNull(recurseTimes)) {
916 str = formatValue(ctx, desc.value, null);
917 } else {
918 str = formatValue(ctx, desc.value, recurseTimes - 1);
919 }
920 if (str.indexOf('\n') > -1) {
921 if (array) {
922 str = str.split('\n').map(function(line) {
923 return ' ' + line;
924 }).join('\n').substr(2);
925 } else {
926 str = '\n' + str.split('\n').map(function(line) {
927 return ' ' + line;
928 }).join('\n');
929 }
930 }
931 } else {
932 str = ctx.stylize('[Circular]', 'special');
933 }
934 }
935 if (isUndefined(name)) {
936 if (array && key.match(/^\d+$/)) {
937 return str;
938 }
939 name = JSON.stringify('' + key);
940 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
941 name = name.substr(1, name.length - 2);
942 name = ctx.stylize(name, 'name');
943 } else {
944 name = name.replace(/'/g, "\\'")
945 .replace(/\\"/g, '"')
946 .replace(/(^"|"$)/g, "'");
947 name = ctx.stylize(name, 'string');
948 }
949 }
950
951 return name + ': ' + str;
952}
953
954
955function reduceToSingleString(output, base, braces) {
956 var numLinesEst = 0;
957 var length = output.reduce(function(prev, cur) {
958 numLinesEst++;
959 if (cur.indexOf('\n') >= 0) numLinesEst++;
960 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
961 }, 0);
962
963 if (length > 60) {
964 return braces[0] +
965 (base === '' ? '' : base + '\n ') +
966 ' ' +
967 output.join(',\n ') +
968 ' ' +
969 braces[1];
970 }
971
972 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
973}
974
975
976// NOTE: These type checking functions intentionally don't use `instanceof`
977// because it is fragile and can be easily faked with `Object.create()`.
978function isArray(ar) {
979 return Array.isArray(ar);
980}
981exports.isArray = isArray;
982
983function isBoolean(arg) {
984 return typeof arg === 'boolean';
985}
986exports.isBoolean = isBoolean;
987
988function isNull(arg) {
989 return arg === null;
990}
991exports.isNull = isNull;
992
993function isNullOrUndefined(arg) {
994 return arg == null;
995}
996exports.isNullOrUndefined = isNullOrUndefined;
997
998function isNumber(arg) {
999 return typeof arg === 'number';
1000}
1001exports.isNumber = isNumber;
1002
1003function isString(arg) {
1004 return typeof arg === 'string';
1005}
1006exports.isString = isString;
1007
1008function isSymbol(arg) {
1009 return typeof arg === 'symbol';
1010}
1011exports.isSymbol = isSymbol;
1012
1013function isUndefined(arg) {
1014 return arg === void 0;
1015}
1016exports.isUndefined = isUndefined;
1017
1018function isRegExp(re) {
1019 return isObject(re) && objectToString(re) === '[object RegExp]';
1020}
1021exports.isRegExp = isRegExp;
1022
1023function isObject(arg) {
1024 return typeof arg === 'object' && arg !== null;
1025}
1026exports.isObject = isObject;
1027
1028function isDate(d) {
1029 return isObject(d) && objectToString(d) === '[object Date]';
1030}
1031exports.isDate = isDate;
1032
1033function isError(e) {
1034 return isObject(e) &&
1035 (objectToString(e) === '[object Error]' || e instanceof Error);
1036}
1037exports.isError = isError;
1038
1039function isFunction(arg) {
1040 return typeof arg === 'function';
1041}
1042exports.isFunction = isFunction;
1043
1044function isPrimitive(arg) {
1045 return arg === null ||
1046 typeof arg === 'boolean' ||
1047 typeof arg === 'number' ||
1048 typeof arg === 'string' ||
1049 typeof arg === 'symbol' || // ES6 symbol
1050 typeof arg === 'undefined';
1051}
1052exports.isPrimitive = isPrimitive;
1053
1054exports.isBuffer = require('./support/isBuffer');
1055
1056function objectToString(o) {
1057 return Object.prototype.toString.call(o);
1058}
1059
1060
1061function pad(n) {
1062 return n < 10 ? '0' + n.toString(10) : n.toString(10);
1063}
1064
1065
1066var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
1067 'Oct', 'Nov', 'Dec'];
1068
1069// 26 Feb 16:19:34
1070function timestamp() {
1071 var d = new Date();
1072 var time = [pad(d.getHours()),
1073 pad(d.getMinutes()),
1074 pad(d.getSeconds())].join(':');
1075 return [d.getDate(), months[d.getMonth()], time].join(' ');
1076}
1077
1078
1079// log is just a thin wrapper to console.log that prepends a timestamp
1080exports.log = function() {
1081 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
1082};
1083
1084
1085/**
1086 * Inherit the prototype methods from one constructor into another.
1087 *
1088 * The Function.prototype.inherits from lang.js rewritten as a standalone
1089 * function (not on Function.prototype). NOTE: If this file is to be loaded
1090 * during bootstrapping this function needs to be rewritten using some native
1091 * functions as prototype setup using normal JavaScript does not work as
1092 * expected during bootstrapping (see mirror.js in r114903).
1093 *
1094 * @param {function} ctor Constructor function which needs to inherit the
1095 * prototype.
1096 * @param {function} superCtor Constructor function to inherit prototype from.
1097 */
1098exports.inherits = require('inherits');
1099
1100exports._extend = function(origin, add) {
1101 // Don't do anything if add isn't an object
1102 if (!add || !isObject(add)) return origin;
1103
1104 var keys = Object.keys(add);
1105 var i = keys.length;
1106 while (i--) {
1107 origin[keys[i]] = add[keys[i]];
1108 }
1109 return origin;
1110};
1111
1112function hasOwnProperty(obj, prop) {
1113 return Object.prototype.hasOwnProperty.call(obj, prop);
1114}
1115
1116}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1117},{"./support/isBuffer":3,"_process":28,"inherits":2}],5:[function(require,module,exports){
1118'use strict'
1119
1120exports.byteLength = byteLength
1121exports.toByteArray = toByteArray
1122exports.fromByteArray = fromByteArray
1123
1124var lookup = []
1125var revLookup = []
1126var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
1127
1128var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1129for (var i = 0, len = code.length; i < len; ++i) {
1130 lookup[i] = code[i]
1131 revLookup[code.charCodeAt(i)] = i
1132}
1133
1134// Support decoding URL-safe base64 strings, as Node.js does.
1135// See: https://en.wikipedia.org/wiki/Base64#URL_applications
1136revLookup['-'.charCodeAt(0)] = 62
1137revLookup['_'.charCodeAt(0)] = 63
1138
1139function getLens (b64) {
1140 var len = b64.length
1141
1142 if (len % 4 > 0) {
1143 throw new Error('Invalid string. Length must be a multiple of 4')
1144 }
1145
1146 // Trim off extra bytes after placeholder bytes are found
1147 // See: https://github.com/beatgammit/base64-js/issues/42
1148 var validLen = b64.indexOf('=')
1149 if (validLen === -1) validLen = len
1150
1151 var placeHoldersLen = validLen === len
1152 ? 0
1153 : 4 - (validLen % 4)
1154
1155 return [validLen, placeHoldersLen]
1156}
1157
1158// base64 is 4/3 + up to two characters of the original data
1159function byteLength (b64) {
1160 var lens = getLens(b64)
1161 var validLen = lens[0]
1162 var placeHoldersLen = lens[1]
1163 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1164}
1165
1166function _byteLength (b64, validLen, placeHoldersLen) {
1167 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1168}
1169
1170function toByteArray (b64) {
1171 var tmp
1172 var lens = getLens(b64)
1173 var validLen = lens[0]
1174 var placeHoldersLen = lens[1]
1175
1176 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1177
1178 var curByte = 0
1179
1180 // if there are placeholders, only get up to the last complete 4 chars
1181 var len = placeHoldersLen > 0
1182 ? validLen - 4
1183 : validLen
1184
1185 for (var i = 0; i < len; i += 4) {
1186 tmp =
1187 (revLookup[b64.charCodeAt(i)] << 18) |
1188 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1189 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1190 revLookup[b64.charCodeAt(i + 3)]
1191 arr[curByte++] = (tmp >> 16) & 0xFF
1192 arr[curByte++] = (tmp >> 8) & 0xFF
1193 arr[curByte++] = tmp & 0xFF
1194 }
1195
1196 if (placeHoldersLen === 2) {
1197 tmp =
1198 (revLookup[b64.charCodeAt(i)] << 2) |
1199 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1200 arr[curByte++] = tmp & 0xFF
1201 }
1202
1203 if (placeHoldersLen === 1) {
1204 tmp =
1205 (revLookup[b64.charCodeAt(i)] << 10) |
1206 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1207 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1208 arr[curByte++] = (tmp >> 8) & 0xFF
1209 arr[curByte++] = tmp & 0xFF
1210 }
1211
1212 return arr
1213}
1214
1215function tripletToBase64 (num) {
1216 return lookup[num >> 18 & 0x3F] +
1217 lookup[num >> 12 & 0x3F] +
1218 lookup[num >> 6 & 0x3F] +
1219 lookup[num & 0x3F]
1220}
1221
1222function encodeChunk (uint8, start, end) {
1223 var tmp
1224 var output = []
1225 for (var i = start; i < end; i += 3) {
1226 tmp =
1227 ((uint8[i] << 16) & 0xFF0000) +
1228 ((uint8[i + 1] << 8) & 0xFF00) +
1229 (uint8[i + 2] & 0xFF)
1230 output.push(tripletToBase64(tmp))
1231 }
1232 return output.join('')
1233}
1234
1235function fromByteArray (uint8) {
1236 var tmp
1237 var len = uint8.length
1238 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1239 var parts = []
1240 var maxChunkLength = 16383 // must be multiple of 3
1241
1242 // go through the array every three bytes, we'll deal with trailing stuff later
1243 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1244 parts.push(encodeChunk(
1245 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
1246 ))
1247 }
1248
1249 // pad the end with zeros, but make sure to not forget the extra bytes
1250 if (extraBytes === 1) {
1251 tmp = uint8[len - 1]
1252 parts.push(
1253 lookup[tmp >> 2] +
1254 lookup[(tmp << 4) & 0x3F] +
1255 '=='
1256 )
1257 } else if (extraBytes === 2) {
1258 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1259 parts.push(
1260 lookup[tmp >> 10] +
1261 lookup[(tmp >> 4) & 0x3F] +
1262 lookup[(tmp << 2) & 0x3F] +
1263 '='
1264 )
1265 }
1266
1267 return parts.join('')
1268}
1269
1270},{}],6:[function(require,module,exports){
1271
1272},{}],7:[function(require,module,exports){
1273(function (process,Buffer){
1274'use strict';
1275/* eslint camelcase: "off" */
1276
1277var assert = require('assert');
1278
1279var Zstream = require('pako/lib/zlib/zstream');
1280var zlib_deflate = require('pako/lib/zlib/deflate.js');
1281var zlib_inflate = require('pako/lib/zlib/inflate.js');
1282var constants = require('pako/lib/zlib/constants');
1283
1284for (var key in constants) {
1285 exports[key] = constants[key];
1286}
1287
1288// zlib modes
1289exports.NONE = 0;
1290exports.DEFLATE = 1;
1291exports.INFLATE = 2;
1292exports.GZIP = 3;
1293exports.GUNZIP = 4;
1294exports.DEFLATERAW = 5;
1295exports.INFLATERAW = 6;
1296exports.UNZIP = 7;
1297
1298var GZIP_HEADER_ID1 = 0x1f;
1299var GZIP_HEADER_ID2 = 0x8b;
1300
1301/**
1302 * Emulate Node's zlib C++ layer for use by the JS layer in index.js
1303 */
1304function Zlib(mode) {
1305 if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
1306 throw new TypeError('Bad argument');
1307 }
1308
1309 this.dictionary = null;
1310 this.err = 0;
1311 this.flush = 0;
1312 this.init_done = false;
1313 this.level = 0;
1314 this.memLevel = 0;
1315 this.mode = mode;
1316 this.strategy = 0;
1317 this.windowBits = 0;
1318 this.write_in_progress = false;
1319 this.pending_close = false;
1320 this.gzip_id_bytes_read = 0;
1321}
1322
1323Zlib.prototype.close = function () {
1324 if (this.write_in_progress) {
1325 this.pending_close = true;
1326 return;
1327 }
1328
1329 this.pending_close = false;
1330
1331 assert(this.init_done, 'close before init');
1332 assert(this.mode <= exports.UNZIP);
1333
1334 if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
1335 zlib_deflate.deflateEnd(this.strm);
1336 } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
1337 zlib_inflate.inflateEnd(this.strm);
1338 }
1339
1340 this.mode = exports.NONE;
1341
1342 this.dictionary = null;
1343};
1344
1345Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
1346 return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
1347};
1348
1349Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
1350 return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
1351};
1352
1353Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
1354 assert.equal(arguments.length, 8);
1355
1356 assert(this.init_done, 'write before init');
1357 assert(this.mode !== exports.NONE, 'already finalized');
1358 assert.equal(false, this.write_in_progress, 'write already in progress');
1359 assert.equal(false, this.pending_close, 'close is pending');
1360
1361 this.write_in_progress = true;
1362
1363 assert.equal(false, flush === undefined, 'must provide flush value');
1364
1365 this.write_in_progress = true;
1366
1367 if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
1368 throw new Error('Invalid flush value');
1369 }
1370
1371 if (input == null) {
1372 input = Buffer.alloc(0);
1373 in_len = 0;
1374 in_off = 0;
1375 }
1376
1377 this.strm.avail_in = in_len;
1378 this.strm.input = input;
1379 this.strm.next_in = in_off;
1380 this.strm.avail_out = out_len;
1381 this.strm.output = out;
1382 this.strm.next_out = out_off;
1383 this.flush = flush;
1384
1385 if (!async) {
1386 // sync version
1387 this._process();
1388
1389 if (this._checkError()) {
1390 return this._afterSync();
1391 }
1392 return;
1393 }
1394
1395 // async version
1396 var self = this;
1397 process.nextTick(function () {
1398 self._process();
1399 self._after();
1400 });
1401
1402 return this;
1403};
1404
1405Zlib.prototype._afterSync = function () {
1406 var avail_out = this.strm.avail_out;
1407 var avail_in = this.strm.avail_in;
1408
1409 this.write_in_progress = false;
1410
1411 return [avail_in, avail_out];
1412};
1413
1414Zlib.prototype._process = function () {
1415 var next_expected_header_byte = null;
1416
1417 // If the avail_out is left at 0, then it means that it ran out
1418 // of room. If there was avail_out left over, then it means
1419 // that all of the input was consumed.
1420 switch (this.mode) {
1421 case exports.DEFLATE:
1422 case exports.GZIP:
1423 case exports.DEFLATERAW:
1424 this.err = zlib_deflate.deflate(this.strm, this.flush);
1425 break;
1426 case exports.UNZIP:
1427 if (this.strm.avail_in > 0) {
1428 next_expected_header_byte = this.strm.next_in;
1429 }
1430
1431 switch (this.gzip_id_bytes_read) {
1432 case 0:
1433 if (next_expected_header_byte === null) {
1434 break;
1435 }
1436
1437 if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
1438 this.gzip_id_bytes_read = 1;
1439 next_expected_header_byte++;
1440
1441 if (this.strm.avail_in === 1) {
1442 // The only available byte was already read.
1443 break;
1444 }
1445 } else {
1446 this.mode = exports.INFLATE;
1447 break;
1448 }
1449
1450 // fallthrough
1451 case 1:
1452 if (next_expected_header_byte === null) {
1453 break;
1454 }
1455
1456 if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
1457 this.gzip_id_bytes_read = 2;
1458 this.mode = exports.GUNZIP;
1459 } else {
1460 // There is no actual difference between INFLATE and INFLATERAW
1461 // (after initialization).
1462 this.mode = exports.INFLATE;
1463 }
1464
1465 break;
1466 default:
1467 throw new Error('invalid number of gzip magic number bytes read');
1468 }
1469
1470 // fallthrough
1471 case exports.INFLATE:
1472 case exports.GUNZIP:
1473 case exports.INFLATERAW:
1474 this.err = zlib_inflate.inflate(this.strm, this.flush
1475
1476 // If data was encoded with dictionary
1477 );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
1478 // Load it
1479 this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
1480 if (this.err === exports.Z_OK) {
1481 // And try to decode again
1482 this.err = zlib_inflate.inflate(this.strm, this.flush);
1483 } else if (this.err === exports.Z_DATA_ERROR) {
1484 // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
1485 // Make it possible for After() to tell a bad dictionary from bad
1486 // input.
1487 this.err = exports.Z_NEED_DICT;
1488 }
1489 }
1490 while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
1491 // Bytes remain in input buffer. Perhaps this is another compressed
1492 // member in the same archive, or just trailing garbage.
1493 // Trailing zero bytes are okay, though, since they are frequently
1494 // used for padding.
1495
1496 this.reset();
1497 this.err = zlib_inflate.inflate(this.strm, this.flush);
1498 }
1499 break;
1500 default:
1501 throw new Error('Unknown mode ' + this.mode);
1502 }
1503};
1504
1505Zlib.prototype._checkError = function () {
1506 // Acceptable error states depend on the type of zlib stream.
1507 switch (this.err) {
1508 case exports.Z_OK:
1509 case exports.Z_BUF_ERROR:
1510 if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
1511 this._error('unexpected end of file');
1512 return false;
1513 }
1514 break;
1515 case exports.Z_STREAM_END:
1516 // normal statuses, not fatal
1517 break;
1518 case exports.Z_NEED_DICT:
1519 if (this.dictionary == null) {
1520 this._error('Missing dictionary');
1521 } else {
1522 this._error('Bad dictionary');
1523 }
1524 return false;
1525 default:
1526 // something else.
1527 this._error('Zlib error');
1528 return false;
1529 }
1530
1531 return true;
1532};
1533
1534Zlib.prototype._after = function () {
1535 if (!this._checkError()) {
1536 return;
1537 }
1538
1539 var avail_out = this.strm.avail_out;
1540 var avail_in = this.strm.avail_in;
1541
1542 this.write_in_progress = false;
1543
1544 // call the write() cb
1545 this.callback(avail_in, avail_out);
1546
1547 if (this.pending_close) {
1548 this.close();
1549 }
1550};
1551
1552Zlib.prototype._error = function (message) {
1553 if (this.strm.msg) {
1554 message = this.strm.msg;
1555 }
1556 this.onerror(message, this.err
1557
1558 // no hope of rescue.
1559 );this.write_in_progress = false;
1560 if (this.pending_close) {
1561 this.close();
1562 }
1563};
1564
1565Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
1566 assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
1567
1568 assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
1569 assert(level >= -1 && level <= 9, 'invalid compression level');
1570
1571 assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
1572
1573 assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');
1574
1575 this._init(level, windowBits, memLevel, strategy, dictionary);
1576 this._setDictionary();
1577};
1578
1579Zlib.prototype.params = function () {
1580 throw new Error('deflateParams Not supported');
1581};
1582
1583Zlib.prototype.reset = function () {
1584 this._reset();
1585 this._setDictionary();
1586};
1587
1588Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
1589 this.level = level;
1590 this.windowBits = windowBits;
1591 this.memLevel = memLevel;
1592 this.strategy = strategy;
1593
1594 this.flush = exports.Z_NO_FLUSH;
1595
1596 this.err = exports.Z_OK;
1597
1598 if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
1599 this.windowBits += 16;
1600 }
1601
1602 if (this.mode === exports.UNZIP) {
1603 this.windowBits += 32;
1604 }
1605
1606 if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
1607 this.windowBits = -1 * this.windowBits;
1608 }
1609
1610 this.strm = new Zstream();
1611
1612 switch (this.mode) {
1613 case exports.DEFLATE:
1614 case exports.GZIP:
1615 case exports.DEFLATERAW:
1616 this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
1617 break;
1618 case exports.INFLATE:
1619 case exports.GUNZIP:
1620 case exports.INFLATERAW:
1621 case exports.UNZIP:
1622 this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
1623 break;
1624 default:
1625 throw new Error('Unknown mode ' + this.mode);
1626 }
1627
1628 if (this.err !== exports.Z_OK) {
1629 this._error('Init error');
1630 }
1631
1632 this.dictionary = dictionary;
1633
1634 this.write_in_progress = false;
1635 this.init_done = true;
1636};
1637
1638Zlib.prototype._setDictionary = function () {
1639 if (this.dictionary == null) {
1640 return;
1641 }
1642
1643 this.err = exports.Z_OK;
1644
1645 switch (this.mode) {
1646 case exports.DEFLATE:
1647 case exports.DEFLATERAW:
1648 this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
1649 break;
1650 default:
1651 break;
1652 }
1653
1654 if (this.err !== exports.Z_OK) {
1655 this._error('Failed to set dictionary');
1656 }
1657};
1658
1659Zlib.prototype._reset = function () {
1660 this.err = exports.Z_OK;
1661
1662 switch (this.mode) {
1663 case exports.DEFLATE:
1664 case exports.DEFLATERAW:
1665 case exports.GZIP:
1666 this.err = zlib_deflate.deflateReset(this.strm);
1667 break;
1668 case exports.INFLATE:
1669 case exports.INFLATERAW:
1670 case exports.GUNZIP:
1671 this.err = zlib_inflate.inflateReset(this.strm);
1672 break;
1673 default:
1674 break;
1675 }
1676
1677 if (this.err !== exports.Z_OK) {
1678 this._error('Failed to reset stream');
1679 }
1680};
1681
1682exports.Zlib = Zlib;
1683}).call(this,require('_process'),require("buffer").Buffer)
1684},{"_process":28,"assert":1,"buffer":9,"pako/lib/zlib/constants":18,"pako/lib/zlib/deflate.js":20,"pako/lib/zlib/inflate.js":22,"pako/lib/zlib/zstream":26}],8:[function(require,module,exports){
1685(function (process){
1686'use strict';
1687
1688var Buffer = require('buffer').Buffer;
1689var Transform = require('stream').Transform;
1690var binding = require('./binding');
1691var util = require('util');
1692var assert = require('assert').ok;
1693var kMaxLength = require('buffer').kMaxLength;
1694var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
1695
1696// zlib doesn't provide these, so kludge them in following the same
1697// const naming scheme zlib uses.
1698binding.Z_MIN_WINDOWBITS = 8;
1699binding.Z_MAX_WINDOWBITS = 15;
1700binding.Z_DEFAULT_WINDOWBITS = 15;
1701
1702// fewer than 64 bytes per chunk is stupid.
1703// technically it could work with as few as 8, but even 64 bytes
1704// is absurdly low. Usually a MB or more is best.
1705binding.Z_MIN_CHUNK = 64;
1706binding.Z_MAX_CHUNK = Infinity;
1707binding.Z_DEFAULT_CHUNK = 16 * 1024;
1708
1709binding.Z_MIN_MEMLEVEL = 1;
1710binding.Z_MAX_MEMLEVEL = 9;
1711binding.Z_DEFAULT_MEMLEVEL = 8;
1712
1713binding.Z_MIN_LEVEL = -1;
1714binding.Z_MAX_LEVEL = 9;
1715binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
1716
1717// expose all the zlib constants
1718var bkeys = Object.keys(binding);
1719for (var bk = 0; bk < bkeys.length; bk++) {
1720 var bkey = bkeys[bk];
1721 if (bkey.match(/^Z/)) {
1722 Object.defineProperty(exports, bkey, {
1723 enumerable: true, value: binding[bkey], writable: false
1724 });
1725 }
1726}
1727
1728// translation table for return codes.
1729var codes = {
1730 Z_OK: binding.Z_OK,
1731 Z_STREAM_END: binding.Z_STREAM_END,
1732 Z_NEED_DICT: binding.Z_NEED_DICT,
1733 Z_ERRNO: binding.Z_ERRNO,
1734 Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
1735 Z_DATA_ERROR: binding.Z_DATA_ERROR,
1736 Z_MEM_ERROR: binding.Z_MEM_ERROR,
1737 Z_BUF_ERROR: binding.Z_BUF_ERROR,
1738 Z_VERSION_ERROR: binding.Z_VERSION_ERROR
1739};
1740
1741var ckeys = Object.keys(codes);
1742for (var ck = 0; ck < ckeys.length; ck++) {
1743 var ckey = ckeys[ck];
1744 codes[codes[ckey]] = ckey;
1745}
1746
1747Object.defineProperty(exports, 'codes', {
1748 enumerable: true, value: Object.freeze(codes), writable: false
1749});
1750
1751exports.Deflate = Deflate;
1752exports.Inflate = Inflate;
1753exports.Gzip = Gzip;
1754exports.Gunzip = Gunzip;
1755exports.DeflateRaw = DeflateRaw;
1756exports.InflateRaw = InflateRaw;
1757exports.Unzip = Unzip;
1758
1759exports.createDeflate = function (o) {
1760 return new Deflate(o);
1761};
1762
1763exports.createInflate = function (o) {
1764 return new Inflate(o);
1765};
1766
1767exports.createDeflateRaw = function (o) {
1768 return new DeflateRaw(o);
1769};
1770
1771exports.createInflateRaw = function (o) {
1772 return new InflateRaw(o);
1773};
1774
1775exports.createGzip = function (o) {
1776 return new Gzip(o);
1777};
1778
1779exports.createGunzip = function (o) {
1780 return new Gunzip(o);
1781};
1782
1783exports.createUnzip = function (o) {
1784 return new Unzip(o);
1785};
1786
1787// Convenience methods.
1788// compress/decompress a string or buffer in one step.
1789exports.deflate = function (buffer, opts, callback) {
1790 if (typeof opts === 'function') {
1791 callback = opts;
1792 opts = {};
1793 }
1794 return zlibBuffer(new Deflate(opts), buffer, callback);
1795};
1796
1797exports.deflateSync = function (buffer, opts) {
1798 return zlibBufferSync(new Deflate(opts), buffer);
1799};
1800
1801exports.gzip = function (buffer, opts, callback) {
1802 if (typeof opts === 'function') {
1803 callback = opts;
1804 opts = {};
1805 }
1806 return zlibBuffer(new Gzip(opts), buffer, callback);
1807};
1808
1809exports.gzipSync = function (buffer, opts) {
1810 return zlibBufferSync(new Gzip(opts), buffer);
1811};
1812
1813exports.deflateRaw = function (buffer, opts, callback) {
1814 if (typeof opts === 'function') {
1815 callback = opts;
1816 opts = {};
1817 }
1818 return zlibBuffer(new DeflateRaw(opts), buffer, callback);
1819};
1820
1821exports.deflateRawSync = function (buffer, opts) {
1822 return zlibBufferSync(new DeflateRaw(opts), buffer);
1823};
1824
1825exports.unzip = function (buffer, opts, callback) {
1826 if (typeof opts === 'function') {
1827 callback = opts;
1828 opts = {};
1829 }
1830 return zlibBuffer(new Unzip(opts), buffer, callback);
1831};
1832
1833exports.unzipSync = function (buffer, opts) {
1834 return zlibBufferSync(new Unzip(opts), buffer);
1835};
1836
1837exports.inflate = function (buffer, opts, callback) {
1838 if (typeof opts === 'function') {
1839 callback = opts;
1840 opts = {};
1841 }
1842 return zlibBuffer(new Inflate(opts), buffer, callback);
1843};
1844
1845exports.inflateSync = function (buffer, opts) {
1846 return zlibBufferSync(new Inflate(opts), buffer);
1847};
1848
1849exports.gunzip = function (buffer, opts, callback) {
1850 if (typeof opts === 'function') {
1851 callback = opts;
1852 opts = {};
1853 }
1854 return zlibBuffer(new Gunzip(opts), buffer, callback);
1855};
1856
1857exports.gunzipSync = function (buffer, opts) {
1858 return zlibBufferSync(new Gunzip(opts), buffer);
1859};
1860
1861exports.inflateRaw = function (buffer, opts, callback) {
1862 if (typeof opts === 'function') {
1863 callback = opts;
1864 opts = {};
1865 }
1866 return zlibBuffer(new InflateRaw(opts), buffer, callback);
1867};
1868
1869exports.inflateRawSync = function (buffer, opts) {
1870 return zlibBufferSync(new InflateRaw(opts), buffer);
1871};
1872
1873function zlibBuffer(engine, buffer, callback) {
1874 var buffers = [];
1875 var nread = 0;
1876
1877 engine.on('error', onError);
1878 engine.on('end', onEnd);
1879
1880 engine.end(buffer);
1881 flow();
1882
1883 function flow() {
1884 var chunk;
1885 while (null !== (chunk = engine.read())) {
1886 buffers.push(chunk);
1887 nread += chunk.length;
1888 }
1889 engine.once('readable', flow);
1890 }
1891
1892 function onError(err) {
1893 engine.removeListener('end', onEnd);
1894 engine.removeListener('readable', flow);
1895 callback(err);
1896 }
1897
1898 function onEnd() {
1899 var buf;
1900 var err = null;
1901
1902 if (nread >= kMaxLength) {
1903 err = new RangeError(kRangeErrorMessage);
1904 } else {
1905 buf = Buffer.concat(buffers, nread);
1906 }
1907
1908 buffers = [];
1909 engine.close();
1910 callback(err, buf);
1911 }
1912}
1913
1914function zlibBufferSync(engine, buffer) {
1915 if (typeof buffer === 'string') buffer = Buffer.from(buffer);
1916
1917 if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
1918
1919 var flushFlag = engine._finishFlushFlag;
1920
1921 return engine._processChunk(buffer, flushFlag);
1922}
1923
1924// generic zlib
1925// minimal 2-byte header
1926function Deflate(opts) {
1927 if (!(this instanceof Deflate)) return new Deflate(opts);
1928 Zlib.call(this, opts, binding.DEFLATE);
1929}
1930
1931function Inflate(opts) {
1932 if (!(this instanceof Inflate)) return new Inflate(opts);
1933 Zlib.call(this, opts, binding.INFLATE);
1934}
1935
1936// gzip - bigger header, same deflate compression
1937function Gzip(opts) {
1938 if (!(this instanceof Gzip)) return new Gzip(opts);
1939 Zlib.call(this, opts, binding.GZIP);
1940}
1941
1942function Gunzip(opts) {
1943 if (!(this instanceof Gunzip)) return new Gunzip(opts);
1944 Zlib.call(this, opts, binding.GUNZIP);
1945}
1946
1947// raw - no header
1948function DeflateRaw(opts) {
1949 if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
1950 Zlib.call(this, opts, binding.DEFLATERAW);
1951}
1952
1953function InflateRaw(opts) {
1954 if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
1955 Zlib.call(this, opts, binding.INFLATERAW);
1956}
1957
1958// auto-detect header.
1959function Unzip(opts) {
1960 if (!(this instanceof Unzip)) return new Unzip(opts);
1961 Zlib.call(this, opts, binding.UNZIP);
1962}
1963
1964function isValidFlushFlag(flag) {
1965 return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
1966}
1967
1968// the Zlib class they all inherit from
1969// This thing manages the queue of requests, and returns
1970// true or false if there is anything in the queue when
1971// you call the .write() method.
1972
1973function Zlib(opts, mode) {
1974 var _this = this;
1975
1976 this._opts = opts = opts || {};
1977 this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
1978
1979 Transform.call(this, opts);
1980
1981 if (opts.flush && !isValidFlushFlag(opts.flush)) {
1982 throw new Error('Invalid flush flag: ' + opts.flush);
1983 }
1984 if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
1985 throw new Error('Invalid flush flag: ' + opts.finishFlush);
1986 }
1987
1988 this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
1989 this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
1990
1991 if (opts.chunkSize) {
1992 if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
1993 throw new Error('Invalid chunk size: ' + opts.chunkSize);
1994 }
1995 }
1996
1997 if (opts.windowBits) {
1998 if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
1999 throw new Error('Invalid windowBits: ' + opts.windowBits);
2000 }
2001 }
2002
2003 if (opts.level) {
2004 if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
2005 throw new Error('Invalid compression level: ' + opts.level);
2006 }
2007 }
2008
2009 if (opts.memLevel) {
2010 if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
2011 throw new Error('Invalid memLevel: ' + opts.memLevel);
2012 }
2013 }
2014
2015 if (opts.strategy) {
2016 if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
2017 throw new Error('Invalid strategy: ' + opts.strategy);
2018 }
2019 }
2020
2021 if (opts.dictionary) {
2022 if (!Buffer.isBuffer(opts.dictionary)) {
2023 throw new Error('Invalid dictionary: it should be a Buffer instance');
2024 }
2025 }
2026
2027 this._handle = new binding.Zlib(mode);
2028
2029 var self = this;
2030 this._hadError = false;
2031 this._handle.onerror = function (message, errno) {
2032 // there is no way to cleanly recover.
2033 // continuing only obscures problems.
2034 _close(self);
2035 self._hadError = true;
2036
2037 var error = new Error(message);
2038 error.errno = errno;
2039 error.code = exports.codes[errno];
2040 self.emit('error', error);
2041 };
2042
2043 var level = exports.Z_DEFAULT_COMPRESSION;
2044 if (typeof opts.level === 'number') level = opts.level;
2045
2046 var strategy = exports.Z_DEFAULT_STRATEGY;
2047 if (typeof opts.strategy === 'number') strategy = opts.strategy;
2048
2049 this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
2050
2051 this._buffer = Buffer.allocUnsafe(this._chunkSize);
2052 this._offset = 0;
2053 this._level = level;
2054 this._strategy = strategy;
2055
2056 this.once('end', this.close);
2057
2058 Object.defineProperty(this, '_closed', {
2059 get: function () {
2060 return !_this._handle;
2061 },
2062 configurable: true,
2063 enumerable: true
2064 });
2065}
2066
2067util.inherits(Zlib, Transform);
2068
2069Zlib.prototype.params = function (level, strategy, callback) {
2070 if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
2071 throw new RangeError('Invalid compression level: ' + level);
2072 }
2073 if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
2074 throw new TypeError('Invalid strategy: ' + strategy);
2075 }
2076
2077 if (this._level !== level || this._strategy !== strategy) {
2078 var self = this;
2079 this.flush(binding.Z_SYNC_FLUSH, function () {
2080 assert(self._handle, 'zlib binding closed');
2081 self._handle.params(level, strategy);
2082 if (!self._hadError) {
2083 self._level = level;
2084 self._strategy = strategy;
2085 if (callback) callback();
2086 }
2087 });
2088 } else {
2089 process.nextTick(callback);
2090 }
2091};
2092
2093Zlib.prototype.reset = function () {
2094 assert(this._handle, 'zlib binding closed');
2095 return this._handle.reset();
2096};
2097
2098// This is the _flush function called by the transform class,
2099// internally, when the last chunk has been written.
2100Zlib.prototype._flush = function (callback) {
2101 this._transform(Buffer.alloc(0), '', callback);
2102};
2103
2104Zlib.prototype.flush = function (kind, callback) {
2105 var _this2 = this;
2106
2107 var ws = this._writableState;
2108
2109 if (typeof kind === 'function' || kind === undefined && !callback) {
2110 callback = kind;
2111 kind = binding.Z_FULL_FLUSH;
2112 }
2113
2114 if (ws.ended) {
2115 if (callback) process.nextTick(callback);
2116 } else if (ws.ending) {
2117 if (callback) this.once('end', callback);
2118 } else if (ws.needDrain) {
2119 if (callback) {
2120 this.once('drain', function () {
2121 return _this2.flush(kind, callback);
2122 });
2123 }
2124 } else {
2125 this._flushFlag = kind;
2126 this.write(Buffer.alloc(0), '', callback);
2127 }
2128};
2129
2130Zlib.prototype.close = function (callback) {
2131 _close(this, callback);
2132 process.nextTick(emitCloseNT, this);
2133};
2134
2135function _close(engine, callback) {
2136 if (callback) process.nextTick(callback);
2137
2138 // Caller may invoke .close after a zlib error (which will null _handle).
2139 if (!engine._handle) return;
2140
2141 engine._handle.close();
2142 engine._handle = null;
2143}
2144
2145function emitCloseNT(self) {
2146 self.emit('close');
2147}
2148
2149Zlib.prototype._transform = function (chunk, encoding, cb) {
2150 var flushFlag;
2151 var ws = this._writableState;
2152 var ending = ws.ending || ws.ended;
2153 var last = ending && (!chunk || ws.length === chunk.length);
2154
2155 if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
2156
2157 if (!this._handle) return cb(new Error('zlib binding closed'));
2158
2159 // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
2160 // (or whatever flag was provided using opts.finishFlush).
2161 // If it's explicitly flushing at some other time, then we use
2162 // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
2163 // goodness.
2164 if (last) flushFlag = this._finishFlushFlag;else {
2165 flushFlag = this._flushFlag;
2166 // once we've flushed the last of the queue, stop flushing and
2167 // go back to the normal behavior.
2168 if (chunk.length >= ws.length) {
2169 this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
2170 }
2171 }
2172
2173 this._processChunk(chunk, flushFlag, cb);
2174};
2175
2176Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
2177 var availInBefore = chunk && chunk.length;
2178 var availOutBefore = this._chunkSize - this._offset;
2179 var inOff = 0;
2180
2181 var self = this;
2182
2183 var async = typeof cb === 'function';
2184
2185 if (!async) {
2186 var buffers = [];
2187 var nread = 0;
2188
2189 var error;
2190 this.on('error', function (er) {
2191 error = er;
2192 });
2193
2194 assert(this._handle, 'zlib binding closed');
2195 do {
2196 var res = this._handle.writeSync(flushFlag, chunk, // in
2197 inOff, // in_off
2198 availInBefore, // in_len
2199 this._buffer, // out
2200 this._offset, //out_off
2201 availOutBefore); // out_len
2202 } while (!this._hadError && callback(res[0], res[1]));
2203
2204 if (this._hadError) {
2205 throw error;
2206 }
2207
2208 if (nread >= kMaxLength) {
2209 _close(this);
2210 throw new RangeError(kRangeErrorMessage);
2211 }
2212
2213 var buf = Buffer.concat(buffers, nread);
2214 _close(this);
2215
2216 return buf;
2217 }
2218
2219 assert(this._handle, 'zlib binding closed');
2220 var req = this._handle.write(flushFlag, chunk, // in
2221 inOff, // in_off
2222 availInBefore, // in_len
2223 this._buffer, // out
2224 this._offset, //out_off
2225 availOutBefore); // out_len
2226
2227 req.buffer = chunk;
2228 req.callback = callback;
2229
2230 function callback(availInAfter, availOutAfter) {
2231 // When the callback is used in an async write, the callback's
2232 // context is the `req` object that was created. The req object
2233 // is === this._handle, and that's why it's important to null
2234 // out the values after they are done being used. `this._handle`
2235 // can stay in memory longer than the callback and buffer are needed.
2236 if (this) {
2237 this.buffer = null;
2238 this.callback = null;
2239 }
2240
2241 if (self._hadError) return;
2242
2243 var have = availOutBefore - availOutAfter;
2244 assert(have >= 0, 'have should not go down');
2245
2246 if (have > 0) {
2247 var out = self._buffer.slice(self._offset, self._offset + have);
2248 self._offset += have;
2249 // serve some output to the consumer.
2250 if (async) {
2251 self.push(out);
2252 } else {
2253 buffers.push(out);
2254 nread += out.length;
2255 }
2256 }
2257
2258 // exhausted the output buffer, or used all the input create a new one.
2259 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
2260 availOutBefore = self._chunkSize;
2261 self._offset = 0;
2262 self._buffer = Buffer.allocUnsafe(self._chunkSize);
2263 }
2264
2265 if (availOutAfter === 0) {
2266 // Not actually done. Need to reprocess.
2267 // Also, update the availInBefore to the availInAfter value,
2268 // so that if we have to hit it a third (fourth, etc.) time,
2269 // it'll have the correct byte counts.
2270 inOff += availInBefore - availInAfter;
2271 availInBefore = availInAfter;
2272
2273 if (!async) return true;
2274
2275 var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
2276 newReq.callback = callback; // this same function
2277 newReq.buffer = chunk;
2278 return;
2279 }
2280
2281 if (!async) return false;
2282
2283 // finished with the chunk.
2284 cb();
2285 }
2286};
2287
2288util.inherits(Deflate, Zlib);
2289util.inherits(Inflate, Zlib);
2290util.inherits(Gzip, Zlib);
2291util.inherits(Gunzip, Zlib);
2292util.inherits(DeflateRaw, Zlib);
2293util.inherits(InflateRaw, Zlib);
2294util.inherits(Unzip, Zlib);
2295}).call(this,require('_process'))
2296},{"./binding":7,"_process":28,"assert":1,"buffer":9,"stream":43,"util":48}],9:[function(require,module,exports){
2297/*!
2298 * The buffer module from node.js, for the browser.
2299 *
2300 * @author Feross Aboukhadijeh <https://feross.org>
2301 * @license MIT
2302 */
2303/* eslint-disable no-proto */
2304
2305'use strict'
2306
2307var base64 = require('base64-js')
2308var ieee754 = require('ieee754')
2309
2310exports.Buffer = Buffer
2311exports.SlowBuffer = SlowBuffer
2312exports.INSPECT_MAX_BYTES = 50
2313
2314var K_MAX_LENGTH = 0x7fffffff
2315exports.kMaxLength = K_MAX_LENGTH
2316
2317/**
2318 * If `Buffer.TYPED_ARRAY_SUPPORT`:
2319 * === true Use Uint8Array implementation (fastest)
2320 * === false Print warning and recommend using `buffer` v4.x which has an Object
2321 * implementation (most compatible, even IE6)
2322 *
2323 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
2324 * Opera 11.6+, iOS 4.2+.
2325 *
2326 * We report that the browser does not support typed arrays if the are not subclassable
2327 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
2328 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
2329 * for __proto__ and has a buggy typed array implementation.
2330 */
2331Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
2332
2333if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
2334 typeof console.error === 'function') {
2335 console.error(
2336 'This browser lacks typed array (Uint8Array) support which is required by ' +
2337 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
2338 )
2339}
2340
2341function typedArraySupport () {
2342 // Can typed array instances can be augmented?
2343 try {
2344 var arr = new Uint8Array(1)
2345 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
2346 return arr.foo() === 42
2347 } catch (e) {
2348 return false
2349 }
2350}
2351
2352Object.defineProperty(Buffer.prototype, 'parent', {
2353 get: function () {
2354 if (!(this instanceof Buffer)) {
2355 return undefined
2356 }
2357 return this.buffer
2358 }
2359})
2360
2361Object.defineProperty(Buffer.prototype, 'offset', {
2362 get: function () {
2363 if (!(this instanceof Buffer)) {
2364 return undefined
2365 }
2366 return this.byteOffset
2367 }
2368})
2369
2370function createBuffer (length) {
2371 if (length > K_MAX_LENGTH) {
2372 throw new RangeError('Invalid typed array length')
2373 }
2374 // Return an augmented `Uint8Array` instance
2375 var buf = new Uint8Array(length)
2376 buf.__proto__ = Buffer.prototype
2377 return buf
2378}
2379
2380/**
2381 * The Buffer constructor returns instances of `Uint8Array` that have their
2382 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
2383 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
2384 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
2385 * returns a single octet.
2386 *
2387 * The `Uint8Array` prototype remains unmodified.
2388 */
2389
2390function Buffer (arg, encodingOrOffset, length) {
2391 // Common case.
2392 if (typeof arg === 'number') {
2393 if (typeof encodingOrOffset === 'string') {
2394 throw new Error(
2395 'If encoding is specified then the first argument must be a string'
2396 )
2397 }
2398 return allocUnsafe(arg)
2399 }
2400 return from(arg, encodingOrOffset, length)
2401}
2402
2403// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
2404if (typeof Symbol !== 'undefined' && Symbol.species &&
2405 Buffer[Symbol.species] === Buffer) {
2406 Object.defineProperty(Buffer, Symbol.species, {
2407 value: null,
2408 configurable: true,
2409 enumerable: false,
2410 writable: false
2411 })
2412}
2413
2414Buffer.poolSize = 8192 // not used by this implementation
2415
2416function from (value, encodingOrOffset, length) {
2417 if (typeof value === 'number') {
2418 throw new TypeError('"value" argument must not be a number')
2419 }
2420
2421 if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) {
2422 return fromArrayBuffer(value, encodingOrOffset, length)
2423 }
2424
2425 if (typeof value === 'string') {
2426 return fromString(value, encodingOrOffset)
2427 }
2428
2429 return fromObject(value)
2430}
2431
2432/**
2433 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
2434 * if value is a number.
2435 * Buffer.from(str[, encoding])
2436 * Buffer.from(array)
2437 * Buffer.from(buffer)
2438 * Buffer.from(arrayBuffer[, byteOffset[, length]])
2439 **/
2440Buffer.from = function (value, encodingOrOffset, length) {
2441 return from(value, encodingOrOffset, length)
2442}
2443
2444// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
2445// https://github.com/feross/buffer/pull/148
2446Buffer.prototype.__proto__ = Uint8Array.prototype
2447Buffer.__proto__ = Uint8Array
2448
2449function assertSize (size) {
2450 if (typeof size !== 'number') {
2451 throw new TypeError('"size" argument must be of type number')
2452 } else if (size < 0) {
2453 throw new RangeError('"size" argument must not be negative')
2454 }
2455}
2456
2457function alloc (size, fill, encoding) {
2458 assertSize(size)
2459 if (size <= 0) {
2460 return createBuffer(size)
2461 }
2462 if (fill !== undefined) {
2463 // Only pay attention to encoding if it's a string. This
2464 // prevents accidentally sending in a number that would
2465 // be interpretted as a start offset.
2466 return typeof encoding === 'string'
2467 ? createBuffer(size).fill(fill, encoding)
2468 : createBuffer(size).fill(fill)
2469 }
2470 return createBuffer(size)
2471}
2472
2473/**
2474 * Creates a new filled Buffer instance.
2475 * alloc(size[, fill[, encoding]])
2476 **/
2477Buffer.alloc = function (size, fill, encoding) {
2478 return alloc(size, fill, encoding)
2479}
2480
2481function allocUnsafe (size) {
2482 assertSize(size)
2483 return createBuffer(size < 0 ? 0 : checked(size) | 0)
2484}
2485
2486/**
2487 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
2488 * */
2489Buffer.allocUnsafe = function (size) {
2490 return allocUnsafe(size)
2491}
2492/**
2493 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
2494 */
2495Buffer.allocUnsafeSlow = function (size) {
2496 return allocUnsafe(size)
2497}
2498
2499function fromString (string, encoding) {
2500 if (typeof encoding !== 'string' || encoding === '') {
2501 encoding = 'utf8'
2502 }
2503
2504 if (!Buffer.isEncoding(encoding)) {
2505 throw new TypeError('Unknown encoding: ' + encoding)
2506 }
2507
2508 var length = byteLength(string, encoding) | 0
2509 var buf = createBuffer(length)
2510
2511 var actual = buf.write(string, encoding)
2512
2513 if (actual !== length) {
2514 // Writing a hex string, for example, that contains invalid characters will
2515 // cause everything after the first invalid character to be ignored. (e.g.
2516 // 'abxxcd' will be treated as 'ab')
2517 buf = buf.slice(0, actual)
2518 }
2519
2520 return buf
2521}
2522
2523function fromArrayLike (array) {
2524 var length = array.length < 0 ? 0 : checked(array.length) | 0
2525 var buf = createBuffer(length)
2526 for (var i = 0; i < length; i += 1) {
2527 buf[i] = array[i] & 255
2528 }
2529 return buf
2530}
2531
2532function fromArrayBuffer (array, byteOffset, length) {
2533 if (byteOffset < 0 || array.byteLength < byteOffset) {
2534 throw new RangeError('"offset" is outside of buffer bounds')
2535 }
2536
2537 if (array.byteLength < byteOffset + (length || 0)) {
2538 throw new RangeError('"length" is outside of buffer bounds')
2539 }
2540
2541 var buf
2542 if (byteOffset === undefined && length === undefined) {
2543 buf = new Uint8Array(array)
2544 } else if (length === undefined) {
2545 buf = new Uint8Array(array, byteOffset)
2546 } else {
2547 buf = new Uint8Array(array, byteOffset, length)
2548 }
2549
2550 // Return an augmented `Uint8Array` instance
2551 buf.__proto__ = Buffer.prototype
2552 return buf
2553}
2554
2555function fromObject (obj) {
2556 if (Buffer.isBuffer(obj)) {
2557 var len = checked(obj.length) | 0
2558 var buf = createBuffer(len)
2559
2560 if (buf.length === 0) {
2561 return buf
2562 }
2563
2564 obj.copy(buf, 0, 0, len)
2565 return buf
2566 }
2567
2568 if (obj) {
2569 if (ArrayBuffer.isView(obj) || 'length' in obj) {
2570 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
2571 return createBuffer(0)
2572 }
2573 return fromArrayLike(obj)
2574 }
2575
2576 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
2577 return fromArrayLike(obj.data)
2578 }
2579 }
2580
2581 throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.')
2582}
2583
2584function checked (length) {
2585 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
2586 // length is NaN (which is otherwise coerced to zero.)
2587 if (length >= K_MAX_LENGTH) {
2588 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
2589 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
2590 }
2591 return length | 0
2592}
2593
2594function SlowBuffer (length) {
2595 if (+length != length) { // eslint-disable-line eqeqeq
2596 length = 0
2597 }
2598 return Buffer.alloc(+length)
2599}
2600
2601Buffer.isBuffer = function isBuffer (b) {
2602 return b != null && b._isBuffer === true
2603}
2604
2605Buffer.compare = function compare (a, b) {
2606 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
2607 throw new TypeError('Arguments must be Buffers')
2608 }
2609
2610 if (a === b) return 0
2611
2612 var x = a.length
2613 var y = b.length
2614
2615 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2616 if (a[i] !== b[i]) {
2617 x = a[i]
2618 y = b[i]
2619 break
2620 }
2621 }
2622
2623 if (x < y) return -1
2624 if (y < x) return 1
2625 return 0
2626}
2627
2628Buffer.isEncoding = function isEncoding (encoding) {
2629 switch (String(encoding).toLowerCase()) {
2630 case 'hex':
2631 case 'utf8':
2632 case 'utf-8':
2633 case 'ascii':
2634 case 'latin1':
2635 case 'binary':
2636 case 'base64':
2637 case 'ucs2':
2638 case 'ucs-2':
2639 case 'utf16le':
2640 case 'utf-16le':
2641 return true
2642 default:
2643 return false
2644 }
2645}
2646
2647Buffer.concat = function concat (list, length) {
2648 if (!Array.isArray(list)) {
2649 throw new TypeError('"list" argument must be an Array of Buffers')
2650 }
2651
2652 if (list.length === 0) {
2653 return Buffer.alloc(0)
2654 }
2655
2656 var i
2657 if (length === undefined) {
2658 length = 0
2659 for (i = 0; i < list.length; ++i) {
2660 length += list[i].length
2661 }
2662 }
2663
2664 var buffer = Buffer.allocUnsafe(length)
2665 var pos = 0
2666 for (i = 0; i < list.length; ++i) {
2667 var buf = list[i]
2668 if (ArrayBuffer.isView(buf)) {
2669 buf = Buffer.from(buf)
2670 }
2671 if (!Buffer.isBuffer(buf)) {
2672 throw new TypeError('"list" argument must be an Array of Buffers')
2673 }
2674 buf.copy(buffer, pos)
2675 pos += buf.length
2676 }
2677 return buffer
2678}
2679
2680function byteLength (string, encoding) {
2681 if (Buffer.isBuffer(string)) {
2682 return string.length
2683 }
2684 if (ArrayBuffer.isView(string) || isArrayBuffer(string)) {
2685 return string.byteLength
2686 }
2687 if (typeof string !== 'string') {
2688 string = '' + string
2689 }
2690
2691 var len = string.length
2692 if (len === 0) return 0
2693
2694 // Use a for loop to avoid recursion
2695 var loweredCase = false
2696 for (;;) {
2697 switch (encoding) {
2698 case 'ascii':
2699 case 'latin1':
2700 case 'binary':
2701 return len
2702 case 'utf8':
2703 case 'utf-8':
2704 case undefined:
2705 return utf8ToBytes(string).length
2706 case 'ucs2':
2707 case 'ucs-2':
2708 case 'utf16le':
2709 case 'utf-16le':
2710 return len * 2
2711 case 'hex':
2712 return len >>> 1
2713 case 'base64':
2714 return base64ToBytes(string).length
2715 default:
2716 if (loweredCase) return utf8ToBytes(string).length // assume utf8
2717 encoding = ('' + encoding).toLowerCase()
2718 loweredCase = true
2719 }
2720 }
2721}
2722Buffer.byteLength = byteLength
2723
2724function slowToString (encoding, start, end) {
2725 var loweredCase = false
2726
2727 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
2728 // property of a typed array.
2729
2730 // This behaves neither like String nor Uint8Array in that we set start/end
2731 // to their upper/lower bounds if the value passed is out of range.
2732 // undefined is handled specially as per ECMA-262 6th Edition,
2733 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
2734 if (start === undefined || start < 0) {
2735 start = 0
2736 }
2737 // Return early if start > this.length. Done here to prevent potential uint32
2738 // coercion fail below.
2739 if (start > this.length) {
2740 return ''
2741 }
2742
2743 if (end === undefined || end > this.length) {
2744 end = this.length
2745 }
2746
2747 if (end <= 0) {
2748 return ''
2749 }
2750
2751 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
2752 end >>>= 0
2753 start >>>= 0
2754
2755 if (end <= start) {
2756 return ''
2757 }
2758
2759 if (!encoding) encoding = 'utf8'
2760
2761 while (true) {
2762 switch (encoding) {
2763 case 'hex':
2764 return hexSlice(this, start, end)
2765
2766 case 'utf8':
2767 case 'utf-8':
2768 return utf8Slice(this, start, end)
2769
2770 case 'ascii':
2771 return asciiSlice(this, start, end)
2772
2773 case 'latin1':
2774 case 'binary':
2775 return latin1Slice(this, start, end)
2776
2777 case 'base64':
2778 return base64Slice(this, start, end)
2779
2780 case 'ucs2':
2781 case 'ucs-2':
2782 case 'utf16le':
2783 case 'utf-16le':
2784 return utf16leSlice(this, start, end)
2785
2786 default:
2787 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2788 encoding = (encoding + '').toLowerCase()
2789 loweredCase = true
2790 }
2791 }
2792}
2793
2794// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
2795// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
2796// reliably in a browserify context because there could be multiple different
2797// copies of the 'buffer' package in use. This method works even for Buffer
2798// instances that were created from another copy of the `buffer` package.
2799// See: https://github.com/feross/buffer/issues/154
2800Buffer.prototype._isBuffer = true
2801
2802function swap (b, n, m) {
2803 var i = b[n]
2804 b[n] = b[m]
2805 b[m] = i
2806}
2807
2808Buffer.prototype.swap16 = function swap16 () {
2809 var len = this.length
2810 if (len % 2 !== 0) {
2811 throw new RangeError('Buffer size must be a multiple of 16-bits')
2812 }
2813 for (var i = 0; i < len; i += 2) {
2814 swap(this, i, i + 1)
2815 }
2816 return this
2817}
2818
2819Buffer.prototype.swap32 = function swap32 () {
2820 var len = this.length
2821 if (len % 4 !== 0) {
2822 throw new RangeError('Buffer size must be a multiple of 32-bits')
2823 }
2824 for (var i = 0; i < len; i += 4) {
2825 swap(this, i, i + 3)
2826 swap(this, i + 1, i + 2)
2827 }
2828 return this
2829}
2830
2831Buffer.prototype.swap64 = function swap64 () {
2832 var len = this.length
2833 if (len % 8 !== 0) {
2834 throw new RangeError('Buffer size must be a multiple of 64-bits')
2835 }
2836 for (var i = 0; i < len; i += 8) {
2837 swap(this, i, i + 7)
2838 swap(this, i + 1, i + 6)
2839 swap(this, i + 2, i + 5)
2840 swap(this, i + 3, i + 4)
2841 }
2842 return this
2843}
2844
2845Buffer.prototype.toString = function toString () {
2846 var length = this.length
2847 if (length === 0) return ''
2848 if (arguments.length === 0) return utf8Slice(this, 0, length)
2849 return slowToString.apply(this, arguments)
2850}
2851
2852Buffer.prototype.toLocaleString = Buffer.prototype.toString
2853
2854Buffer.prototype.equals = function equals (b) {
2855 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2856 if (this === b) return true
2857 return Buffer.compare(this, b) === 0
2858}
2859
2860Buffer.prototype.inspect = function inspect () {
2861 var str = ''
2862 var max = exports.INSPECT_MAX_BYTES
2863 if (this.length > 0) {
2864 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
2865 if (this.length > max) str += ' ... '
2866 }
2867 return '<Buffer ' + str + '>'
2868}
2869
2870Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2871 if (!Buffer.isBuffer(target)) {
2872 throw new TypeError('Argument must be a Buffer')
2873 }
2874
2875 if (start === undefined) {
2876 start = 0
2877 }
2878 if (end === undefined) {
2879 end = target ? target.length : 0
2880 }
2881 if (thisStart === undefined) {
2882 thisStart = 0
2883 }
2884 if (thisEnd === undefined) {
2885 thisEnd = this.length
2886 }
2887
2888 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2889 throw new RangeError('out of range index')
2890 }
2891
2892 if (thisStart >= thisEnd && start >= end) {
2893 return 0
2894 }
2895 if (thisStart >= thisEnd) {
2896 return -1
2897 }
2898 if (start >= end) {
2899 return 1
2900 }
2901
2902 start >>>= 0
2903 end >>>= 0
2904 thisStart >>>= 0
2905 thisEnd >>>= 0
2906
2907 if (this === target) return 0
2908
2909 var x = thisEnd - thisStart
2910 var y = end - start
2911 var len = Math.min(x, y)
2912
2913 var thisCopy = this.slice(thisStart, thisEnd)
2914 var targetCopy = target.slice(start, end)
2915
2916 for (var i = 0; i < len; ++i) {
2917 if (thisCopy[i] !== targetCopy[i]) {
2918 x = thisCopy[i]
2919 y = targetCopy[i]
2920 break
2921 }
2922 }
2923
2924 if (x < y) return -1
2925 if (y < x) return 1
2926 return 0
2927}
2928
2929// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2930// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2931//
2932// Arguments:
2933// - buffer - a Buffer to search
2934// - val - a string, Buffer, or number
2935// - byteOffset - an index into `buffer`; will be clamped to an int32
2936// - encoding - an optional encoding, relevant is val is a string
2937// - dir - true for indexOf, false for lastIndexOf
2938function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2939 // Empty buffer means no match
2940 if (buffer.length === 0) return -1
2941
2942 // Normalize byteOffset
2943 if (typeof byteOffset === 'string') {
2944 encoding = byteOffset
2945 byteOffset = 0
2946 } else if (byteOffset > 0x7fffffff) {
2947 byteOffset = 0x7fffffff
2948 } else if (byteOffset < -0x80000000) {
2949 byteOffset = -0x80000000
2950 }
2951 byteOffset = +byteOffset // Coerce to Number.
2952 if (numberIsNaN(byteOffset)) {
2953 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2954 byteOffset = dir ? 0 : (buffer.length - 1)
2955 }
2956
2957 // Normalize byteOffset: negative offsets start from the end of the buffer
2958 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2959 if (byteOffset >= buffer.length) {
2960 if (dir) return -1
2961 else byteOffset = buffer.length - 1
2962 } else if (byteOffset < 0) {
2963 if (dir) byteOffset = 0
2964 else return -1
2965 }
2966
2967 // Normalize val
2968 if (typeof val === 'string') {
2969 val = Buffer.from(val, encoding)
2970 }
2971
2972 // Finally, search either indexOf (if dir is true) or lastIndexOf
2973 if (Buffer.isBuffer(val)) {
2974 // Special case: looking for empty string/buffer always fails
2975 if (val.length === 0) {
2976 return -1
2977 }
2978 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2979 } else if (typeof val === 'number') {
2980 val = val & 0xFF // Search for a byte value [0-255]
2981 if (typeof Uint8Array.prototype.indexOf === 'function') {
2982 if (dir) {
2983 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2984 } else {
2985 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2986 }
2987 }
2988 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
2989 }
2990
2991 throw new TypeError('val must be string, number or Buffer')
2992}
2993
2994function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2995 var indexSize = 1
2996 var arrLength = arr.length
2997 var valLength = val.length
2998
2999 if (encoding !== undefined) {
3000 encoding = String(encoding).toLowerCase()
3001 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
3002 encoding === 'utf16le' || encoding === 'utf-16le') {
3003 if (arr.length < 2 || val.length < 2) {
3004 return -1
3005 }
3006 indexSize = 2
3007 arrLength /= 2
3008 valLength /= 2
3009 byteOffset /= 2
3010 }
3011 }
3012
3013 function read (buf, i) {
3014 if (indexSize === 1) {
3015 return buf[i]
3016 } else {
3017 return buf.readUInt16BE(i * indexSize)
3018 }
3019 }
3020
3021 var i
3022 if (dir) {
3023 var foundIndex = -1
3024 for (i = byteOffset; i < arrLength; i++) {
3025 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
3026 if (foundIndex === -1) foundIndex = i
3027 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
3028 } else {
3029 if (foundIndex !== -1) i -= i - foundIndex
3030 foundIndex = -1
3031 }
3032 }
3033 } else {
3034 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
3035 for (i = byteOffset; i >= 0; i--) {
3036 var found = true
3037 for (var j = 0; j < valLength; j++) {
3038 if (read(arr, i + j) !== read(val, j)) {
3039 found = false
3040 break
3041 }
3042 }
3043 if (found) return i
3044 }
3045 }
3046
3047 return -1
3048}
3049
3050Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
3051 return this.indexOf(val, byteOffset, encoding) !== -1
3052}
3053
3054Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
3055 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
3056}
3057
3058Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
3059 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
3060}
3061
3062function hexWrite (buf, string, offset, length) {
3063 offset = Number(offset) || 0
3064 var remaining = buf.length - offset
3065 if (!length) {
3066 length = remaining
3067 } else {
3068 length = Number(length)
3069 if (length > remaining) {
3070 length = remaining
3071 }
3072 }
3073
3074 var strLen = string.length
3075
3076 if (length > strLen / 2) {
3077 length = strLen / 2
3078 }
3079 for (var i = 0; i < length; ++i) {
3080 var parsed = parseInt(string.substr(i * 2, 2), 16)
3081 if (numberIsNaN(parsed)) return i
3082 buf[offset + i] = parsed
3083 }
3084 return i
3085}
3086
3087function utf8Write (buf, string, offset, length) {
3088 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
3089}
3090
3091function asciiWrite (buf, string, offset, length) {
3092 return blitBuffer(asciiToBytes(string), buf, offset, length)
3093}
3094
3095function latin1Write (buf, string, offset, length) {
3096 return asciiWrite(buf, string, offset, length)
3097}
3098
3099function base64Write (buf, string, offset, length) {
3100 return blitBuffer(base64ToBytes(string), buf, offset, length)
3101}
3102
3103function ucs2Write (buf, string, offset, length) {
3104 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
3105}
3106
3107Buffer.prototype.write = function write (string, offset, length, encoding) {
3108 // Buffer#write(string)
3109 if (offset === undefined) {
3110 encoding = 'utf8'
3111 length = this.length
3112 offset = 0
3113 // Buffer#write(string, encoding)
3114 } else if (length === undefined && typeof offset === 'string') {
3115 encoding = offset
3116 length = this.length
3117 offset = 0
3118 // Buffer#write(string, offset[, length][, encoding])
3119 } else if (isFinite(offset)) {
3120 offset = offset >>> 0
3121 if (isFinite(length)) {
3122 length = length >>> 0
3123 if (encoding === undefined) encoding = 'utf8'
3124 } else {
3125 encoding = length
3126 length = undefined
3127 }
3128 } else {
3129 throw new Error(
3130 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
3131 )
3132 }
3133
3134 var remaining = this.length - offset
3135 if (length === undefined || length > remaining) length = remaining
3136
3137 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
3138 throw new RangeError('Attempt to write outside buffer bounds')
3139 }
3140
3141 if (!encoding) encoding = 'utf8'
3142
3143 var loweredCase = false
3144 for (;;) {
3145 switch (encoding) {
3146 case 'hex':
3147 return hexWrite(this, string, offset, length)
3148
3149 case 'utf8':
3150 case 'utf-8':
3151 return utf8Write(this, string, offset, length)
3152
3153 case 'ascii':
3154 return asciiWrite(this, string, offset, length)
3155
3156 case 'latin1':
3157 case 'binary':
3158 return latin1Write(this, string, offset, length)
3159
3160 case 'base64':
3161 // Warning: maxLength not taken into account in base64Write
3162 return base64Write(this, string, offset, length)
3163
3164 case 'ucs2':
3165 case 'ucs-2':
3166 case 'utf16le':
3167 case 'utf-16le':
3168 return ucs2Write(this, string, offset, length)
3169
3170 default:
3171 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
3172 encoding = ('' + encoding).toLowerCase()
3173 loweredCase = true
3174 }
3175 }
3176}
3177
3178Buffer.prototype.toJSON = function toJSON () {
3179 return {
3180 type: 'Buffer',
3181 data: Array.prototype.slice.call(this._arr || this, 0)
3182 }
3183}
3184
3185function base64Slice (buf, start, end) {
3186 if (start === 0 && end === buf.length) {
3187 return base64.fromByteArray(buf)
3188 } else {
3189 return base64.fromByteArray(buf.slice(start, end))
3190 }
3191}
3192
3193function utf8Slice (buf, start, end) {
3194 end = Math.min(buf.length, end)
3195 var res = []
3196
3197 var i = start
3198 while (i < end) {
3199 var firstByte = buf[i]
3200 var codePoint = null
3201 var bytesPerSequence = (firstByte > 0xEF) ? 4
3202 : (firstByte > 0xDF) ? 3
3203 : (firstByte > 0xBF) ? 2
3204 : 1
3205
3206 if (i + bytesPerSequence <= end) {
3207 var secondByte, thirdByte, fourthByte, tempCodePoint
3208
3209 switch (bytesPerSequence) {
3210 case 1:
3211 if (firstByte < 0x80) {
3212 codePoint = firstByte
3213 }
3214 break
3215 case 2:
3216 secondByte = buf[i + 1]
3217 if ((secondByte & 0xC0) === 0x80) {
3218 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
3219 if (tempCodePoint > 0x7F) {
3220 codePoint = tempCodePoint
3221 }
3222 }
3223 break
3224 case 3:
3225 secondByte = buf[i + 1]
3226 thirdByte = buf[i + 2]
3227 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
3228 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
3229 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
3230 codePoint = tempCodePoint
3231 }
3232 }
3233 break
3234 case 4:
3235 secondByte = buf[i + 1]
3236 thirdByte = buf[i + 2]
3237 fourthByte = buf[i + 3]
3238 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
3239 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
3240 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
3241 codePoint = tempCodePoint
3242 }
3243 }
3244 }
3245 }
3246
3247 if (codePoint === null) {
3248 // we did not generate a valid codePoint so insert a
3249 // replacement char (U+FFFD) and advance only 1 byte
3250 codePoint = 0xFFFD
3251 bytesPerSequence = 1
3252 } else if (codePoint > 0xFFFF) {
3253 // encode to utf16 (surrogate pair dance)
3254 codePoint -= 0x10000
3255 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
3256 codePoint = 0xDC00 | codePoint & 0x3FF
3257 }
3258
3259 res.push(codePoint)
3260 i += bytesPerSequence
3261 }
3262
3263 return decodeCodePointsArray(res)
3264}
3265
3266// Based on http://stackoverflow.com/a/22747272/680742, the browser with
3267// the lowest limit is Chrome, with 0x10000 args.
3268// We go 1 magnitude less, for safety
3269var MAX_ARGUMENTS_LENGTH = 0x1000
3270
3271function decodeCodePointsArray (codePoints) {
3272 var len = codePoints.length
3273 if (len <= MAX_ARGUMENTS_LENGTH) {
3274 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
3275 }
3276
3277 // Decode in chunks to avoid "call stack size exceeded".
3278 var res = ''
3279 var i = 0
3280 while (i < len) {
3281 res += String.fromCharCode.apply(
3282 String,
3283 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
3284 )
3285 }
3286 return res
3287}
3288
3289function asciiSlice (buf, start, end) {
3290 var ret = ''
3291 end = Math.min(buf.length, end)
3292
3293 for (var i = start; i < end; ++i) {
3294 ret += String.fromCharCode(buf[i] & 0x7F)
3295 }
3296 return ret
3297}
3298
3299function latin1Slice (buf, start, end) {
3300 var ret = ''
3301 end = Math.min(buf.length, end)
3302
3303 for (var i = start; i < end; ++i) {
3304 ret += String.fromCharCode(buf[i])
3305 }
3306 return ret
3307}
3308
3309function hexSlice (buf, start, end) {
3310 var len = buf.length
3311
3312 if (!start || start < 0) start = 0
3313 if (!end || end < 0 || end > len) end = len
3314
3315 var out = ''
3316 for (var i = start; i < end; ++i) {
3317 out += toHex(buf[i])
3318 }
3319 return out
3320}
3321
3322function utf16leSlice (buf, start, end) {
3323 var bytes = buf.slice(start, end)
3324 var res = ''
3325 for (var i = 0; i < bytes.length; i += 2) {
3326 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
3327 }
3328 return res
3329}
3330
3331Buffer.prototype.slice = function slice (start, end) {
3332 var len = this.length
3333 start = ~~start
3334 end = end === undefined ? len : ~~end
3335
3336 if (start < 0) {
3337 start += len
3338 if (start < 0) start = 0
3339 } else if (start > len) {
3340 start = len
3341 }
3342
3343 if (end < 0) {
3344 end += len
3345 if (end < 0) end = 0
3346 } else if (end > len) {
3347 end = len
3348 }
3349
3350 if (end < start) end = start
3351
3352 var newBuf = this.subarray(start, end)
3353 // Return an augmented `Uint8Array` instance
3354 newBuf.__proto__ = Buffer.prototype
3355 return newBuf
3356}
3357
3358/*
3359 * Need to make sure that buffer isn't trying to write out of bounds.
3360 */
3361function checkOffset (offset, ext, length) {
3362 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
3363 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
3364}
3365
3366Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
3367 offset = offset >>> 0
3368 byteLength = byteLength >>> 0
3369 if (!noAssert) checkOffset(offset, byteLength, this.length)
3370
3371 var val = this[offset]
3372 var mul = 1
3373 var i = 0
3374 while (++i < byteLength && (mul *= 0x100)) {
3375 val += this[offset + i] * mul
3376 }
3377
3378 return val
3379}
3380
3381Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
3382 offset = offset >>> 0
3383 byteLength = byteLength >>> 0
3384 if (!noAssert) {
3385 checkOffset(offset, byteLength, this.length)
3386 }
3387
3388 var val = this[offset + --byteLength]
3389 var mul = 1
3390 while (byteLength > 0 && (mul *= 0x100)) {
3391 val += this[offset + --byteLength] * mul
3392 }
3393
3394 return val
3395}
3396
3397Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
3398 offset = offset >>> 0
3399 if (!noAssert) checkOffset(offset, 1, this.length)
3400 return this[offset]
3401}
3402
3403Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
3404 offset = offset >>> 0
3405 if (!noAssert) checkOffset(offset, 2, this.length)
3406 return this[offset] | (this[offset + 1] << 8)
3407}
3408
3409Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
3410 offset = offset >>> 0
3411 if (!noAssert) checkOffset(offset, 2, this.length)
3412 return (this[offset] << 8) | this[offset + 1]
3413}
3414
3415Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
3416 offset = offset >>> 0
3417 if (!noAssert) checkOffset(offset, 4, this.length)
3418
3419 return ((this[offset]) |
3420 (this[offset + 1] << 8) |
3421 (this[offset + 2] << 16)) +
3422 (this[offset + 3] * 0x1000000)
3423}
3424
3425Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
3426 offset = offset >>> 0
3427 if (!noAssert) checkOffset(offset, 4, this.length)
3428
3429 return (this[offset] * 0x1000000) +
3430 ((this[offset + 1] << 16) |
3431 (this[offset + 2] << 8) |
3432 this[offset + 3])
3433}
3434
3435Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
3436 offset = offset >>> 0
3437 byteLength = byteLength >>> 0
3438 if (!noAssert) checkOffset(offset, byteLength, this.length)
3439
3440 var val = this[offset]
3441 var mul = 1
3442 var i = 0
3443 while (++i < byteLength && (mul *= 0x100)) {
3444 val += this[offset + i] * mul
3445 }
3446 mul *= 0x80
3447
3448 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
3449
3450 return val
3451}
3452
3453Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
3454 offset = offset >>> 0
3455 byteLength = byteLength >>> 0
3456 if (!noAssert) checkOffset(offset, byteLength, this.length)
3457
3458 var i = byteLength
3459 var mul = 1
3460 var val = this[offset + --i]
3461 while (i > 0 && (mul *= 0x100)) {
3462 val += this[offset + --i] * mul
3463 }
3464 mul *= 0x80
3465
3466 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
3467
3468 return val
3469}
3470
3471Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
3472 offset = offset >>> 0
3473 if (!noAssert) checkOffset(offset, 1, this.length)
3474 if (!(this[offset] & 0x80)) return (this[offset])
3475 return ((0xff - this[offset] + 1) * -1)
3476}
3477
3478Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
3479 offset = offset >>> 0
3480 if (!noAssert) checkOffset(offset, 2, this.length)
3481 var val = this[offset] | (this[offset + 1] << 8)
3482 return (val & 0x8000) ? val | 0xFFFF0000 : val
3483}
3484
3485Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
3486 offset = offset >>> 0
3487 if (!noAssert) checkOffset(offset, 2, this.length)
3488 var val = this[offset + 1] | (this[offset] << 8)
3489 return (val & 0x8000) ? val | 0xFFFF0000 : val
3490}
3491
3492Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
3493 offset = offset >>> 0
3494 if (!noAssert) checkOffset(offset, 4, this.length)
3495
3496 return (this[offset]) |
3497 (this[offset + 1] << 8) |
3498 (this[offset + 2] << 16) |
3499 (this[offset + 3] << 24)
3500}
3501
3502Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
3503 offset = offset >>> 0
3504 if (!noAssert) checkOffset(offset, 4, this.length)
3505
3506 return (this[offset] << 24) |
3507 (this[offset + 1] << 16) |
3508 (this[offset + 2] << 8) |
3509 (this[offset + 3])
3510}
3511
3512Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
3513 offset = offset >>> 0
3514 if (!noAssert) checkOffset(offset, 4, this.length)
3515 return ieee754.read(this, offset, true, 23, 4)
3516}
3517
3518Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
3519 offset = offset >>> 0
3520 if (!noAssert) checkOffset(offset, 4, this.length)
3521 return ieee754.read(this, offset, false, 23, 4)
3522}
3523
3524Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
3525 offset = offset >>> 0
3526 if (!noAssert) checkOffset(offset, 8, this.length)
3527 return ieee754.read(this, offset, true, 52, 8)
3528}
3529
3530Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
3531 offset = offset >>> 0
3532 if (!noAssert) checkOffset(offset, 8, this.length)
3533 return ieee754.read(this, offset, false, 52, 8)
3534}
3535
3536function checkInt (buf, value, offset, ext, max, min) {
3537 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
3538 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
3539 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3540}
3541
3542Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
3543 value = +value
3544 offset = offset >>> 0
3545 byteLength = byteLength >>> 0
3546 if (!noAssert) {
3547 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3548 checkInt(this, value, offset, byteLength, maxBytes, 0)
3549 }
3550
3551 var mul = 1
3552 var i = 0
3553 this[offset] = value & 0xFF
3554 while (++i < byteLength && (mul *= 0x100)) {
3555 this[offset + i] = (value / mul) & 0xFF
3556 }
3557
3558 return offset + byteLength
3559}
3560
3561Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
3562 value = +value
3563 offset = offset >>> 0
3564 byteLength = byteLength >>> 0
3565 if (!noAssert) {
3566 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3567 checkInt(this, value, offset, byteLength, maxBytes, 0)
3568 }
3569
3570 var i = byteLength - 1
3571 var mul = 1
3572 this[offset + i] = value & 0xFF
3573 while (--i >= 0 && (mul *= 0x100)) {
3574 this[offset + i] = (value / mul) & 0xFF
3575 }
3576
3577 return offset + byteLength
3578}
3579
3580Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
3581 value = +value
3582 offset = offset >>> 0
3583 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
3584 this[offset] = (value & 0xff)
3585 return offset + 1
3586}
3587
3588Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
3589 value = +value
3590 offset = offset >>> 0
3591 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3592 this[offset] = (value & 0xff)
3593 this[offset + 1] = (value >>> 8)
3594 return offset + 2
3595}
3596
3597Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
3598 value = +value
3599 offset = offset >>> 0
3600 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3601 this[offset] = (value >>> 8)
3602 this[offset + 1] = (value & 0xff)
3603 return offset + 2
3604}
3605
3606Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
3607 value = +value
3608 offset = offset >>> 0
3609 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3610 this[offset + 3] = (value >>> 24)
3611 this[offset + 2] = (value >>> 16)
3612 this[offset + 1] = (value >>> 8)
3613 this[offset] = (value & 0xff)
3614 return offset + 4
3615}
3616
3617Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
3618 value = +value
3619 offset = offset >>> 0
3620 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3621 this[offset] = (value >>> 24)
3622 this[offset + 1] = (value >>> 16)
3623 this[offset + 2] = (value >>> 8)
3624 this[offset + 3] = (value & 0xff)
3625 return offset + 4
3626}
3627
3628Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
3629 value = +value
3630 offset = offset >>> 0
3631 if (!noAssert) {
3632 var limit = Math.pow(2, (8 * byteLength) - 1)
3633
3634 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3635 }
3636
3637 var i = 0
3638 var mul = 1
3639 var sub = 0
3640 this[offset] = value & 0xFF
3641 while (++i < byteLength && (mul *= 0x100)) {
3642 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
3643 sub = 1
3644 }
3645 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3646 }
3647
3648 return offset + byteLength
3649}
3650
3651Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
3652 value = +value
3653 offset = offset >>> 0
3654 if (!noAssert) {
3655 var limit = Math.pow(2, (8 * byteLength) - 1)
3656
3657 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3658 }
3659
3660 var i = byteLength - 1
3661 var mul = 1
3662 var sub = 0
3663 this[offset + i] = value & 0xFF
3664 while (--i >= 0 && (mul *= 0x100)) {
3665 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
3666 sub = 1
3667 }
3668 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3669 }
3670
3671 return offset + byteLength
3672}
3673
3674Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
3675 value = +value
3676 offset = offset >>> 0
3677 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
3678 if (value < 0) value = 0xff + value + 1
3679 this[offset] = (value & 0xff)
3680 return offset + 1
3681}
3682
3683Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
3684 value = +value
3685 offset = offset >>> 0
3686 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3687 this[offset] = (value & 0xff)
3688 this[offset + 1] = (value >>> 8)
3689 return offset + 2
3690}
3691
3692Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
3693 value = +value
3694 offset = offset >>> 0
3695 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3696 this[offset] = (value >>> 8)
3697 this[offset + 1] = (value & 0xff)
3698 return offset + 2
3699}
3700
3701Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
3702 value = +value
3703 offset = offset >>> 0
3704 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3705 this[offset] = (value & 0xff)
3706 this[offset + 1] = (value >>> 8)
3707 this[offset + 2] = (value >>> 16)
3708 this[offset + 3] = (value >>> 24)
3709 return offset + 4
3710}
3711
3712Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
3713 value = +value
3714 offset = offset >>> 0
3715 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3716 if (value < 0) value = 0xffffffff + value + 1
3717 this[offset] = (value >>> 24)
3718 this[offset + 1] = (value >>> 16)
3719 this[offset + 2] = (value >>> 8)
3720 this[offset + 3] = (value & 0xff)
3721 return offset + 4
3722}
3723
3724function checkIEEE754 (buf, value, offset, ext, max, min) {
3725 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3726 if (offset < 0) throw new RangeError('Index out of range')
3727}
3728
3729function writeFloat (buf, value, offset, littleEndian, noAssert) {
3730 value = +value
3731 offset = offset >>> 0
3732 if (!noAssert) {
3733 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
3734 }
3735 ieee754.write(buf, value, offset, littleEndian, 23, 4)
3736 return offset + 4
3737}
3738
3739Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
3740 return writeFloat(this, value, offset, true, noAssert)
3741}
3742
3743Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
3744 return writeFloat(this, value, offset, false, noAssert)
3745}
3746
3747function writeDouble (buf, value, offset, littleEndian, noAssert) {
3748 value = +value
3749 offset = offset >>> 0
3750 if (!noAssert) {
3751 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
3752 }
3753 ieee754.write(buf, value, offset, littleEndian, 52, 8)
3754 return offset + 8
3755}
3756
3757Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
3758 return writeDouble(this, value, offset, true, noAssert)
3759}
3760
3761Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
3762 return writeDouble(this, value, offset, false, noAssert)
3763}
3764
3765// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3766Buffer.prototype.copy = function copy (target, targetStart, start, end) {
3767 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
3768 if (!start) start = 0
3769 if (!end && end !== 0) end = this.length
3770 if (targetStart >= target.length) targetStart = target.length
3771 if (!targetStart) targetStart = 0
3772 if (end > 0 && end < start) end = start
3773
3774 // Copy 0 bytes; we're done
3775 if (end === start) return 0
3776 if (target.length === 0 || this.length === 0) return 0
3777
3778 // Fatal error conditions
3779 if (targetStart < 0) {
3780 throw new RangeError('targetStart out of bounds')
3781 }
3782 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
3783 if (end < 0) throw new RangeError('sourceEnd out of bounds')
3784
3785 // Are we oob?
3786 if (end > this.length) end = this.length
3787 if (target.length - targetStart < end - start) {
3788 end = target.length - targetStart + start
3789 }
3790
3791 var len = end - start
3792
3793 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
3794 // Use built-in when available, missing from IE11
3795 this.copyWithin(targetStart, start, end)
3796 } else if (this === target && start < targetStart && targetStart < end) {
3797 // descending copy from end
3798 for (var i = len - 1; i >= 0; --i) {
3799 target[i + targetStart] = this[i + start]
3800 }
3801 } else {
3802 Uint8Array.prototype.set.call(
3803 target,
3804 this.subarray(start, end),
3805 targetStart
3806 )
3807 }
3808
3809 return len
3810}
3811
3812// Usage:
3813// buffer.fill(number[, offset[, end]])
3814// buffer.fill(buffer[, offset[, end]])
3815// buffer.fill(string[, offset[, end]][, encoding])
3816Buffer.prototype.fill = function fill (val, start, end, encoding) {
3817 // Handle string cases:
3818 if (typeof val === 'string') {
3819 if (typeof start === 'string') {
3820 encoding = start
3821 start = 0
3822 end = this.length
3823 } else if (typeof end === 'string') {
3824 encoding = end
3825 end = this.length
3826 }
3827 if (encoding !== undefined && typeof encoding !== 'string') {
3828 throw new TypeError('encoding must be a string')
3829 }
3830 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
3831 throw new TypeError('Unknown encoding: ' + encoding)
3832 }
3833 if (val.length === 1) {
3834 var code = val.charCodeAt(0)
3835 if ((encoding === 'utf8' && code < 128) ||
3836 encoding === 'latin1') {
3837 // Fast path: If `val` fits into a single byte, use that numeric value.
3838 val = code
3839 }
3840 }
3841 } else if (typeof val === 'number') {
3842 val = val & 255
3843 }
3844
3845 // Invalid ranges are not set to a default, so can range check early.
3846 if (start < 0 || this.length < start || this.length < end) {
3847 throw new RangeError('Out of range index')
3848 }
3849
3850 if (end <= start) {
3851 return this
3852 }
3853
3854 start = start >>> 0
3855 end = end === undefined ? this.length : end >>> 0
3856
3857 if (!val) val = 0
3858
3859 var i
3860 if (typeof val === 'number') {
3861 for (i = start; i < end; ++i) {
3862 this[i] = val
3863 }
3864 } else {
3865 var bytes = Buffer.isBuffer(val)
3866 ? val
3867 : new Buffer(val, encoding)
3868 var len = bytes.length
3869 if (len === 0) {
3870 throw new TypeError('The value "' + val +
3871 '" is invalid for argument "value"')
3872 }
3873 for (i = 0; i < end - start; ++i) {
3874 this[i + start] = bytes[i % len]
3875 }
3876 }
3877
3878 return this
3879}
3880
3881// HELPER FUNCTIONS
3882// ================
3883
3884var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3885
3886function base64clean (str) {
3887 // Node takes equal signs as end of the Base64 encoding
3888 str = str.split('=')[0]
3889 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3890 str = str.trim().replace(INVALID_BASE64_RE, '')
3891 // Node converts strings with length < 2 to ''
3892 if (str.length < 2) return ''
3893 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3894 while (str.length % 4 !== 0) {
3895 str = str + '='
3896 }
3897 return str
3898}
3899
3900function toHex (n) {
3901 if (n < 16) return '0' + n.toString(16)
3902 return n.toString(16)
3903}
3904
3905function utf8ToBytes (string, units) {
3906 units = units || Infinity
3907 var codePoint
3908 var length = string.length
3909 var leadSurrogate = null
3910 var bytes = []
3911
3912 for (var i = 0; i < length; ++i) {
3913 codePoint = string.charCodeAt(i)
3914
3915 // is surrogate component
3916 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3917 // last char was a lead
3918 if (!leadSurrogate) {
3919 // no lead yet
3920 if (codePoint > 0xDBFF) {
3921 // unexpected trail
3922 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3923 continue
3924 } else if (i + 1 === length) {
3925 // unpaired lead
3926 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3927 continue
3928 }
3929
3930 // valid lead
3931 leadSurrogate = codePoint
3932
3933 continue
3934 }
3935
3936 // 2 leads in a row
3937 if (codePoint < 0xDC00) {
3938 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3939 leadSurrogate = codePoint
3940 continue
3941 }
3942
3943 // valid surrogate pair
3944 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3945 } else if (leadSurrogate) {
3946 // valid bmp char, but last char was a lead
3947 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3948 }
3949
3950 leadSurrogate = null
3951
3952 // encode utf8
3953 if (codePoint < 0x80) {
3954 if ((units -= 1) < 0) break
3955 bytes.push(codePoint)
3956 } else if (codePoint < 0x800) {
3957 if ((units -= 2) < 0) break
3958 bytes.push(
3959 codePoint >> 0x6 | 0xC0,
3960 codePoint & 0x3F | 0x80
3961 )
3962 } else if (codePoint < 0x10000) {
3963 if ((units -= 3) < 0) break
3964 bytes.push(
3965 codePoint >> 0xC | 0xE0,
3966 codePoint >> 0x6 & 0x3F | 0x80,
3967 codePoint & 0x3F | 0x80
3968 )
3969 } else if (codePoint < 0x110000) {
3970 if ((units -= 4) < 0) break
3971 bytes.push(
3972 codePoint >> 0x12 | 0xF0,
3973 codePoint >> 0xC & 0x3F | 0x80,
3974 codePoint >> 0x6 & 0x3F | 0x80,
3975 codePoint & 0x3F | 0x80
3976 )
3977 } else {
3978 throw new Error('Invalid code point')
3979 }
3980 }
3981
3982 return bytes
3983}
3984
3985function asciiToBytes (str) {
3986 var byteArray = []
3987 for (var i = 0; i < str.length; ++i) {
3988 // Node's code seems to be doing this and not & 0x7F..
3989 byteArray.push(str.charCodeAt(i) & 0xFF)
3990 }
3991 return byteArray
3992}
3993
3994function utf16leToBytes (str, units) {
3995 var c, hi, lo
3996 var byteArray = []
3997 for (var i = 0; i < str.length; ++i) {
3998 if ((units -= 2) < 0) break
3999
4000 c = str.charCodeAt(i)
4001 hi = c >> 8
4002 lo = c % 256
4003 byteArray.push(lo)
4004 byteArray.push(hi)
4005 }
4006
4007 return byteArray
4008}
4009
4010function base64ToBytes (str) {
4011 return base64.toByteArray(base64clean(str))
4012}
4013
4014function blitBuffer (src, dst, offset, length) {
4015 for (var i = 0; i < length; ++i) {
4016 if ((i + offset >= dst.length) || (i >= src.length)) break
4017 dst[i + offset] = src[i]
4018 }
4019 return i
4020}
4021
4022// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
4023// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
4024function isArrayBuffer (obj) {
4025 return obj instanceof ArrayBuffer ||
4026 (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
4027 typeof obj.byteLength === 'number')
4028}
4029
4030function numberIsNaN (obj) {
4031 return obj !== obj // eslint-disable-line no-self-compare
4032}
4033
4034},{"base64-js":5,"ieee754":12}],10:[function(require,module,exports){
4035(function (Buffer){
4036// Copyright Joyent, Inc. and other Node contributors.
4037//
4038// Permission is hereby granted, free of charge, to any person obtaining a
4039// copy of this software and associated documentation files (the
4040// "Software"), to deal in the Software without restriction, including
4041// without limitation the rights to use, copy, modify, merge, publish,
4042// distribute, sublicense, and/or sell copies of the Software, and to permit
4043// persons to whom the Software is furnished to do so, subject to the
4044// following conditions:
4045//
4046// The above copyright notice and this permission notice shall be included
4047// in all copies or substantial portions of the Software.
4048//
4049// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4050// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4051// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4052// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4053// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4054// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4055// USE OR OTHER DEALINGS IN THE SOFTWARE.
4056
4057// NOTE: These type checking functions intentionally don't use `instanceof`
4058// because it is fragile and can be easily faked with `Object.create()`.
4059
4060function isArray(arg) {
4061 if (Array.isArray) {
4062 return Array.isArray(arg);
4063 }
4064 return objectToString(arg) === '[object Array]';
4065}
4066exports.isArray = isArray;
4067
4068function isBoolean(arg) {
4069 return typeof arg === 'boolean';
4070}
4071exports.isBoolean = isBoolean;
4072
4073function isNull(arg) {
4074 return arg === null;
4075}
4076exports.isNull = isNull;
4077
4078function isNullOrUndefined(arg) {
4079 return arg == null;
4080}
4081exports.isNullOrUndefined = isNullOrUndefined;
4082
4083function isNumber(arg) {
4084 return typeof arg === 'number';
4085}
4086exports.isNumber = isNumber;
4087
4088function isString(arg) {
4089 return typeof arg === 'string';
4090}
4091exports.isString = isString;
4092
4093function isSymbol(arg) {
4094 return typeof arg === 'symbol';
4095}
4096exports.isSymbol = isSymbol;
4097
4098function isUndefined(arg) {
4099 return arg === void 0;
4100}
4101exports.isUndefined = isUndefined;
4102
4103function isRegExp(re) {
4104 return objectToString(re) === '[object RegExp]';
4105}
4106exports.isRegExp = isRegExp;
4107
4108function isObject(arg) {
4109 return typeof arg === 'object' && arg !== null;
4110}
4111exports.isObject = isObject;
4112
4113function isDate(d) {
4114 return objectToString(d) === '[object Date]';
4115}
4116exports.isDate = isDate;
4117
4118function isError(e) {
4119 return (objectToString(e) === '[object Error]' || e instanceof Error);
4120}
4121exports.isError = isError;
4122
4123function isFunction(arg) {
4124 return typeof arg === 'function';
4125}
4126exports.isFunction = isFunction;
4127
4128function isPrimitive(arg) {
4129 return arg === null ||
4130 typeof arg === 'boolean' ||
4131 typeof arg === 'number' ||
4132 typeof arg === 'string' ||
4133 typeof arg === 'symbol' || // ES6 symbol
4134 typeof arg === 'undefined';
4135}
4136exports.isPrimitive = isPrimitive;
4137
4138exports.isBuffer = Buffer.isBuffer;
4139
4140function objectToString(o) {
4141 return Object.prototype.toString.call(o);
4142}
4143
4144}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
4145},{"../../is-buffer/index.js":14}],11:[function(require,module,exports){
4146// Copyright Joyent, Inc. and other Node contributors.
4147//
4148// Permission is hereby granted, free of charge, to any person obtaining a
4149// copy of this software and associated documentation files (the
4150// "Software"), to deal in the Software without restriction, including
4151// without limitation the rights to use, copy, modify, merge, publish,
4152// distribute, sublicense, and/or sell copies of the Software, and to permit
4153// persons to whom the Software is furnished to do so, subject to the
4154// following conditions:
4155//
4156// The above copyright notice and this permission notice shall be included
4157// in all copies or substantial portions of the Software.
4158//
4159// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4160// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4161// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4162// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4163// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4164// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4165// USE OR OTHER DEALINGS IN THE SOFTWARE.
4166
4167var objectCreate = Object.create || objectCreatePolyfill
4168var objectKeys = Object.keys || objectKeysPolyfill
4169var bind = Function.prototype.bind || functionBindPolyfill
4170
4171function EventEmitter() {
4172 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
4173 this._events = objectCreate(null);
4174 this._eventsCount = 0;
4175 }
4176
4177 this._maxListeners = this._maxListeners || undefined;
4178}
4179module.exports = EventEmitter;
4180
4181// Backwards-compat with node 0.10.x
4182EventEmitter.EventEmitter = EventEmitter;
4183
4184EventEmitter.prototype._events = undefined;
4185EventEmitter.prototype._maxListeners = undefined;
4186
4187// By default EventEmitters will print a warning if more than 10 listeners are
4188// added to it. This is a useful default which helps finding memory leaks.
4189var defaultMaxListeners = 10;
4190
4191var hasDefineProperty;
4192try {
4193 var o = {};
4194 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
4195 hasDefineProperty = o.x === 0;
4196} catch (err) { hasDefineProperty = false }
4197if (hasDefineProperty) {
4198 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
4199 enumerable: true,
4200 get: function() {
4201 return defaultMaxListeners;
4202 },
4203 set: function(arg) {
4204 // check whether the input is a positive number (whose value is zero or
4205 // greater and not a NaN).
4206 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
4207 throw new TypeError('"defaultMaxListeners" must be a positive number');
4208 defaultMaxListeners = arg;
4209 }
4210 });
4211} else {
4212 EventEmitter.defaultMaxListeners = defaultMaxListeners;
4213}
4214
4215// Obviously not all Emitters should be limited to 10. This function allows
4216// that to be increased. Set to zero for unlimited.
4217EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
4218 if (typeof n !== 'number' || n < 0 || isNaN(n))
4219 throw new TypeError('"n" argument must be a positive number');
4220 this._maxListeners = n;
4221 return this;
4222};
4223
4224function $getMaxListeners(that) {
4225 if (that._maxListeners === undefined)
4226 return EventEmitter.defaultMaxListeners;
4227 return that._maxListeners;
4228}
4229
4230EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
4231 return $getMaxListeners(this);
4232};
4233
4234// These standalone emit* functions are used to optimize calling of event
4235// handlers for fast cases because emit() itself often has a variable number of
4236// arguments and can be deoptimized because of that. These functions always have
4237// the same number of arguments and thus do not get deoptimized, so the code
4238// inside them can execute faster.
4239function emitNone(handler, isFn, self) {
4240 if (isFn)
4241 handler.call(self);
4242 else {
4243 var len = handler.length;
4244 var listeners = arrayClone(handler, len);
4245 for (var i = 0; i < len; ++i)
4246 listeners[i].call(self);
4247 }
4248}
4249function emitOne(handler, isFn, self, arg1) {
4250 if (isFn)
4251 handler.call(self, arg1);
4252 else {
4253 var len = handler.length;
4254 var listeners = arrayClone(handler, len);
4255 for (var i = 0; i < len; ++i)
4256 listeners[i].call(self, arg1);
4257 }
4258}
4259function emitTwo(handler, isFn, self, arg1, arg2) {
4260 if (isFn)
4261 handler.call(self, arg1, arg2);
4262 else {
4263 var len = handler.length;
4264 var listeners = arrayClone(handler, len);
4265 for (var i = 0; i < len; ++i)
4266 listeners[i].call(self, arg1, arg2);
4267 }
4268}
4269function emitThree(handler, isFn, self, arg1, arg2, arg3) {
4270 if (isFn)
4271 handler.call(self, arg1, arg2, arg3);
4272 else {
4273 var len = handler.length;
4274 var listeners = arrayClone(handler, len);
4275 for (var i = 0; i < len; ++i)
4276 listeners[i].call(self, arg1, arg2, arg3);
4277 }
4278}
4279
4280function emitMany(handler, isFn, self, args) {
4281 if (isFn)
4282 handler.apply(self, args);
4283 else {
4284 var len = handler.length;
4285 var listeners = arrayClone(handler, len);
4286 for (var i = 0; i < len; ++i)
4287 listeners[i].apply(self, args);
4288 }
4289}
4290
4291EventEmitter.prototype.emit = function emit(type) {
4292 var er, handler, len, args, i, events;
4293 var doError = (type === 'error');
4294
4295 events = this._events;
4296 if (events)
4297 doError = (doError && events.error == null);
4298 else if (!doError)
4299 return false;
4300
4301 // If there is no 'error' event listener then throw.
4302 if (doError) {
4303 if (arguments.length > 1)
4304 er = arguments[1];
4305 if (er instanceof Error) {
4306 throw er; // Unhandled 'error' event
4307 } else {
4308 // At least give some kind of context to the user
4309 var err = new Error('Unhandled "error" event. (' + er + ')');
4310 err.context = er;
4311 throw err;
4312 }
4313 return false;
4314 }
4315
4316 handler = events[type];
4317
4318 if (!handler)
4319 return false;
4320
4321 var isFn = typeof handler === 'function';
4322 len = arguments.length;
4323 switch (len) {
4324 // fast cases
4325 case 1:
4326 emitNone(handler, isFn, this);
4327 break;
4328 case 2:
4329 emitOne(handler, isFn, this, arguments[1]);
4330 break;
4331 case 3:
4332 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
4333 break;
4334 case 4:
4335 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
4336 break;
4337 // slower
4338 default:
4339 args = new Array(len - 1);
4340 for (i = 1; i < len; i++)
4341 args[i - 1] = arguments[i];
4342 emitMany(handler, isFn, this, args);
4343 }
4344
4345 return true;
4346};
4347
4348function _addListener(target, type, listener, prepend) {
4349 var m;
4350 var events;
4351 var existing;
4352
4353 if (typeof listener !== 'function')
4354 throw new TypeError('"listener" argument must be a function');
4355
4356 events = target._events;
4357 if (!events) {
4358 events = target._events = objectCreate(null);
4359 target._eventsCount = 0;
4360 } else {
4361 // To avoid recursion in the case that type === "newListener"! Before
4362 // adding it to the listeners, first emit "newListener".
4363 if (events.newListener) {
4364 target.emit('newListener', type,
4365 listener.listener ? listener.listener : listener);
4366
4367 // Re-assign `events` because a newListener handler could have caused the
4368 // this._events to be assigned to a new object
4369 events = target._events;
4370 }
4371 existing = events[type];
4372 }
4373
4374 if (!existing) {
4375 // Optimize the case of one listener. Don't need the extra array object.
4376 existing = events[type] = listener;
4377 ++target._eventsCount;
4378 } else {
4379 if (typeof existing === 'function') {
4380 // Adding the second element, need to change to array.
4381 existing = events[type] =
4382 prepend ? [listener, existing] : [existing, listener];
4383 } else {
4384 // If we've already got an array, just append.
4385 if (prepend) {
4386 existing.unshift(listener);
4387 } else {
4388 existing.push(listener);
4389 }
4390 }
4391
4392 // Check for listener leak
4393 if (!existing.warned) {
4394 m = $getMaxListeners(target);
4395 if (m && m > 0 && existing.length > m) {
4396 existing.warned = true;
4397 var w = new Error('Possible EventEmitter memory leak detected. ' +
4398 existing.length + ' "' + String(type) + '" listeners ' +
4399 'added. Use emitter.setMaxListeners() to ' +
4400 'increase limit.');
4401 w.name = 'MaxListenersExceededWarning';
4402 w.emitter = target;
4403 w.type = type;
4404 w.count = existing.length;
4405 if (typeof console === 'object' && console.warn) {
4406 console.warn('%s: %s', w.name, w.message);
4407 }
4408 }
4409 }
4410 }
4411
4412 return target;
4413}
4414
4415EventEmitter.prototype.addListener = function addListener(type, listener) {
4416 return _addListener(this, type, listener, false);
4417};
4418
4419EventEmitter.prototype.on = EventEmitter.prototype.addListener;
4420
4421EventEmitter.prototype.prependListener =
4422 function prependListener(type, listener) {
4423 return _addListener(this, type, listener, true);
4424 };
4425
4426function onceWrapper() {
4427 if (!this.fired) {
4428 this.target.removeListener(this.type, this.wrapFn);
4429 this.fired = true;
4430 switch (arguments.length) {
4431 case 0:
4432 return this.listener.call(this.target);
4433 case 1:
4434 return this.listener.call(this.target, arguments[0]);
4435 case 2:
4436 return this.listener.call(this.target, arguments[0], arguments[1]);
4437 case 3:
4438 return this.listener.call(this.target, arguments[0], arguments[1],
4439 arguments[2]);
4440 default:
4441 var args = new Array(arguments.length);
4442 for (var i = 0; i < args.length; ++i)
4443 args[i] = arguments[i];
4444 this.listener.apply(this.target, args);
4445 }
4446 }
4447}
4448
4449function _onceWrap(target, type, listener) {
4450 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
4451 var wrapped = bind.call(onceWrapper, state);
4452 wrapped.listener = listener;
4453 state.wrapFn = wrapped;
4454 return wrapped;
4455}
4456
4457EventEmitter.prototype.once = function once(type, listener) {
4458 if (typeof listener !== 'function')
4459 throw new TypeError('"listener" argument must be a function');
4460 this.on(type, _onceWrap(this, type, listener));
4461 return this;
4462};
4463
4464EventEmitter.prototype.prependOnceListener =
4465 function prependOnceListener(type, listener) {
4466 if (typeof listener !== 'function')
4467 throw new TypeError('"listener" argument must be a function');
4468 this.prependListener(type, _onceWrap(this, type, listener));
4469 return this;
4470 };
4471
4472// Emits a 'removeListener' event if and only if the listener was removed.
4473EventEmitter.prototype.removeListener =
4474 function removeListener(type, listener) {
4475 var list, events, position, i, originalListener;
4476
4477 if (typeof listener !== 'function')
4478 throw new TypeError('"listener" argument must be a function');
4479
4480 events = this._events;
4481 if (!events)
4482 return this;
4483
4484 list = events[type];
4485 if (!list)
4486 return this;
4487
4488 if (list === listener || list.listener === listener) {
4489 if (--this._eventsCount === 0)
4490 this._events = objectCreate(null);
4491 else {
4492 delete events[type];
4493 if (events.removeListener)
4494 this.emit('removeListener', type, list.listener || listener);
4495 }
4496 } else if (typeof list !== 'function') {
4497 position = -1;
4498
4499 for (i = list.length - 1; i >= 0; i--) {
4500 if (list[i] === listener || list[i].listener === listener) {
4501 originalListener = list[i].listener;
4502 position = i;
4503 break;
4504 }
4505 }
4506
4507 if (position < 0)
4508 return this;
4509
4510 if (position === 0)
4511 list.shift();
4512 else
4513 spliceOne(list, position);
4514
4515 if (list.length === 1)
4516 events[type] = list[0];
4517
4518 if (events.removeListener)
4519 this.emit('removeListener', type, originalListener || listener);
4520 }
4521
4522 return this;
4523 };
4524
4525EventEmitter.prototype.removeAllListeners =
4526 function removeAllListeners(type) {
4527 var listeners, events, i;
4528
4529 events = this._events;
4530 if (!events)
4531 return this;
4532
4533 // not listening for removeListener, no need to emit
4534 if (!events.removeListener) {
4535 if (arguments.length === 0) {
4536 this._events = objectCreate(null);
4537 this._eventsCount = 0;
4538 } else if (events[type]) {
4539 if (--this._eventsCount === 0)
4540 this._events = objectCreate(null);
4541 else
4542 delete events[type];
4543 }
4544 return this;
4545 }
4546
4547 // emit removeListener for all listeners on all events
4548 if (arguments.length === 0) {
4549 var keys = objectKeys(events);
4550 var key;
4551 for (i = 0; i < keys.length; ++i) {
4552 key = keys[i];
4553 if (key === 'removeListener') continue;
4554 this.removeAllListeners(key);
4555 }
4556 this.removeAllListeners('removeListener');
4557 this._events = objectCreate(null);
4558 this._eventsCount = 0;
4559 return this;
4560 }
4561
4562 listeners = events[type];
4563
4564 if (typeof listeners === 'function') {
4565 this.removeListener(type, listeners);
4566 } else if (listeners) {
4567 // LIFO order
4568 for (i = listeners.length - 1; i >= 0; i--) {
4569 this.removeListener(type, listeners[i]);
4570 }
4571 }
4572
4573 return this;
4574 };
4575
4576function _listeners(target, type, unwrap) {
4577 var events = target._events;
4578
4579 if (!events)
4580 return [];
4581
4582 var evlistener = events[type];
4583 if (!evlistener)
4584 return [];
4585
4586 if (typeof evlistener === 'function')
4587 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
4588
4589 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
4590}
4591
4592EventEmitter.prototype.listeners = function listeners(type) {
4593 return _listeners(this, type, true);
4594};
4595
4596EventEmitter.prototype.rawListeners = function rawListeners(type) {
4597 return _listeners(this, type, false);
4598};
4599
4600EventEmitter.listenerCount = function(emitter, type) {
4601 if (typeof emitter.listenerCount === 'function') {
4602 return emitter.listenerCount(type);
4603 } else {
4604 return listenerCount.call(emitter, type);
4605 }
4606};
4607
4608EventEmitter.prototype.listenerCount = listenerCount;
4609function listenerCount(type) {
4610 var events = this._events;
4611
4612 if (events) {
4613 var evlistener = events[type];
4614
4615 if (typeof evlistener === 'function') {
4616 return 1;
4617 } else if (evlistener) {
4618 return evlistener.length;
4619 }
4620 }
4621
4622 return 0;
4623}
4624
4625EventEmitter.prototype.eventNames = function eventNames() {
4626 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
4627};
4628
4629// About 1.5x faster than the two-arg version of Array#splice().
4630function spliceOne(list, index) {
4631 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
4632 list[i] = list[k];
4633 list.pop();
4634}
4635
4636function arrayClone(arr, n) {
4637 var copy = new Array(n);
4638 for (var i = 0; i < n; ++i)
4639 copy[i] = arr[i];
4640 return copy;
4641}
4642
4643function unwrapListeners(arr) {
4644 var ret = new Array(arr.length);
4645 for (var i = 0; i < ret.length; ++i) {
4646 ret[i] = arr[i].listener || arr[i];
4647 }
4648 return ret;
4649}
4650
4651function objectCreatePolyfill(proto) {
4652 var F = function() {};
4653 F.prototype = proto;
4654 return new F;
4655}
4656function objectKeysPolyfill(obj) {
4657 var keys = [];
4658 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
4659 keys.push(k);
4660 }
4661 return k;
4662}
4663function functionBindPolyfill(context) {
4664 var fn = this;
4665 return function () {
4666 return fn.apply(context, arguments);
4667 };
4668}
4669
4670},{}],12:[function(require,module,exports){
4671exports.read = function (buffer, offset, isLE, mLen, nBytes) {
4672 var e, m
4673 var eLen = (nBytes * 8) - mLen - 1
4674 var eMax = (1 << eLen) - 1
4675 var eBias = eMax >> 1
4676 var nBits = -7
4677 var i = isLE ? (nBytes - 1) : 0
4678 var d = isLE ? -1 : 1
4679 var s = buffer[offset + i]
4680
4681 i += d
4682
4683 e = s & ((1 << (-nBits)) - 1)
4684 s >>= (-nBits)
4685 nBits += eLen
4686 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
4687
4688 m = e & ((1 << (-nBits)) - 1)
4689 e >>= (-nBits)
4690 nBits += mLen
4691 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
4692
4693 if (e === 0) {
4694 e = 1 - eBias
4695 } else if (e === eMax) {
4696 return m ? NaN : ((s ? -1 : 1) * Infinity)
4697 } else {
4698 m = m + Math.pow(2, mLen)
4699 e = e - eBias
4700 }
4701 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
4702}
4703
4704exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
4705 var e, m, c
4706 var eLen = (nBytes * 8) - mLen - 1
4707 var eMax = (1 << eLen) - 1
4708 var eBias = eMax >> 1
4709 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
4710 var i = isLE ? 0 : (nBytes - 1)
4711 var d = isLE ? 1 : -1
4712 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
4713
4714 value = Math.abs(value)
4715
4716 if (isNaN(value) || value === Infinity) {
4717 m = isNaN(value) ? 1 : 0
4718 e = eMax
4719 } else {
4720 e = Math.floor(Math.log(value) / Math.LN2)
4721 if (value * (c = Math.pow(2, -e)) < 1) {
4722 e--
4723 c *= 2
4724 }
4725 if (e + eBias >= 1) {
4726 value += rt / c
4727 } else {
4728 value += rt * Math.pow(2, 1 - eBias)
4729 }
4730 if (value * c >= 2) {
4731 e++
4732 c /= 2
4733 }
4734
4735 if (e + eBias >= eMax) {
4736 m = 0
4737 e = eMax
4738 } else if (e + eBias >= 1) {
4739 m = ((value * c) - 1) * Math.pow(2, mLen)
4740 e = e + eBias
4741 } else {
4742 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
4743 e = 0
4744 }
4745 }
4746
4747 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
4748
4749 e = (e << mLen) | m
4750 eLen += mLen
4751 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
4752
4753 buffer[offset + i - d] |= s * 128
4754}
4755
4756},{}],13:[function(require,module,exports){
4757arguments[4][2][0].apply(exports,arguments)
4758},{"dup":2}],14:[function(require,module,exports){
4759/*!
4760 * Determine if an object is a Buffer
4761 *
4762 * @author Feross Aboukhadijeh <https://feross.org>
4763 * @license MIT
4764 */
4765
4766// The _isBuffer check is for Safari 5-7 support, because it's missing
4767// Object.prototype.constructor. Remove this eventually
4768module.exports = function (obj) {
4769 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
4770}
4771
4772function isBuffer (obj) {
4773 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
4774}
4775
4776// For Node v0.10 support. Remove this eventually.
4777function isSlowBuffer (obj) {
4778 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
4779}
4780
4781},{}],15:[function(require,module,exports){
4782var toString = {}.toString;
4783
4784module.exports = Array.isArray || function (arr) {
4785 return toString.call(arr) == '[object Array]';
4786};
4787
4788},{}],16:[function(require,module,exports){
4789'use strict';
4790
4791
4792var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
4793 (typeof Uint16Array !== 'undefined') &&
4794 (typeof Int32Array !== 'undefined');
4795
4796function _has(obj, key) {
4797 return Object.prototype.hasOwnProperty.call(obj, key);
4798}
4799
4800exports.assign = function (obj /*from1, from2, from3, ...*/) {
4801 var sources = Array.prototype.slice.call(arguments, 1);
4802 while (sources.length) {
4803 var source = sources.shift();
4804 if (!source) { continue; }
4805
4806 if (typeof source !== 'object') {
4807 throw new TypeError(source + 'must be non-object');
4808 }
4809
4810 for (var p in source) {
4811 if (_has(source, p)) {
4812 obj[p] = source[p];
4813 }
4814 }
4815 }
4816
4817 return obj;
4818};
4819
4820
4821// reduce buffer size, avoiding mem copy
4822exports.shrinkBuf = function (buf, size) {
4823 if (buf.length === size) { return buf; }
4824 if (buf.subarray) { return buf.subarray(0, size); }
4825 buf.length = size;
4826 return buf;
4827};
4828
4829
4830var fnTyped = {
4831 arraySet: function (dest, src, src_offs, len, dest_offs) {
4832 if (src.subarray && dest.subarray) {
4833 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
4834 return;
4835 }
4836 // Fallback to ordinary array
4837 for (var i = 0; i < len; i++) {
4838 dest[dest_offs + i] = src[src_offs + i];
4839 }
4840 },
4841 // Join array of chunks to single array.
4842 flattenChunks: function (chunks) {
4843 var i, l, len, pos, chunk, result;
4844
4845 // calculate data length
4846 len = 0;
4847 for (i = 0, l = chunks.length; i < l; i++) {
4848 len += chunks[i].length;
4849 }
4850
4851 // join chunks
4852 result = new Uint8Array(len);
4853 pos = 0;
4854 for (i = 0, l = chunks.length; i < l; i++) {
4855 chunk = chunks[i];
4856 result.set(chunk, pos);
4857 pos += chunk.length;
4858 }
4859
4860 return result;
4861 }
4862};
4863
4864var fnUntyped = {
4865 arraySet: function (dest, src, src_offs, len, dest_offs) {
4866 for (var i = 0; i < len; i++) {
4867 dest[dest_offs + i] = src[src_offs + i];
4868 }
4869 },
4870 // Join array of chunks to single array.
4871 flattenChunks: function (chunks) {
4872 return [].concat.apply([], chunks);
4873 }
4874};
4875
4876
4877// Enable/Disable typed arrays use, for testing
4878//
4879exports.setTyped = function (on) {
4880 if (on) {
4881 exports.Buf8 = Uint8Array;
4882 exports.Buf16 = Uint16Array;
4883 exports.Buf32 = Int32Array;
4884 exports.assign(exports, fnTyped);
4885 } else {
4886 exports.Buf8 = Array;
4887 exports.Buf16 = Array;
4888 exports.Buf32 = Array;
4889 exports.assign(exports, fnUntyped);
4890 }
4891};
4892
4893exports.setTyped(TYPED_OK);
4894
4895},{}],17:[function(require,module,exports){
4896'use strict';
4897
4898// Note: adler32 takes 12% for level 0 and 2% for level 6.
4899// It isn't worth it to make additional optimizations as in original.
4900// Small size is preferable.
4901
4902// (C) 1995-2013 Jean-loup Gailly and Mark Adler
4903// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
4904//
4905// This software is provided 'as-is', without any express or implied
4906// warranty. In no event will the authors be held liable for any damages
4907// arising from the use of this software.
4908//
4909// Permission is granted to anyone to use this software for any purpose,
4910// including commercial applications, and to alter it and redistribute it
4911// freely, subject to the following restrictions:
4912//
4913// 1. The origin of this software must not be misrepresented; you must not
4914// claim that you wrote the original software. If you use this software
4915// in a product, an acknowledgment in the product documentation would be
4916// appreciated but is not required.
4917// 2. Altered source versions must be plainly marked as such, and must not be
4918// misrepresented as being the original software.
4919// 3. This notice may not be removed or altered from any source distribution.
4920
4921function adler32(adler, buf, len, pos) {
4922 var s1 = (adler & 0xffff) |0,
4923 s2 = ((adler >>> 16) & 0xffff) |0,
4924 n = 0;
4925
4926 while (len !== 0) {
4927 // Set limit ~ twice less than 5552, to keep
4928 // s2 in 31-bits, because we force signed ints.
4929 // in other case %= will fail.
4930 n = len > 2000 ? 2000 : len;
4931 len -= n;
4932
4933 do {
4934 s1 = (s1 + buf[pos++]) |0;
4935 s2 = (s2 + s1) |0;
4936 } while (--n);
4937
4938 s1 %= 65521;
4939 s2 %= 65521;
4940 }
4941
4942 return (s1 | (s2 << 16)) |0;
4943}
4944
4945
4946module.exports = adler32;
4947
4948},{}],18:[function(require,module,exports){
4949'use strict';
4950
4951// (C) 1995-2013 Jean-loup Gailly and Mark Adler
4952// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
4953//
4954// This software is provided 'as-is', without any express or implied
4955// warranty. In no event will the authors be held liable for any damages
4956// arising from the use of this software.
4957//
4958// Permission is granted to anyone to use this software for any purpose,
4959// including commercial applications, and to alter it and redistribute it
4960// freely, subject to the following restrictions:
4961//
4962// 1. The origin of this software must not be misrepresented; you must not
4963// claim that you wrote the original software. If you use this software
4964// in a product, an acknowledgment in the product documentation would be
4965// appreciated but is not required.
4966// 2. Altered source versions must be plainly marked as such, and must not be
4967// misrepresented as being the original software.
4968// 3. This notice may not be removed or altered from any source distribution.
4969
4970module.exports = {
4971
4972 /* Allowed flush values; see deflate() and inflate() below for details */
4973 Z_NO_FLUSH: 0,
4974 Z_PARTIAL_FLUSH: 1,
4975 Z_SYNC_FLUSH: 2,
4976 Z_FULL_FLUSH: 3,
4977 Z_FINISH: 4,
4978 Z_BLOCK: 5,
4979 Z_TREES: 6,
4980
4981 /* Return codes for the compression/decompression functions. Negative values
4982 * are errors, positive values are used for special but normal events.
4983 */
4984 Z_OK: 0,
4985 Z_STREAM_END: 1,
4986 Z_NEED_DICT: 2,
4987 Z_ERRNO: -1,
4988 Z_STREAM_ERROR: -2,
4989 Z_DATA_ERROR: -3,
4990 //Z_MEM_ERROR: -4,
4991 Z_BUF_ERROR: -5,
4992 //Z_VERSION_ERROR: -6,
4993
4994 /* compression levels */
4995 Z_NO_COMPRESSION: 0,
4996 Z_BEST_SPEED: 1,
4997 Z_BEST_COMPRESSION: 9,
4998 Z_DEFAULT_COMPRESSION: -1,
4999
5000
5001 Z_FILTERED: 1,
5002 Z_HUFFMAN_ONLY: 2,
5003 Z_RLE: 3,
5004 Z_FIXED: 4,
5005 Z_DEFAULT_STRATEGY: 0,
5006
5007 /* Possible values of the data_type field (though see inflate()) */
5008 Z_BINARY: 0,
5009 Z_TEXT: 1,
5010 //Z_ASCII: 1, // = Z_TEXT (deprecated)
5011 Z_UNKNOWN: 2,
5012
5013 /* The deflate compression method */
5014 Z_DEFLATED: 8
5015 //Z_NULL: null // Use -1 or null inline, depending on var type
5016};
5017
5018},{}],19:[function(require,module,exports){
5019'use strict';
5020
5021// Note: we can't get significant speed boost here.
5022// So write code to minimize size - no pregenerated tables
5023// and array tools dependencies.
5024
5025// (C) 1995-2013 Jean-loup Gailly and Mark Adler
5026// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5027//
5028// This software is provided 'as-is', without any express or implied
5029// warranty. In no event will the authors be held liable for any damages
5030// arising from the use of this software.
5031//
5032// Permission is granted to anyone to use this software for any purpose,
5033// including commercial applications, and to alter it and redistribute it
5034// freely, subject to the following restrictions:
5035//
5036// 1. The origin of this software must not be misrepresented; you must not
5037// claim that you wrote the original software. If you use this software
5038// in a product, an acknowledgment in the product documentation would be
5039// appreciated but is not required.
5040// 2. Altered source versions must be plainly marked as such, and must not be
5041// misrepresented as being the original software.
5042// 3. This notice may not be removed or altered from any source distribution.
5043
5044// Use ordinary array, since untyped makes no boost here
5045function makeTable() {
5046 var c, table = [];
5047
5048 for (var n = 0; n < 256; n++) {
5049 c = n;
5050 for (var k = 0; k < 8; k++) {
5051 c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
5052 }
5053 table[n] = c;
5054 }
5055
5056 return table;
5057}
5058
5059// Create table on load. Just 255 signed longs. Not a problem.
5060var crcTable = makeTable();
5061
5062
5063function crc32(crc, buf, len, pos) {
5064 var t = crcTable,
5065 end = pos + len;
5066
5067 crc ^= -1;
5068
5069 for (var i = pos; i < end; i++) {
5070 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
5071 }
5072
5073 return (crc ^ (-1)); // >>> 0;
5074}
5075
5076
5077module.exports = crc32;
5078
5079},{}],20:[function(require,module,exports){
5080'use strict';
5081
5082// (C) 1995-2013 Jean-loup Gailly and Mark Adler
5083// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5084//
5085// This software is provided 'as-is', without any express or implied
5086// warranty. In no event will the authors be held liable for any damages
5087// arising from the use of this software.
5088//
5089// Permission is granted to anyone to use this software for any purpose,
5090// including commercial applications, and to alter it and redistribute it
5091// freely, subject to the following restrictions:
5092//
5093// 1. The origin of this software must not be misrepresented; you must not
5094// claim that you wrote the original software. If you use this software
5095// in a product, an acknowledgment in the product documentation would be
5096// appreciated but is not required.
5097// 2. Altered source versions must be plainly marked as such, and must not be
5098// misrepresented as being the original software.
5099// 3. This notice may not be removed or altered from any source distribution.
5100
5101var utils = require('../utils/common');
5102var trees = require('./trees');
5103var adler32 = require('./adler32');
5104var crc32 = require('./crc32');
5105var msg = require('./messages');
5106
5107/* Public constants ==========================================================*/
5108/* ===========================================================================*/
5109
5110
5111/* Allowed flush values; see deflate() and inflate() below for details */
5112var Z_NO_FLUSH = 0;
5113var Z_PARTIAL_FLUSH = 1;
5114//var Z_SYNC_FLUSH = 2;
5115var Z_FULL_FLUSH = 3;
5116var Z_FINISH = 4;
5117var Z_BLOCK = 5;
5118//var Z_TREES = 6;
5119
5120
5121/* Return codes for the compression/decompression functions. Negative values
5122 * are errors, positive values are used for special but normal events.
5123 */
5124var Z_OK = 0;
5125var Z_STREAM_END = 1;
5126//var Z_NEED_DICT = 2;
5127//var Z_ERRNO = -1;
5128var Z_STREAM_ERROR = -2;
5129var Z_DATA_ERROR = -3;
5130//var Z_MEM_ERROR = -4;
5131var Z_BUF_ERROR = -5;
5132//var Z_VERSION_ERROR = -6;
5133
5134
5135/* compression levels */
5136//var Z_NO_COMPRESSION = 0;
5137//var Z_BEST_SPEED = 1;
5138//var Z_BEST_COMPRESSION = 9;
5139var Z_DEFAULT_COMPRESSION = -1;
5140
5141
5142var Z_FILTERED = 1;
5143var Z_HUFFMAN_ONLY = 2;
5144var Z_RLE = 3;
5145var Z_FIXED = 4;
5146var Z_DEFAULT_STRATEGY = 0;
5147
5148/* Possible values of the data_type field (though see inflate()) */
5149//var Z_BINARY = 0;
5150//var Z_TEXT = 1;
5151//var Z_ASCII = 1; // = Z_TEXT
5152var Z_UNKNOWN = 2;
5153
5154
5155/* The deflate compression method */
5156var Z_DEFLATED = 8;
5157
5158/*============================================================================*/
5159
5160
5161var MAX_MEM_LEVEL = 9;
5162/* Maximum value for memLevel in deflateInit2 */
5163var MAX_WBITS = 15;
5164/* 32K LZ77 window */
5165var DEF_MEM_LEVEL = 8;
5166
5167
5168var LENGTH_CODES = 29;
5169/* number of length codes, not counting the special END_BLOCK code */
5170var LITERALS = 256;
5171/* number of literal bytes 0..255 */
5172var L_CODES = LITERALS + 1 + LENGTH_CODES;
5173/* number of Literal or Length codes, including the END_BLOCK code */
5174var D_CODES = 30;
5175/* number of distance codes */
5176var BL_CODES = 19;
5177/* number of codes used to transfer the bit lengths */
5178var HEAP_SIZE = 2 * L_CODES + 1;
5179/* maximum heap size */
5180var MAX_BITS = 15;
5181/* All codes must not exceed MAX_BITS bits */
5182
5183var MIN_MATCH = 3;
5184var MAX_MATCH = 258;
5185var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
5186
5187var PRESET_DICT = 0x20;
5188
5189var INIT_STATE = 42;
5190var EXTRA_STATE = 69;
5191var NAME_STATE = 73;
5192var COMMENT_STATE = 91;
5193var HCRC_STATE = 103;
5194var BUSY_STATE = 113;
5195var FINISH_STATE = 666;
5196
5197var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
5198var BS_BLOCK_DONE = 2; /* block flush performed */
5199var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
5200var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
5201
5202var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
5203
5204function err(strm, errorCode) {
5205 strm.msg = msg[errorCode];
5206 return errorCode;
5207}
5208
5209function rank(f) {
5210 return ((f) << 1) - ((f) > 4 ? 9 : 0);
5211}
5212
5213function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
5214
5215
5216/* =========================================================================
5217 * Flush as much pending output as possible. All deflate() output goes
5218 * through this function so some applications may wish to modify it
5219 * to avoid allocating a large strm->output buffer and copying into it.
5220 * (See also read_buf()).
5221 */
5222function flush_pending(strm) {
5223 var s = strm.state;
5224
5225 //_tr_flush_bits(s);
5226 var len = s.pending;
5227 if (len > strm.avail_out) {
5228 len = strm.avail_out;
5229 }
5230 if (len === 0) { return; }
5231
5232 utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
5233 strm.next_out += len;
5234 s.pending_out += len;
5235 strm.total_out += len;
5236 strm.avail_out -= len;
5237 s.pending -= len;
5238 if (s.pending === 0) {
5239 s.pending_out = 0;
5240 }
5241}
5242
5243
5244function flush_block_only(s, last) {
5245 trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
5246 s.block_start = s.strstart;
5247 flush_pending(s.strm);
5248}
5249
5250
5251function put_byte(s, b) {
5252 s.pending_buf[s.pending++] = b;
5253}
5254
5255
5256/* =========================================================================
5257 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
5258 * IN assertion: the stream state is correct and there is enough room in
5259 * pending_buf.
5260 */
5261function putShortMSB(s, b) {
5262// put_byte(s, (Byte)(b >> 8));
5263// put_byte(s, (Byte)(b & 0xff));
5264 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
5265 s.pending_buf[s.pending++] = b & 0xff;
5266}
5267
5268
5269/* ===========================================================================
5270 * Read a new buffer from the current input stream, update the adler32
5271 * and total number of bytes read. All deflate() input goes through
5272 * this function so some applications may wish to modify it to avoid
5273 * allocating a large strm->input buffer and copying from it.
5274 * (See also flush_pending()).
5275 */
5276function read_buf(strm, buf, start, size) {
5277 var len = strm.avail_in;
5278
5279 if (len > size) { len = size; }
5280 if (len === 0) { return 0; }
5281
5282 strm.avail_in -= len;
5283
5284 // zmemcpy(buf, strm->next_in, len);
5285 utils.arraySet(buf, strm.input, strm.next_in, len, start);
5286 if (strm.state.wrap === 1) {
5287 strm.adler = adler32(strm.adler, buf, len, start);
5288 }
5289
5290 else if (strm.state.wrap === 2) {
5291 strm.adler = crc32(strm.adler, buf, len, start);
5292 }
5293
5294 strm.next_in += len;
5295 strm.total_in += len;
5296
5297 return len;
5298}
5299
5300
5301/* ===========================================================================
5302 * Set match_start to the longest match starting at the given string and
5303 * return its length. Matches shorter or equal to prev_length are discarded,
5304 * in which case the result is equal to prev_length and match_start is
5305 * garbage.
5306 * IN assertions: cur_match is the head of the hash chain for the current
5307 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
5308 * OUT assertion: the match length is not greater than s->lookahead.
5309 */
5310function longest_match(s, cur_match) {
5311 var chain_length = s.max_chain_length; /* max hash chain length */
5312 var scan = s.strstart; /* current string */
5313 var match; /* matched string */
5314 var len; /* length of current match */
5315 var best_len = s.prev_length; /* best match length so far */
5316 var nice_match = s.nice_match; /* stop if match long enough */
5317 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
5318 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
5319
5320 var _win = s.window; // shortcut
5321
5322 var wmask = s.w_mask;
5323 var prev = s.prev;
5324
5325 /* Stop when cur_match becomes <= limit. To simplify the code,
5326 * we prevent matches with the string of window index 0.
5327 */
5328
5329 var strend = s.strstart + MAX_MATCH;
5330 var scan_end1 = _win[scan + best_len - 1];
5331 var scan_end = _win[scan + best_len];
5332
5333 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
5334 * It is easy to get rid of this optimization if necessary.
5335 */
5336 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
5337
5338 /* Do not waste too much time if we already have a good match: */
5339 if (s.prev_length >= s.good_match) {
5340 chain_length >>= 2;
5341 }
5342 /* Do not look for matches beyond the end of the input. This is necessary
5343 * to make deflate deterministic.
5344 */
5345 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
5346
5347 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
5348
5349 do {
5350 // Assert(cur_match < s->strstart, "no future");
5351 match = cur_match;
5352
5353 /* Skip to next match if the match length cannot increase
5354 * or if the match length is less than 2. Note that the checks below
5355 * for insufficient lookahead only occur occasionally for performance
5356 * reasons. Therefore uninitialized memory will be accessed, and
5357 * conditional jumps will be made that depend on those values.
5358 * However the length of the match is limited to the lookahead, so
5359 * the output of deflate is not affected by the uninitialized values.
5360 */
5361
5362 if (_win[match + best_len] !== scan_end ||
5363 _win[match + best_len - 1] !== scan_end1 ||
5364 _win[match] !== _win[scan] ||
5365 _win[++match] !== _win[scan + 1]) {
5366 continue;
5367 }
5368
5369 /* The check at best_len-1 can be removed because it will be made
5370 * again later. (This heuristic is not always a win.)
5371 * It is not necessary to compare scan[2] and match[2] since they
5372 * are always equal when the other bytes match, given that
5373 * the hash keys are equal and that HASH_BITS >= 8.
5374 */
5375 scan += 2;
5376 match++;
5377 // Assert(*scan == *match, "match[2]?");
5378
5379 /* We check for insufficient lookahead only every 8th comparison;
5380 * the 256th check will be made at strstart+258.
5381 */
5382 do {
5383 /*jshint noempty:false*/
5384 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
5385 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
5386 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
5387 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
5388 scan < strend);
5389
5390 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
5391
5392 len = MAX_MATCH - (strend - scan);
5393 scan = strend - MAX_MATCH;
5394
5395 if (len > best_len) {
5396 s.match_start = cur_match;
5397 best_len = len;
5398 if (len >= nice_match) {
5399 break;
5400 }
5401 scan_end1 = _win[scan + best_len - 1];
5402 scan_end = _win[scan + best_len];
5403 }
5404 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
5405
5406 if (best_len <= s.lookahead) {
5407 return best_len;
5408 }
5409 return s.lookahead;
5410}
5411
5412
5413/* ===========================================================================
5414 * Fill the window when the lookahead becomes insufficient.
5415 * Updates strstart and lookahead.
5416 *
5417 * IN assertion: lookahead < MIN_LOOKAHEAD
5418 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
5419 * At least one byte has been read, or avail_in == 0; reads are
5420 * performed for at least two bytes (required for the zip translate_eol
5421 * option -- not supported here).
5422 */
5423function fill_window(s) {
5424 var _w_size = s.w_size;
5425 var p, n, m, more, str;
5426
5427 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
5428
5429 do {
5430 more = s.window_size - s.lookahead - s.strstart;
5431
5432 // JS ints have 32 bit, block below not needed
5433 /* Deal with !@#$% 64K limit: */
5434 //if (sizeof(int) <= 2) {
5435 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
5436 // more = wsize;
5437 //
5438 // } else if (more == (unsigned)(-1)) {
5439 // /* Very unlikely, but possible on 16 bit machine if
5440 // * strstart == 0 && lookahead == 1 (input done a byte at time)
5441 // */
5442 // more--;
5443 // }
5444 //}
5445
5446
5447 /* If the window is almost full and there is insufficient lookahead,
5448 * move the upper half to the lower one to make room in the upper half.
5449 */
5450 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
5451
5452 utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
5453 s.match_start -= _w_size;
5454 s.strstart -= _w_size;
5455 /* we now have strstart >= MAX_DIST */
5456 s.block_start -= _w_size;
5457
5458 /* Slide the hash table (could be avoided with 32 bit values
5459 at the expense of memory usage). We slide even when level == 0
5460 to keep the hash table consistent if we switch back to level > 0
5461 later. (Using level 0 permanently is not an optimal usage of
5462 zlib, so we don't care about this pathological case.)
5463 */
5464
5465 n = s.hash_size;
5466 p = n;
5467 do {
5468 m = s.head[--p];
5469 s.head[p] = (m >= _w_size ? m - _w_size : 0);
5470 } while (--n);
5471
5472 n = _w_size;
5473 p = n;
5474 do {
5475 m = s.prev[--p];
5476 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
5477 /* If n is not on any hash chain, prev[n] is garbage but
5478 * its value will never be used.
5479 */
5480 } while (--n);
5481
5482 more += _w_size;
5483 }
5484 if (s.strm.avail_in === 0) {
5485 break;
5486 }
5487
5488 /* If there was no sliding:
5489 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
5490 * more == window_size - lookahead - strstart
5491 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
5492 * => more >= window_size - 2*WSIZE + 2
5493 * In the BIG_MEM or MMAP case (not yet supported),
5494 * window_size == input_size + MIN_LOOKAHEAD &&
5495 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
5496 * Otherwise, window_size == 2*WSIZE so more >= 2.
5497 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
5498 */
5499 //Assert(more >= 2, "more < 2");
5500 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
5501 s.lookahead += n;
5502
5503 /* Initialize the hash value now that we have some input: */
5504 if (s.lookahead + s.insert >= MIN_MATCH) {
5505 str = s.strstart - s.insert;
5506 s.ins_h = s.window[str];
5507
5508 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
5509 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
5510//#if MIN_MATCH != 3
5511// Call update_hash() MIN_MATCH-3 more times
5512//#endif
5513 while (s.insert) {
5514 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
5515 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
5516
5517 s.prev[str & s.w_mask] = s.head[s.ins_h];
5518 s.head[s.ins_h] = str;
5519 str++;
5520 s.insert--;
5521 if (s.lookahead + s.insert < MIN_MATCH) {
5522 break;
5523 }
5524 }
5525 }
5526 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
5527 * but this is not important since only literal bytes will be emitted.
5528 */
5529
5530 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
5531
5532 /* If the WIN_INIT bytes after the end of the current data have never been
5533 * written, then zero those bytes in order to avoid memory check reports of
5534 * the use of uninitialized (or uninitialised as Julian writes) bytes by
5535 * the longest match routines. Update the high water mark for the next
5536 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
5537 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
5538 */
5539// if (s.high_water < s.window_size) {
5540// var curr = s.strstart + s.lookahead;
5541// var init = 0;
5542//
5543// if (s.high_water < curr) {
5544// /* Previous high water mark below current data -- zero WIN_INIT
5545// * bytes or up to end of window, whichever is less.
5546// */
5547// init = s.window_size - curr;
5548// if (init > WIN_INIT)
5549// init = WIN_INIT;
5550// zmemzero(s->window + curr, (unsigned)init);
5551// s->high_water = curr + init;
5552// }
5553// else if (s->high_water < (ulg)curr + WIN_INIT) {
5554// /* High water mark at or above current data, but below current data
5555// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
5556// * to end of window, whichever is less.
5557// */
5558// init = (ulg)curr + WIN_INIT - s->high_water;
5559// if (init > s->window_size - s->high_water)
5560// init = s->window_size - s->high_water;
5561// zmemzero(s->window + s->high_water, (unsigned)init);
5562// s->high_water += init;
5563// }
5564// }
5565//
5566// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
5567// "not enough room for search");
5568}
5569
5570/* ===========================================================================
5571 * Copy without compression as much as possible from the input stream, return
5572 * the current block state.
5573 * This function does not insert new strings in the dictionary since
5574 * uncompressible data is probably not useful. This function is used
5575 * only for the level=0 compression option.
5576 * NOTE: this function should be optimized to avoid extra copying from
5577 * window to pending_buf.
5578 */
5579function deflate_stored(s, flush) {
5580 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
5581 * to pending_buf_size, and each stored block has a 5 byte header:
5582 */
5583 var max_block_size = 0xffff;
5584
5585 if (max_block_size > s.pending_buf_size - 5) {
5586 max_block_size = s.pending_buf_size - 5;
5587 }
5588
5589 /* Copy as much as possible from input to output: */
5590 for (;;) {
5591 /* Fill the window as much as possible: */
5592 if (s.lookahead <= 1) {
5593
5594 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
5595 // s->block_start >= (long)s->w_size, "slide too late");
5596// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
5597// s.block_start >= s.w_size)) {
5598// throw new Error("slide too late");
5599// }
5600
5601 fill_window(s);
5602 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
5603 return BS_NEED_MORE;
5604 }
5605
5606 if (s.lookahead === 0) {
5607 break;
5608 }
5609 /* flush the current block */
5610 }
5611 //Assert(s->block_start >= 0L, "block gone");
5612// if (s.block_start < 0) throw new Error("block gone");
5613
5614 s.strstart += s.lookahead;
5615 s.lookahead = 0;
5616
5617 /* Emit a stored block if pending_buf will be full: */
5618 var max_start = s.block_start + max_block_size;
5619
5620 if (s.strstart === 0 || s.strstart >= max_start) {
5621 /* strstart == 0 is possible when wraparound on 16-bit machine */
5622 s.lookahead = s.strstart - max_start;
5623 s.strstart = max_start;
5624 /*** FLUSH_BLOCK(s, 0); ***/
5625 flush_block_only(s, false);
5626 if (s.strm.avail_out === 0) {
5627 return BS_NEED_MORE;
5628 }
5629 /***/
5630
5631
5632 }
5633 /* Flush if we may have to slide, otherwise block_start may become
5634 * negative and the data will be gone:
5635 */
5636 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
5637 /*** FLUSH_BLOCK(s, 0); ***/
5638 flush_block_only(s, false);
5639 if (s.strm.avail_out === 0) {
5640 return BS_NEED_MORE;
5641 }
5642 /***/
5643 }
5644 }
5645
5646 s.insert = 0;
5647
5648 if (flush === Z_FINISH) {
5649 /*** FLUSH_BLOCK(s, 1); ***/
5650 flush_block_only(s, true);
5651 if (s.strm.avail_out === 0) {
5652 return BS_FINISH_STARTED;
5653 }
5654 /***/
5655 return BS_FINISH_DONE;
5656 }
5657
5658 if (s.strstart > s.block_start) {
5659 /*** FLUSH_BLOCK(s, 0); ***/
5660 flush_block_only(s, false);
5661 if (s.strm.avail_out === 0) {
5662 return BS_NEED_MORE;
5663 }
5664 /***/
5665 }
5666
5667 return BS_NEED_MORE;
5668}
5669
5670/* ===========================================================================
5671 * Compress as much as possible from the input stream, return the current
5672 * block state.
5673 * This function does not perform lazy evaluation of matches and inserts
5674 * new strings in the dictionary only for unmatched strings or for short
5675 * matches. It is used only for the fast compression options.
5676 */
5677function deflate_fast(s, flush) {
5678 var hash_head; /* head of the hash chain */
5679 var bflush; /* set if current block must be flushed */
5680
5681 for (;;) {
5682 /* Make sure that we always have enough lookahead, except
5683 * at the end of the input file. We need MAX_MATCH bytes
5684 * for the next match, plus MIN_MATCH bytes to insert the
5685 * string following the next match.
5686 */
5687 if (s.lookahead < MIN_LOOKAHEAD) {
5688 fill_window(s);
5689 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
5690 return BS_NEED_MORE;
5691 }
5692 if (s.lookahead === 0) {
5693 break; /* flush the current block */
5694 }
5695 }
5696
5697 /* Insert the string window[strstart .. strstart+2] in the
5698 * dictionary, and set hash_head to the head of the hash chain:
5699 */
5700 hash_head = 0/*NIL*/;
5701 if (s.lookahead >= MIN_MATCH) {
5702 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
5703 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
5704 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
5705 s.head[s.ins_h] = s.strstart;
5706 /***/
5707 }
5708
5709 /* Find the longest match, discarding those <= prev_length.
5710 * At this point we have always match_length < MIN_MATCH
5711 */
5712 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
5713 /* To simplify the code, we prevent matches with the string
5714 * of window index 0 (in particular we have to avoid a match
5715 * of the string with itself at the start of the input file).
5716 */
5717 s.match_length = longest_match(s, hash_head);
5718 /* longest_match() sets match_start */
5719 }
5720 if (s.match_length >= MIN_MATCH) {
5721 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
5722
5723 /*** _tr_tally_dist(s, s.strstart - s.match_start,
5724 s.match_length - MIN_MATCH, bflush); ***/
5725 bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
5726
5727 s.lookahead -= s.match_length;
5728
5729 /* Insert new strings in the hash table only if the match length
5730 * is not too large. This saves time but degrades compression.
5731 */
5732 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
5733 s.match_length--; /* string at strstart already in table */
5734 do {
5735 s.strstart++;
5736 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
5737 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
5738 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
5739 s.head[s.ins_h] = s.strstart;
5740 /***/
5741 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
5742 * always MIN_MATCH bytes ahead.
5743 */
5744 } while (--s.match_length !== 0);
5745 s.strstart++;
5746 } else
5747 {
5748 s.strstart += s.match_length;
5749 s.match_length = 0;
5750 s.ins_h = s.window[s.strstart];
5751 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
5752 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
5753
5754//#if MIN_MATCH != 3
5755// Call UPDATE_HASH() MIN_MATCH-3 more times
5756//#endif
5757 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
5758 * matter since it will be recomputed at next deflate call.
5759 */
5760 }
5761 } else {
5762 /* No match, output a literal byte */
5763 //Tracevv((stderr,"%c", s.window[s.strstart]));
5764 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
5765 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
5766
5767 s.lookahead--;
5768 s.strstart++;
5769 }
5770 if (bflush) {
5771 /*** FLUSH_BLOCK(s, 0); ***/
5772 flush_block_only(s, false);
5773 if (s.strm.avail_out === 0) {
5774 return BS_NEED_MORE;
5775 }
5776 /***/
5777 }
5778 }
5779 s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
5780 if (flush === Z_FINISH) {
5781 /*** FLUSH_BLOCK(s, 1); ***/
5782 flush_block_only(s, true);
5783 if (s.strm.avail_out === 0) {
5784 return BS_FINISH_STARTED;
5785 }
5786 /***/
5787 return BS_FINISH_DONE;
5788 }
5789 if (s.last_lit) {
5790 /*** FLUSH_BLOCK(s, 0); ***/
5791 flush_block_only(s, false);
5792 if (s.strm.avail_out === 0) {
5793 return BS_NEED_MORE;
5794 }
5795 /***/
5796 }
5797 return BS_BLOCK_DONE;
5798}
5799
5800/* ===========================================================================
5801 * Same as above, but achieves better compression. We use a lazy
5802 * evaluation for matches: a match is finally adopted only if there is
5803 * no better match at the next window position.
5804 */
5805function deflate_slow(s, flush) {
5806 var hash_head; /* head of hash chain */
5807 var bflush; /* set if current block must be flushed */
5808
5809 var max_insert;
5810
5811 /* Process the input block. */
5812 for (;;) {
5813 /* Make sure that we always have enough lookahead, except
5814 * at the end of the input file. We need MAX_MATCH bytes
5815 * for the next match, plus MIN_MATCH bytes to insert the
5816 * string following the next match.
5817 */
5818 if (s.lookahead < MIN_LOOKAHEAD) {
5819 fill_window(s);
5820 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
5821 return BS_NEED_MORE;
5822 }
5823 if (s.lookahead === 0) { break; } /* flush the current block */
5824 }
5825
5826 /* Insert the string window[strstart .. strstart+2] in the
5827 * dictionary, and set hash_head to the head of the hash chain:
5828 */
5829 hash_head = 0/*NIL*/;
5830 if (s.lookahead >= MIN_MATCH) {
5831 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
5832 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
5833 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
5834 s.head[s.ins_h] = s.strstart;
5835 /***/
5836 }
5837
5838 /* Find the longest match, discarding those <= prev_length.
5839 */
5840 s.prev_length = s.match_length;
5841 s.prev_match = s.match_start;
5842 s.match_length = MIN_MATCH - 1;
5843
5844 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
5845 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
5846 /* To simplify the code, we prevent matches with the string
5847 * of window index 0 (in particular we have to avoid a match
5848 * of the string with itself at the start of the input file).
5849 */
5850 s.match_length = longest_match(s, hash_head);
5851 /* longest_match() sets match_start */
5852
5853 if (s.match_length <= 5 &&
5854 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
5855
5856 /* If prev_match is also MIN_MATCH, match_start is garbage
5857 * but we will ignore the current match anyway.
5858 */
5859 s.match_length = MIN_MATCH - 1;
5860 }
5861 }
5862 /* If there was a match at the previous step and the current
5863 * match is not better, output the previous match:
5864 */
5865 if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
5866 max_insert = s.strstart + s.lookahead - MIN_MATCH;
5867 /* Do not insert strings in hash table beyond this. */
5868
5869 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
5870
5871 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
5872 s.prev_length - MIN_MATCH, bflush);***/
5873 bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
5874 /* Insert in hash table all strings up to the end of the match.
5875 * strstart-1 and strstart are already inserted. If there is not
5876 * enough lookahead, the last two strings are not inserted in
5877 * the hash table.
5878 */
5879 s.lookahead -= s.prev_length - 1;
5880 s.prev_length -= 2;
5881 do {
5882 if (++s.strstart <= max_insert) {
5883 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
5884 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
5885 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
5886 s.head[s.ins_h] = s.strstart;
5887 /***/
5888 }
5889 } while (--s.prev_length !== 0);
5890 s.match_available = 0;
5891 s.match_length = MIN_MATCH - 1;
5892 s.strstart++;
5893
5894 if (bflush) {
5895 /*** FLUSH_BLOCK(s, 0); ***/
5896 flush_block_only(s, false);
5897 if (s.strm.avail_out === 0) {
5898 return BS_NEED_MORE;
5899 }
5900 /***/
5901 }
5902
5903 } else if (s.match_available) {
5904 /* If there was no match at the previous position, output a
5905 * single literal. If there was a match but the current match
5906 * is longer, truncate the previous match to a single literal.
5907 */
5908 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
5909 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
5910 bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
5911
5912 if (bflush) {
5913 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
5914 flush_block_only(s, false);
5915 /***/
5916 }
5917 s.strstart++;
5918 s.lookahead--;
5919 if (s.strm.avail_out === 0) {
5920 return BS_NEED_MORE;
5921 }
5922 } else {
5923 /* There is no previous match to compare with, wait for
5924 * the next step to decide.
5925 */
5926 s.match_available = 1;
5927 s.strstart++;
5928 s.lookahead--;
5929 }
5930 }
5931 //Assert (flush != Z_NO_FLUSH, "no flush?");
5932 if (s.match_available) {
5933 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
5934 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
5935 bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
5936
5937 s.match_available = 0;
5938 }
5939 s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
5940 if (flush === Z_FINISH) {
5941 /*** FLUSH_BLOCK(s, 1); ***/
5942 flush_block_only(s, true);
5943 if (s.strm.avail_out === 0) {
5944 return BS_FINISH_STARTED;
5945 }
5946 /***/
5947 return BS_FINISH_DONE;
5948 }
5949 if (s.last_lit) {
5950 /*** FLUSH_BLOCK(s, 0); ***/
5951 flush_block_only(s, false);
5952 if (s.strm.avail_out === 0) {
5953 return BS_NEED_MORE;
5954 }
5955 /***/
5956 }
5957
5958 return BS_BLOCK_DONE;
5959}
5960
5961
5962/* ===========================================================================
5963 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
5964 * one. Do not maintain a hash table. (It will be regenerated if this run of
5965 * deflate switches away from Z_RLE.)
5966 */
5967function deflate_rle(s, flush) {
5968 var bflush; /* set if current block must be flushed */
5969 var prev; /* byte at distance one to match */
5970 var scan, strend; /* scan goes up to strend for length of run */
5971
5972 var _win = s.window;
5973
5974 for (;;) {
5975 /* Make sure that we always have enough lookahead, except
5976 * at the end of the input file. We need MAX_MATCH bytes
5977 * for the longest run, plus one for the unrolled loop.
5978 */
5979 if (s.lookahead <= MAX_MATCH) {
5980 fill_window(s);
5981 if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
5982 return BS_NEED_MORE;
5983 }
5984 if (s.lookahead === 0) { break; } /* flush the current block */
5985 }
5986
5987 /* See how many times the previous byte repeats */
5988 s.match_length = 0;
5989 if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
5990 scan = s.strstart - 1;
5991 prev = _win[scan];
5992 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
5993 strend = s.strstart + MAX_MATCH;
5994 do {
5995 /*jshint noempty:false*/
5996 } while (prev === _win[++scan] && prev === _win[++scan] &&
5997 prev === _win[++scan] && prev === _win[++scan] &&
5998 prev === _win[++scan] && prev === _win[++scan] &&
5999 prev === _win[++scan] && prev === _win[++scan] &&
6000 scan < strend);
6001 s.match_length = MAX_MATCH - (strend - scan);
6002 if (s.match_length > s.lookahead) {
6003 s.match_length = s.lookahead;
6004 }
6005 }
6006 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
6007 }
6008
6009 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
6010 if (s.match_length >= MIN_MATCH) {
6011 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
6012
6013 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
6014 bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
6015
6016 s.lookahead -= s.match_length;
6017 s.strstart += s.match_length;
6018 s.match_length = 0;
6019 } else {
6020 /* No match, output a literal byte */
6021 //Tracevv((stderr,"%c", s->window[s->strstart]));
6022 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6023 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6024
6025 s.lookahead--;
6026 s.strstart++;
6027 }
6028 if (bflush) {
6029 /*** FLUSH_BLOCK(s, 0); ***/
6030 flush_block_only(s, false);
6031 if (s.strm.avail_out === 0) {
6032 return BS_NEED_MORE;
6033 }
6034 /***/
6035 }
6036 }
6037 s.insert = 0;
6038 if (flush === Z_FINISH) {
6039 /*** FLUSH_BLOCK(s, 1); ***/
6040 flush_block_only(s, true);
6041 if (s.strm.avail_out === 0) {
6042 return BS_FINISH_STARTED;
6043 }
6044 /***/
6045 return BS_FINISH_DONE;
6046 }
6047 if (s.last_lit) {
6048 /*** FLUSH_BLOCK(s, 0); ***/
6049 flush_block_only(s, false);
6050 if (s.strm.avail_out === 0) {
6051 return BS_NEED_MORE;
6052 }
6053 /***/
6054 }
6055 return BS_BLOCK_DONE;
6056}
6057
6058/* ===========================================================================
6059 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
6060 * (It will be regenerated if this run of deflate switches away from Huffman.)
6061 */
6062function deflate_huff(s, flush) {
6063 var bflush; /* set if current block must be flushed */
6064
6065 for (;;) {
6066 /* Make sure that we have a literal to write. */
6067 if (s.lookahead === 0) {
6068 fill_window(s);
6069 if (s.lookahead === 0) {
6070 if (flush === Z_NO_FLUSH) {
6071 return BS_NEED_MORE;
6072 }
6073 break; /* flush the current block */
6074 }
6075 }
6076
6077 /* Output a literal byte */
6078 s.match_length = 0;
6079 //Tracevv((stderr,"%c", s->window[s->strstart]));
6080 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6081 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6082 s.lookahead--;
6083 s.strstart++;
6084 if (bflush) {
6085 /*** FLUSH_BLOCK(s, 0); ***/
6086 flush_block_only(s, false);
6087 if (s.strm.avail_out === 0) {
6088 return BS_NEED_MORE;
6089 }
6090 /***/
6091 }
6092 }
6093 s.insert = 0;
6094 if (flush === Z_FINISH) {
6095 /*** FLUSH_BLOCK(s, 1); ***/
6096 flush_block_only(s, true);
6097 if (s.strm.avail_out === 0) {
6098 return BS_FINISH_STARTED;
6099 }
6100 /***/
6101 return BS_FINISH_DONE;
6102 }
6103 if (s.last_lit) {
6104 /*** FLUSH_BLOCK(s, 0); ***/
6105 flush_block_only(s, false);
6106 if (s.strm.avail_out === 0) {
6107 return BS_NEED_MORE;
6108 }
6109 /***/
6110 }
6111 return BS_BLOCK_DONE;
6112}
6113
6114/* Values for max_lazy_match, good_match and max_chain_length, depending on
6115 * the desired pack level (0..9). The values given below have been tuned to
6116 * exclude worst case performance for pathological files. Better values may be
6117 * found for specific files.
6118 */
6119function Config(good_length, max_lazy, nice_length, max_chain, func) {
6120 this.good_length = good_length;
6121 this.max_lazy = max_lazy;
6122 this.nice_length = nice_length;
6123 this.max_chain = max_chain;
6124 this.func = func;
6125}
6126
6127var configuration_table;
6128
6129configuration_table = [
6130 /* good lazy nice chain */
6131 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
6132 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
6133 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
6134 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
6135
6136 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
6137 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
6138 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
6139 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
6140 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
6141 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
6142];
6143
6144
6145/* ===========================================================================
6146 * Initialize the "longest match" routines for a new zlib stream
6147 */
6148function lm_init(s) {
6149 s.window_size = 2 * s.w_size;
6150
6151 /*** CLEAR_HASH(s); ***/
6152 zero(s.head); // Fill with NIL (= 0);
6153
6154 /* Set the default configuration parameters:
6155 */
6156 s.max_lazy_match = configuration_table[s.level].max_lazy;
6157 s.good_match = configuration_table[s.level].good_length;
6158 s.nice_match = configuration_table[s.level].nice_length;
6159 s.max_chain_length = configuration_table[s.level].max_chain;
6160
6161 s.strstart = 0;
6162 s.block_start = 0;
6163 s.lookahead = 0;
6164 s.insert = 0;
6165 s.match_length = s.prev_length = MIN_MATCH - 1;
6166 s.match_available = 0;
6167 s.ins_h = 0;
6168}
6169
6170
6171function DeflateState() {
6172 this.strm = null; /* pointer back to this zlib stream */
6173 this.status = 0; /* as the name implies */
6174 this.pending_buf = null; /* output still pending */
6175 this.pending_buf_size = 0; /* size of pending_buf */
6176 this.pending_out = 0; /* next pending byte to output to the stream */
6177 this.pending = 0; /* nb of bytes in the pending buffer */
6178 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
6179 this.gzhead = null; /* gzip header information to write */
6180 this.gzindex = 0; /* where in extra, name, or comment */
6181 this.method = Z_DEFLATED; /* can only be DEFLATED */
6182 this.last_flush = -1; /* value of flush param for previous deflate call */
6183
6184 this.w_size = 0; /* LZ77 window size (32K by default) */
6185 this.w_bits = 0; /* log2(w_size) (8..16) */
6186 this.w_mask = 0; /* w_size - 1 */
6187
6188 this.window = null;
6189 /* Sliding window. Input bytes are read into the second half of the window,
6190 * and move to the first half later to keep a dictionary of at least wSize
6191 * bytes. With this organization, matches are limited to a distance of
6192 * wSize-MAX_MATCH bytes, but this ensures that IO is always
6193 * performed with a length multiple of the block size.
6194 */
6195
6196 this.window_size = 0;
6197 /* Actual size of window: 2*wSize, except when the user input buffer
6198 * is directly used as sliding window.
6199 */
6200
6201 this.prev = null;
6202 /* Link to older string with same hash index. To limit the size of this
6203 * array to 64K, this link is maintained only for the last 32K strings.
6204 * An index in this array is thus a window index modulo 32K.
6205 */
6206
6207 this.head = null; /* Heads of the hash chains or NIL. */
6208
6209 this.ins_h = 0; /* hash index of string to be inserted */
6210 this.hash_size = 0; /* number of elements in hash table */
6211 this.hash_bits = 0; /* log2(hash_size) */
6212 this.hash_mask = 0; /* hash_size-1 */
6213
6214 this.hash_shift = 0;
6215 /* Number of bits by which ins_h must be shifted at each input
6216 * step. It must be such that after MIN_MATCH steps, the oldest
6217 * byte no longer takes part in the hash key, that is:
6218 * hash_shift * MIN_MATCH >= hash_bits
6219 */
6220
6221 this.block_start = 0;
6222 /* Window position at the beginning of the current output block. Gets
6223 * negative when the window is moved backwards.
6224 */
6225
6226 this.match_length = 0; /* length of best match */
6227 this.prev_match = 0; /* previous match */
6228 this.match_available = 0; /* set if previous match exists */
6229 this.strstart = 0; /* start of string to insert */
6230 this.match_start = 0; /* start of matching string */
6231 this.lookahead = 0; /* number of valid bytes ahead in window */
6232
6233 this.prev_length = 0;
6234 /* Length of the best match at previous step. Matches not greater than this
6235 * are discarded. This is used in the lazy match evaluation.
6236 */
6237
6238 this.max_chain_length = 0;
6239 /* To speed up deflation, hash chains are never searched beyond this
6240 * length. A higher limit improves compression ratio but degrades the
6241 * speed.
6242 */
6243
6244 this.max_lazy_match = 0;
6245 /* Attempt to find a better match only when the current match is strictly
6246 * smaller than this value. This mechanism is used only for compression
6247 * levels >= 4.
6248 */
6249 // That's alias to max_lazy_match, don't use directly
6250 //this.max_insert_length = 0;
6251 /* Insert new strings in the hash table only if the match length is not
6252 * greater than this length. This saves time but degrades compression.
6253 * max_insert_length is used only for compression levels <= 3.
6254 */
6255
6256 this.level = 0; /* compression level (1..9) */
6257 this.strategy = 0; /* favor or force Huffman coding*/
6258
6259 this.good_match = 0;
6260 /* Use a faster search when the previous match is longer than this */
6261
6262 this.nice_match = 0; /* Stop searching when current match exceeds this */
6263
6264 /* used by trees.c: */
6265
6266 /* Didn't use ct_data typedef below to suppress compiler warning */
6267
6268 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
6269 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
6270 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
6271
6272 // Use flat array of DOUBLE size, with interleaved fata,
6273 // because JS does not support effective
6274 this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
6275 this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
6276 this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
6277 zero(this.dyn_ltree);
6278 zero(this.dyn_dtree);
6279 zero(this.bl_tree);
6280
6281 this.l_desc = null; /* desc. for literal tree */
6282 this.d_desc = null; /* desc. for distance tree */
6283 this.bl_desc = null; /* desc. for bit length tree */
6284
6285 //ush bl_count[MAX_BITS+1];
6286 this.bl_count = new utils.Buf16(MAX_BITS + 1);
6287 /* number of codes at each bit length for an optimal tree */
6288
6289 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
6290 this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
6291 zero(this.heap);
6292
6293 this.heap_len = 0; /* number of elements in the heap */
6294 this.heap_max = 0; /* element of largest frequency */
6295 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
6296 * The same heap array is used to build all trees.
6297 */
6298
6299 this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
6300 zero(this.depth);
6301 /* Depth of each subtree used as tie breaker for trees of equal frequency
6302 */
6303
6304 this.l_buf = 0; /* buffer index for literals or lengths */
6305
6306 this.lit_bufsize = 0;
6307 /* Size of match buffer for literals/lengths. There are 4 reasons for
6308 * limiting lit_bufsize to 64K:
6309 * - frequencies can be kept in 16 bit counters
6310 * - if compression is not successful for the first block, all input
6311 * data is still in the window so we can still emit a stored block even
6312 * when input comes from standard input. (This can also be done for
6313 * all blocks if lit_bufsize is not greater than 32K.)
6314 * - if compression is not successful for a file smaller than 64K, we can
6315 * even emit a stored file instead of a stored block (saving 5 bytes).
6316 * This is applicable only for zip (not gzip or zlib).
6317 * - creating new Huffman trees less frequently may not provide fast
6318 * adaptation to changes in the input data statistics. (Take for
6319 * example a binary file with poorly compressible code followed by
6320 * a highly compressible string table.) Smaller buffer sizes give
6321 * fast adaptation but have of course the overhead of transmitting
6322 * trees more frequently.
6323 * - I can't count above 4
6324 */
6325
6326 this.last_lit = 0; /* running index in l_buf */
6327
6328 this.d_buf = 0;
6329 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
6330 * the same number of elements. To use different lengths, an extra flag
6331 * array would be necessary.
6332 */
6333
6334 this.opt_len = 0; /* bit length of current block with optimal trees */
6335 this.static_len = 0; /* bit length of current block with static trees */
6336 this.matches = 0; /* number of string matches in current block */
6337 this.insert = 0; /* bytes at end of window left to insert */
6338
6339
6340 this.bi_buf = 0;
6341 /* Output buffer. bits are inserted starting at the bottom (least
6342 * significant bits).
6343 */
6344 this.bi_valid = 0;
6345 /* Number of valid bits in bi_buf. All bits above the last valid bit
6346 * are always zero.
6347 */
6348
6349 // Used for window memory init. We safely ignore it for JS. That makes
6350 // sense only for pointers and memory check tools.
6351 //this.high_water = 0;
6352 /* High water mark offset in window for initialized bytes -- bytes above
6353 * this are set to zero in order to avoid memory check warnings when
6354 * longest match routines access bytes past the input. This is then
6355 * updated to the new high water mark.
6356 */
6357}
6358
6359
6360function deflateResetKeep(strm) {
6361 var s;
6362
6363 if (!strm || !strm.state) {
6364 return err(strm, Z_STREAM_ERROR);
6365 }
6366
6367 strm.total_in = strm.total_out = 0;
6368 strm.data_type = Z_UNKNOWN;
6369
6370 s = strm.state;
6371 s.pending = 0;
6372 s.pending_out = 0;
6373
6374 if (s.wrap < 0) {
6375 s.wrap = -s.wrap;
6376 /* was made negative by deflate(..., Z_FINISH); */
6377 }
6378 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
6379 strm.adler = (s.wrap === 2) ?
6380 0 // crc32(0, Z_NULL, 0)
6381 :
6382 1; // adler32(0, Z_NULL, 0)
6383 s.last_flush = Z_NO_FLUSH;
6384 trees._tr_init(s);
6385 return Z_OK;
6386}
6387
6388
6389function deflateReset(strm) {
6390 var ret = deflateResetKeep(strm);
6391 if (ret === Z_OK) {
6392 lm_init(strm.state);
6393 }
6394 return ret;
6395}
6396
6397
6398function deflateSetHeader(strm, head) {
6399 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
6400 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
6401 strm.state.gzhead = head;
6402 return Z_OK;
6403}
6404
6405
6406function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
6407 if (!strm) { // === Z_NULL
6408 return Z_STREAM_ERROR;
6409 }
6410 var wrap = 1;
6411
6412 if (level === Z_DEFAULT_COMPRESSION) {
6413 level = 6;
6414 }
6415
6416 if (windowBits < 0) { /* suppress zlib wrapper */
6417 wrap = 0;
6418 windowBits = -windowBits;
6419 }
6420
6421 else if (windowBits > 15) {
6422 wrap = 2; /* write gzip wrapper instead */
6423 windowBits -= 16;
6424 }
6425
6426
6427 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
6428 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
6429 strategy < 0 || strategy > Z_FIXED) {
6430 return err(strm, Z_STREAM_ERROR);
6431 }
6432
6433
6434 if (windowBits === 8) {
6435 windowBits = 9;
6436 }
6437 /* until 256-byte window bug fixed */
6438
6439 var s = new DeflateState();
6440
6441 strm.state = s;
6442 s.strm = strm;
6443
6444 s.wrap = wrap;
6445 s.gzhead = null;
6446 s.w_bits = windowBits;
6447 s.w_size = 1 << s.w_bits;
6448 s.w_mask = s.w_size - 1;
6449
6450 s.hash_bits = memLevel + 7;
6451 s.hash_size = 1 << s.hash_bits;
6452 s.hash_mask = s.hash_size - 1;
6453 s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
6454
6455 s.window = new utils.Buf8(s.w_size * 2);
6456 s.head = new utils.Buf16(s.hash_size);
6457 s.prev = new utils.Buf16(s.w_size);
6458
6459 // Don't need mem init magic for JS.
6460 //s.high_water = 0; /* nothing written to s->window yet */
6461
6462 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
6463
6464 s.pending_buf_size = s.lit_bufsize * 4;
6465
6466 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
6467 //s->pending_buf = (uchf *) overlay;
6468 s.pending_buf = new utils.Buf8(s.pending_buf_size);
6469
6470 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
6471 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
6472 s.d_buf = 1 * s.lit_bufsize;
6473
6474 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
6475 s.l_buf = (1 + 2) * s.lit_bufsize;
6476
6477 s.level = level;
6478 s.strategy = strategy;
6479 s.method = method;
6480
6481 return deflateReset(strm);
6482}
6483
6484function deflateInit(strm, level) {
6485 return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
6486}
6487
6488
6489function deflate(strm, flush) {
6490 var old_flush, s;
6491 var beg, val; // for gzip header write only
6492
6493 if (!strm || !strm.state ||
6494 flush > Z_BLOCK || flush < 0) {
6495 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
6496 }
6497
6498 s = strm.state;
6499
6500 if (!strm.output ||
6501 (!strm.input && strm.avail_in !== 0) ||
6502 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
6503 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
6504 }
6505
6506 s.strm = strm; /* just in case */
6507 old_flush = s.last_flush;
6508 s.last_flush = flush;
6509
6510 /* Write the header */
6511 if (s.status === INIT_STATE) {
6512
6513 if (s.wrap === 2) { // GZIP header
6514 strm.adler = 0; //crc32(0L, Z_NULL, 0);
6515 put_byte(s, 31);
6516 put_byte(s, 139);
6517 put_byte(s, 8);
6518 if (!s.gzhead) { // s->gzhead == Z_NULL
6519 put_byte(s, 0);
6520 put_byte(s, 0);
6521 put_byte(s, 0);
6522 put_byte(s, 0);
6523 put_byte(s, 0);
6524 put_byte(s, s.level === 9 ? 2 :
6525 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
6526 4 : 0));
6527 put_byte(s, OS_CODE);
6528 s.status = BUSY_STATE;
6529 }
6530 else {
6531 put_byte(s, (s.gzhead.text ? 1 : 0) +
6532 (s.gzhead.hcrc ? 2 : 0) +
6533 (!s.gzhead.extra ? 0 : 4) +
6534 (!s.gzhead.name ? 0 : 8) +
6535 (!s.gzhead.comment ? 0 : 16)
6536 );
6537 put_byte(s, s.gzhead.time & 0xff);
6538 put_byte(s, (s.gzhead.time >> 8) & 0xff);
6539 put_byte(s, (s.gzhead.time >> 16) & 0xff);
6540 put_byte(s, (s.gzhead.time >> 24) & 0xff);
6541 put_byte(s, s.level === 9 ? 2 :
6542 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
6543 4 : 0));
6544 put_byte(s, s.gzhead.os & 0xff);
6545 if (s.gzhead.extra && s.gzhead.extra.length) {
6546 put_byte(s, s.gzhead.extra.length & 0xff);
6547 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
6548 }
6549 if (s.gzhead.hcrc) {
6550 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
6551 }
6552 s.gzindex = 0;
6553 s.status = EXTRA_STATE;
6554 }
6555 }
6556 else // DEFLATE header
6557 {
6558 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
6559 var level_flags = -1;
6560
6561 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
6562 level_flags = 0;
6563 } else if (s.level < 6) {
6564 level_flags = 1;
6565 } else if (s.level === 6) {
6566 level_flags = 2;
6567 } else {
6568 level_flags = 3;
6569 }
6570 header |= (level_flags << 6);
6571 if (s.strstart !== 0) { header |= PRESET_DICT; }
6572 header += 31 - (header % 31);
6573
6574 s.status = BUSY_STATE;
6575 putShortMSB(s, header);
6576
6577 /* Save the adler32 of the preset dictionary: */
6578 if (s.strstart !== 0) {
6579 putShortMSB(s, strm.adler >>> 16);
6580 putShortMSB(s, strm.adler & 0xffff);
6581 }
6582 strm.adler = 1; // adler32(0L, Z_NULL, 0);
6583 }
6584 }
6585
6586//#ifdef GZIP
6587 if (s.status === EXTRA_STATE) {
6588 if (s.gzhead.extra/* != Z_NULL*/) {
6589 beg = s.pending; /* start of bytes to update crc */
6590
6591 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
6592 if (s.pending === s.pending_buf_size) {
6593 if (s.gzhead.hcrc && s.pending > beg) {
6594 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
6595 }
6596 flush_pending(strm);
6597 beg = s.pending;
6598 if (s.pending === s.pending_buf_size) {
6599 break;
6600 }
6601 }
6602 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
6603 s.gzindex++;
6604 }
6605 if (s.gzhead.hcrc && s.pending > beg) {
6606 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
6607 }
6608 if (s.gzindex === s.gzhead.extra.length) {
6609 s.gzindex = 0;
6610 s.status = NAME_STATE;
6611 }
6612 }
6613 else {
6614 s.status = NAME_STATE;
6615 }
6616 }
6617 if (s.status === NAME_STATE) {
6618 if (s.gzhead.name/* != Z_NULL*/) {
6619 beg = s.pending; /* start of bytes to update crc */
6620 //int val;
6621
6622 do {
6623 if (s.pending === s.pending_buf_size) {
6624 if (s.gzhead.hcrc && s.pending > beg) {
6625 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
6626 }
6627 flush_pending(strm);
6628 beg = s.pending;
6629 if (s.pending === s.pending_buf_size) {
6630 val = 1;
6631 break;
6632 }
6633 }
6634 // JS specific: little magic to add zero terminator to end of string
6635 if (s.gzindex < s.gzhead.name.length) {
6636 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
6637 } else {
6638 val = 0;
6639 }
6640 put_byte(s, val);
6641 } while (val !== 0);
6642
6643 if (s.gzhead.hcrc && s.pending > beg) {
6644 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
6645 }
6646 if (val === 0) {
6647 s.gzindex = 0;
6648 s.status = COMMENT_STATE;
6649 }
6650 }
6651 else {
6652 s.status = COMMENT_STATE;
6653 }
6654 }
6655 if (s.status === COMMENT_STATE) {
6656 if (s.gzhead.comment/* != Z_NULL*/) {
6657 beg = s.pending; /* start of bytes to update crc */
6658 //int val;
6659
6660 do {
6661 if (s.pending === s.pending_buf_size) {
6662 if (s.gzhead.hcrc && s.pending > beg) {
6663 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
6664 }
6665 flush_pending(strm);
6666 beg = s.pending;
6667 if (s.pending === s.pending_buf_size) {
6668 val = 1;
6669 break;
6670 }
6671 }
6672 // JS specific: little magic to add zero terminator to end of string
6673 if (s.gzindex < s.gzhead.comment.length) {
6674 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
6675 } else {
6676 val = 0;
6677 }
6678 put_byte(s, val);
6679 } while (val !== 0);
6680
6681 if (s.gzhead.hcrc && s.pending > beg) {
6682 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
6683 }
6684 if (val === 0) {
6685 s.status = HCRC_STATE;
6686 }
6687 }
6688 else {
6689 s.status = HCRC_STATE;
6690 }
6691 }
6692 if (s.status === HCRC_STATE) {
6693 if (s.gzhead.hcrc) {
6694 if (s.pending + 2 > s.pending_buf_size) {
6695 flush_pending(strm);
6696 }
6697 if (s.pending + 2 <= s.pending_buf_size) {
6698 put_byte(s, strm.adler & 0xff);
6699 put_byte(s, (strm.adler >> 8) & 0xff);
6700 strm.adler = 0; //crc32(0L, Z_NULL, 0);
6701 s.status = BUSY_STATE;
6702 }
6703 }
6704 else {
6705 s.status = BUSY_STATE;
6706 }
6707 }
6708//#endif
6709
6710 /* Flush as much pending output as possible */
6711 if (s.pending !== 0) {
6712 flush_pending(strm);
6713 if (strm.avail_out === 0) {
6714 /* Since avail_out is 0, deflate will be called again with
6715 * more output space, but possibly with both pending and
6716 * avail_in equal to zero. There won't be anything to do,
6717 * but this is not an error situation so make sure we
6718 * return OK instead of BUF_ERROR at next call of deflate:
6719 */
6720 s.last_flush = -1;
6721 return Z_OK;
6722 }
6723
6724 /* Make sure there is something to do and avoid duplicate consecutive
6725 * flushes. For repeated and useless calls with Z_FINISH, we keep
6726 * returning Z_STREAM_END instead of Z_BUF_ERROR.
6727 */
6728 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
6729 flush !== Z_FINISH) {
6730 return err(strm, Z_BUF_ERROR);
6731 }
6732
6733 /* User must not provide more input after the first FINISH: */
6734 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
6735 return err(strm, Z_BUF_ERROR);
6736 }
6737
6738 /* Start a new block or continue the current one.
6739 */
6740 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
6741 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
6742 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
6743 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
6744 configuration_table[s.level].func(s, flush));
6745
6746 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
6747 s.status = FINISH_STATE;
6748 }
6749 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
6750 if (strm.avail_out === 0) {
6751 s.last_flush = -1;
6752 /* avoid BUF_ERROR next call, see above */
6753 }
6754 return Z_OK;
6755 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
6756 * of deflate should use the same flush parameter to make sure
6757 * that the flush is complete. So we don't have to output an
6758 * empty block here, this will be done at next call. This also
6759 * ensures that for a very small output buffer, we emit at most
6760 * one empty block.
6761 */
6762 }
6763 if (bstate === BS_BLOCK_DONE) {
6764 if (flush === Z_PARTIAL_FLUSH) {
6765 trees._tr_align(s);
6766 }
6767 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
6768
6769 trees._tr_stored_block(s, 0, 0, false);
6770 /* For a full flush, this empty block will be recognized
6771 * as a special marker by inflate_sync().
6772 */
6773 if (flush === Z_FULL_FLUSH) {
6774 /*** CLEAR_HASH(s); ***/ /* forget history */
6775 zero(s.head); // Fill with NIL (= 0);
6776
6777 if (s.lookahead === 0) {
6778 s.strstart = 0;
6779 s.block_start = 0;
6780 s.insert = 0;
6781 }
6782 }
6783 }
6784 flush_pending(strm);
6785 if (strm.avail_out === 0) {
6786 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
6787 return Z_OK;
6788 }
6789 }
6790 }
6791 //Assert(strm->avail_out > 0, "bug2");
6792 //if (strm.avail_out <= 0) { throw new Error("bug2");}
6793
6794 if (flush !== Z_FINISH) { return Z_OK; }
6795 if (s.wrap <= 0) { return Z_STREAM_END; }
6796
6797 /* Write the trailer */
6798 if (s.wrap === 2) {
6799 put_byte(s, strm.adler & 0xff);
6800 put_byte(s, (strm.adler >> 8) & 0xff);
6801 put_byte(s, (strm.adler >> 16) & 0xff);
6802 put_byte(s, (strm.adler >> 24) & 0xff);
6803 put_byte(s, strm.total_in & 0xff);
6804 put_byte(s, (strm.total_in >> 8) & 0xff);
6805 put_byte(s, (strm.total_in >> 16) & 0xff);
6806 put_byte(s, (strm.total_in >> 24) & 0xff);
6807 }
6808 else
6809 {
6810 putShortMSB(s, strm.adler >>> 16);
6811 putShortMSB(s, strm.adler & 0xffff);
6812 }
6813
6814 flush_pending(strm);
6815 /* If avail_out is zero, the application will call deflate again
6816 * to flush the rest.
6817 */
6818 if (s.wrap > 0) { s.wrap = -s.wrap; }
6819 /* write the trailer only once! */
6820 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
6821}
6822
6823function deflateEnd(strm) {
6824 var status;
6825
6826 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
6827 return Z_STREAM_ERROR;
6828 }
6829
6830 status = strm.state.status;
6831 if (status !== INIT_STATE &&
6832 status !== EXTRA_STATE &&
6833 status !== NAME_STATE &&
6834 status !== COMMENT_STATE &&
6835 status !== HCRC_STATE &&
6836 status !== BUSY_STATE &&
6837 status !== FINISH_STATE
6838 ) {
6839 return err(strm, Z_STREAM_ERROR);
6840 }
6841
6842 strm.state = null;
6843
6844 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
6845}
6846
6847
6848/* =========================================================================
6849 * Initializes the compression dictionary from the given byte
6850 * sequence without producing any compressed output.
6851 */
6852function deflateSetDictionary(strm, dictionary) {
6853 var dictLength = dictionary.length;
6854
6855 var s;
6856 var str, n;
6857 var wrap;
6858 var avail;
6859 var next;
6860 var input;
6861 var tmpDict;
6862
6863 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
6864 return Z_STREAM_ERROR;
6865 }
6866
6867 s = strm.state;
6868 wrap = s.wrap;
6869
6870 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
6871 return Z_STREAM_ERROR;
6872 }
6873
6874 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
6875 if (wrap === 1) {
6876 /* adler32(strm->adler, dictionary, dictLength); */
6877 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
6878 }
6879
6880 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
6881
6882 /* if dictionary would fill window, just replace the history */
6883 if (dictLength >= s.w_size) {
6884 if (wrap === 0) { /* already empty otherwise */
6885 /*** CLEAR_HASH(s); ***/
6886 zero(s.head); // Fill with NIL (= 0);
6887 s.strstart = 0;
6888 s.block_start = 0;
6889 s.insert = 0;
6890 }
6891 /* use the tail */
6892 // dictionary = dictionary.slice(dictLength - s.w_size);
6893 tmpDict = new utils.Buf8(s.w_size);
6894 utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
6895 dictionary = tmpDict;
6896 dictLength = s.w_size;
6897 }
6898 /* insert dictionary into window and hash */
6899 avail = strm.avail_in;
6900 next = strm.next_in;
6901 input = strm.input;
6902 strm.avail_in = dictLength;
6903 strm.next_in = 0;
6904 strm.input = dictionary;
6905 fill_window(s);
6906 while (s.lookahead >= MIN_MATCH) {
6907 str = s.strstart;
6908 n = s.lookahead - (MIN_MATCH - 1);
6909 do {
6910 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
6911 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
6912
6913 s.prev[str & s.w_mask] = s.head[s.ins_h];
6914
6915 s.head[s.ins_h] = str;
6916 str++;
6917 } while (--n);
6918 s.strstart = str;
6919 s.lookahead = MIN_MATCH - 1;
6920 fill_window(s);
6921 }
6922 s.strstart += s.lookahead;
6923 s.block_start = s.strstart;
6924 s.insert = s.lookahead;
6925 s.lookahead = 0;
6926 s.match_length = s.prev_length = MIN_MATCH - 1;
6927 s.match_available = 0;
6928 strm.next_in = next;
6929 strm.input = input;
6930 strm.avail_in = avail;
6931 s.wrap = wrap;
6932 return Z_OK;
6933}
6934
6935
6936exports.deflateInit = deflateInit;
6937exports.deflateInit2 = deflateInit2;
6938exports.deflateReset = deflateReset;
6939exports.deflateResetKeep = deflateResetKeep;
6940exports.deflateSetHeader = deflateSetHeader;
6941exports.deflate = deflate;
6942exports.deflateEnd = deflateEnd;
6943exports.deflateSetDictionary = deflateSetDictionary;
6944exports.deflateInfo = 'pako deflate (from Nodeca project)';
6945
6946/* Not implemented
6947exports.deflateBound = deflateBound;
6948exports.deflateCopy = deflateCopy;
6949exports.deflateParams = deflateParams;
6950exports.deflatePending = deflatePending;
6951exports.deflatePrime = deflatePrime;
6952exports.deflateTune = deflateTune;
6953*/
6954
6955},{"../utils/common":16,"./adler32":17,"./crc32":19,"./messages":24,"./trees":25}],21:[function(require,module,exports){
6956'use strict';
6957
6958// (C) 1995-2013 Jean-loup Gailly and Mark Adler
6959// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
6960//
6961// This software is provided 'as-is', without any express or implied
6962// warranty. In no event will the authors be held liable for any damages
6963// arising from the use of this software.
6964//
6965// Permission is granted to anyone to use this software for any purpose,
6966// including commercial applications, and to alter it and redistribute it
6967// freely, subject to the following restrictions:
6968//
6969// 1. The origin of this software must not be misrepresented; you must not
6970// claim that you wrote the original software. If you use this software
6971// in a product, an acknowledgment in the product documentation would be
6972// appreciated but is not required.
6973// 2. Altered source versions must be plainly marked as such, and must not be
6974// misrepresented as being the original software.
6975// 3. This notice may not be removed or altered from any source distribution.
6976
6977// See state defs from inflate.js
6978var BAD = 30; /* got a data error -- remain here until reset */
6979var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
6980
6981/*
6982 Decode literal, length, and distance codes and write out the resulting
6983 literal and match bytes until either not enough input or output is
6984 available, an end-of-block is encountered, or a data error is encountered.
6985 When large enough input and output buffers are supplied to inflate(), for
6986 example, a 16K input buffer and a 64K output buffer, more than 95% of the
6987 inflate execution time is spent in this routine.
6988
6989 Entry assumptions:
6990
6991 state.mode === LEN
6992 strm.avail_in >= 6
6993 strm.avail_out >= 258
6994 start >= strm.avail_out
6995 state.bits < 8
6996
6997 On return, state.mode is one of:
6998
6999 LEN -- ran out of enough output space or enough available input
7000 TYPE -- reached end of block code, inflate() to interpret next block
7001 BAD -- error in block data
7002
7003 Notes:
7004
7005 - The maximum input bits used by a length/distance pair is 15 bits for the
7006 length code, 5 bits for the length extra, 15 bits for the distance code,
7007 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
7008 Therefore if strm.avail_in >= 6, then there is enough input to avoid
7009 checking for available input while decoding.
7010
7011 - The maximum bytes that a single length/distance pair can output is 258
7012 bytes, which is the maximum length that can be coded. inflate_fast()
7013 requires strm.avail_out >= 258 for each loop to avoid checking for
7014 output space.
7015 */
7016module.exports = function inflate_fast(strm, start) {
7017 var state;
7018 var _in; /* local strm.input */
7019 var last; /* have enough input while in < last */
7020 var _out; /* local strm.output */
7021 var beg; /* inflate()'s initial strm.output */
7022 var end; /* while out < end, enough space available */
7023//#ifdef INFLATE_STRICT
7024 var dmax; /* maximum distance from zlib header */
7025//#endif
7026 var wsize; /* window size or zero if not using window */
7027 var whave; /* valid bytes in the window */
7028 var wnext; /* window write index */
7029 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
7030 var s_window; /* allocated sliding window, if wsize != 0 */
7031 var hold; /* local strm.hold */
7032 var bits; /* local strm.bits */
7033 var lcode; /* local strm.lencode */
7034 var dcode; /* local strm.distcode */
7035 var lmask; /* mask for first level of length codes */
7036 var dmask; /* mask for first level of distance codes */
7037 var here; /* retrieved table entry */
7038 var op; /* code bits, operation, extra bits, or */
7039 /* window position, window bytes to copy */
7040 var len; /* match length, unused bytes */
7041 var dist; /* match distance */
7042 var from; /* where to copy match from */
7043 var from_source;
7044
7045
7046 var input, output; // JS specific, because we have no pointers
7047
7048 /* copy state to local variables */
7049 state = strm.state;
7050 //here = state.here;
7051 _in = strm.next_in;
7052 input = strm.input;
7053 last = _in + (strm.avail_in - 5);
7054 _out = strm.next_out;
7055 output = strm.output;
7056 beg = _out - (start - strm.avail_out);
7057 end = _out + (strm.avail_out - 257);
7058//#ifdef INFLATE_STRICT
7059 dmax = state.dmax;
7060//#endif
7061 wsize = state.wsize;
7062 whave = state.whave;
7063 wnext = state.wnext;
7064 s_window = state.window;
7065 hold = state.hold;
7066 bits = state.bits;
7067 lcode = state.lencode;
7068 dcode = state.distcode;
7069 lmask = (1 << state.lenbits) - 1;
7070 dmask = (1 << state.distbits) - 1;
7071
7072
7073 /* decode literals and length/distances until end-of-block or not enough
7074 input data or output space */
7075
7076 top:
7077 do {
7078 if (bits < 15) {
7079 hold += input[_in++] << bits;
7080 bits += 8;
7081 hold += input[_in++] << bits;
7082 bits += 8;
7083 }
7084
7085 here = lcode[hold & lmask];
7086
7087 dolen:
7088 for (;;) { // Goto emulation
7089 op = here >>> 24/*here.bits*/;
7090 hold >>>= op;
7091 bits -= op;
7092 op = (here >>> 16) & 0xff/*here.op*/;
7093 if (op === 0) { /* literal */
7094 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
7095 // "inflate: literal '%c'\n" :
7096 // "inflate: literal 0x%02x\n", here.val));
7097 output[_out++] = here & 0xffff/*here.val*/;
7098 }
7099 else if (op & 16) { /* length base */
7100 len = here & 0xffff/*here.val*/;
7101 op &= 15; /* number of extra bits */
7102 if (op) {
7103 if (bits < op) {
7104 hold += input[_in++] << bits;
7105 bits += 8;
7106 }
7107 len += hold & ((1 << op) - 1);
7108 hold >>>= op;
7109 bits -= op;
7110 }
7111 //Tracevv((stderr, "inflate: length %u\n", len));
7112 if (bits < 15) {
7113 hold += input[_in++] << bits;
7114 bits += 8;
7115 hold += input[_in++] << bits;
7116 bits += 8;
7117 }
7118 here = dcode[hold & dmask];
7119
7120 dodist:
7121 for (;;) { // goto emulation
7122 op = here >>> 24/*here.bits*/;
7123 hold >>>= op;
7124 bits -= op;
7125 op = (here >>> 16) & 0xff/*here.op*/;
7126
7127 if (op & 16) { /* distance base */
7128 dist = here & 0xffff/*here.val*/;
7129 op &= 15; /* number of extra bits */
7130 if (bits < op) {
7131 hold += input[_in++] << bits;
7132 bits += 8;
7133 if (bits < op) {
7134 hold += input[_in++] << bits;
7135 bits += 8;
7136 }
7137 }
7138 dist += hold & ((1 << op) - 1);
7139//#ifdef INFLATE_STRICT
7140 if (dist > dmax) {
7141 strm.msg = 'invalid distance too far back';
7142 state.mode = BAD;
7143 break top;
7144 }
7145//#endif
7146 hold >>>= op;
7147 bits -= op;
7148 //Tracevv((stderr, "inflate: distance %u\n", dist));
7149 op = _out - beg; /* max distance in output */
7150 if (dist > op) { /* see if copy from window */
7151 op = dist - op; /* distance back in window */
7152 if (op > whave) {
7153 if (state.sane) {
7154 strm.msg = 'invalid distance too far back';
7155 state.mode = BAD;
7156 break top;
7157 }
7158
7159// (!) This block is disabled in zlib defaults,
7160// don't enable it for binary compatibility
7161//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
7162// if (len <= op - whave) {
7163// do {
7164// output[_out++] = 0;
7165// } while (--len);
7166// continue top;
7167// }
7168// len -= op - whave;
7169// do {
7170// output[_out++] = 0;
7171// } while (--op > whave);
7172// if (op === 0) {
7173// from = _out - dist;
7174// do {
7175// output[_out++] = output[from++];
7176// } while (--len);
7177// continue top;
7178// }
7179//#endif
7180 }
7181 from = 0; // window index
7182 from_source = s_window;
7183 if (wnext === 0) { /* very common case */
7184 from += wsize - op;
7185 if (op < len) { /* some from window */
7186 len -= op;
7187 do {
7188 output[_out++] = s_window[from++];
7189 } while (--op);
7190 from = _out - dist; /* rest from output */
7191 from_source = output;
7192 }
7193 }
7194 else if (wnext < op) { /* wrap around window */
7195 from += wsize + wnext - op;
7196 op -= wnext;
7197 if (op < len) { /* some from end of window */
7198 len -= op;
7199 do {
7200 output[_out++] = s_window[from++];
7201 } while (--op);
7202 from = 0;
7203 if (wnext < len) { /* some from start of window */
7204 op = wnext;
7205 len -= op;
7206 do {
7207 output[_out++] = s_window[from++];
7208 } while (--op);
7209 from = _out - dist; /* rest from output */
7210 from_source = output;
7211 }
7212 }
7213 }
7214 else { /* contiguous in window */
7215 from += wnext - op;
7216 if (op < len) { /* some from window */
7217 len -= op;
7218 do {
7219 output[_out++] = s_window[from++];
7220 } while (--op);
7221 from = _out - dist; /* rest from output */
7222 from_source = output;
7223 }
7224 }
7225 while (len > 2) {
7226 output[_out++] = from_source[from++];
7227 output[_out++] = from_source[from++];
7228 output[_out++] = from_source[from++];
7229 len -= 3;
7230 }
7231 if (len) {
7232 output[_out++] = from_source[from++];
7233 if (len > 1) {
7234 output[_out++] = from_source[from++];
7235 }
7236 }
7237 }
7238 else {
7239 from = _out - dist; /* copy direct from output */
7240 do { /* minimum length is three */
7241 output[_out++] = output[from++];
7242 output[_out++] = output[from++];
7243 output[_out++] = output[from++];
7244 len -= 3;
7245 } while (len > 2);
7246 if (len) {
7247 output[_out++] = output[from++];
7248 if (len > 1) {
7249 output[_out++] = output[from++];
7250 }
7251 }
7252 }
7253 }
7254 else if ((op & 64) === 0) { /* 2nd level distance code */
7255 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
7256 continue dodist;
7257 }
7258 else {
7259 strm.msg = 'invalid distance code';
7260 state.mode = BAD;
7261 break top;
7262 }
7263
7264 break; // need to emulate goto via "continue"
7265 }
7266 }
7267 else if ((op & 64) === 0) { /* 2nd level length code */
7268 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
7269 continue dolen;
7270 }
7271 else if (op & 32) { /* end-of-block */
7272 //Tracevv((stderr, "inflate: end of block\n"));
7273 state.mode = TYPE;
7274 break top;
7275 }
7276 else {
7277 strm.msg = 'invalid literal/length code';
7278 state.mode = BAD;
7279 break top;
7280 }
7281
7282 break; // need to emulate goto via "continue"
7283 }
7284 } while (_in < last && _out < end);
7285
7286 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
7287 len = bits >> 3;
7288 _in -= len;
7289 bits -= len << 3;
7290 hold &= (1 << bits) - 1;
7291
7292 /* update state and return */
7293 strm.next_in = _in;
7294 strm.next_out = _out;
7295 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
7296 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
7297 state.hold = hold;
7298 state.bits = bits;
7299 return;
7300};
7301
7302},{}],22:[function(require,module,exports){
7303'use strict';
7304
7305// (C) 1995-2013 Jean-loup Gailly and Mark Adler
7306// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
7307//
7308// This software is provided 'as-is', without any express or implied
7309// warranty. In no event will the authors be held liable for any damages
7310// arising from the use of this software.
7311//
7312// Permission is granted to anyone to use this software for any purpose,
7313// including commercial applications, and to alter it and redistribute it
7314// freely, subject to the following restrictions:
7315//
7316// 1. The origin of this software must not be misrepresented; you must not
7317// claim that you wrote the original software. If you use this software
7318// in a product, an acknowledgment in the product documentation would be
7319// appreciated but is not required.
7320// 2. Altered source versions must be plainly marked as such, and must not be
7321// misrepresented as being the original software.
7322// 3. This notice may not be removed or altered from any source distribution.
7323
7324var utils = require('../utils/common');
7325var adler32 = require('./adler32');
7326var crc32 = require('./crc32');
7327var inflate_fast = require('./inffast');
7328var inflate_table = require('./inftrees');
7329
7330var CODES = 0;
7331var LENS = 1;
7332var DISTS = 2;
7333
7334/* Public constants ==========================================================*/
7335/* ===========================================================================*/
7336
7337
7338/* Allowed flush values; see deflate() and inflate() below for details */
7339//var Z_NO_FLUSH = 0;
7340//var Z_PARTIAL_FLUSH = 1;
7341//var Z_SYNC_FLUSH = 2;
7342//var Z_FULL_FLUSH = 3;
7343var Z_FINISH = 4;
7344var Z_BLOCK = 5;
7345var Z_TREES = 6;
7346
7347
7348/* Return codes for the compression/decompression functions. Negative values
7349 * are errors, positive values are used for special but normal events.
7350 */
7351var Z_OK = 0;
7352var Z_STREAM_END = 1;
7353var Z_NEED_DICT = 2;
7354//var Z_ERRNO = -1;
7355var Z_STREAM_ERROR = -2;
7356var Z_DATA_ERROR = -3;
7357var Z_MEM_ERROR = -4;
7358var Z_BUF_ERROR = -5;
7359//var Z_VERSION_ERROR = -6;
7360
7361/* The deflate compression method */
7362var Z_DEFLATED = 8;
7363
7364
7365/* STATES ====================================================================*/
7366/* ===========================================================================*/
7367
7368
7369var HEAD = 1; /* i: waiting for magic header */
7370var FLAGS = 2; /* i: waiting for method and flags (gzip) */
7371var TIME = 3; /* i: waiting for modification time (gzip) */
7372var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
7373var EXLEN = 5; /* i: waiting for extra length (gzip) */
7374var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
7375var NAME = 7; /* i: waiting for end of file name (gzip) */
7376var COMMENT = 8; /* i: waiting for end of comment (gzip) */
7377var HCRC = 9; /* i: waiting for header crc (gzip) */
7378var DICTID = 10; /* i: waiting for dictionary check value */
7379var DICT = 11; /* waiting for inflateSetDictionary() call */
7380var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
7381var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
7382var STORED = 14; /* i: waiting for stored size (length and complement) */
7383var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
7384var COPY = 16; /* i/o: waiting for input or output to copy stored block */
7385var TABLE = 17; /* i: waiting for dynamic block table lengths */
7386var LENLENS = 18; /* i: waiting for code length code lengths */
7387var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
7388var LEN_ = 20; /* i: same as LEN below, but only first time in */
7389var LEN = 21; /* i: waiting for length/lit/eob code */
7390var LENEXT = 22; /* i: waiting for length extra bits */
7391var DIST = 23; /* i: waiting for distance code */
7392var DISTEXT = 24; /* i: waiting for distance extra bits */
7393var MATCH = 25; /* o: waiting for output space to copy string */
7394var LIT = 26; /* o: waiting for output space to write literal */
7395var CHECK = 27; /* i: waiting for 32-bit check value */
7396var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
7397var DONE = 29; /* finished check, done -- remain here until reset */
7398var BAD = 30; /* got a data error -- remain here until reset */
7399var MEM = 31; /* got an inflate() memory error -- remain here until reset */
7400var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
7401
7402/* ===========================================================================*/
7403
7404
7405
7406var ENOUGH_LENS = 852;
7407var ENOUGH_DISTS = 592;
7408//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
7409
7410var MAX_WBITS = 15;
7411/* 32K LZ77 window */
7412var DEF_WBITS = MAX_WBITS;
7413
7414
7415function zswap32(q) {
7416 return (((q >>> 24) & 0xff) +
7417 ((q >>> 8) & 0xff00) +
7418 ((q & 0xff00) << 8) +
7419 ((q & 0xff) << 24));
7420}
7421
7422
7423function InflateState() {
7424 this.mode = 0; /* current inflate mode */
7425 this.last = false; /* true if processing last block */
7426 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
7427 this.havedict = false; /* true if dictionary provided */
7428 this.flags = 0; /* gzip header method and flags (0 if zlib) */
7429 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
7430 this.check = 0; /* protected copy of check value */
7431 this.total = 0; /* protected copy of output count */
7432 // TODO: may be {}
7433 this.head = null; /* where to save gzip header information */
7434
7435 /* sliding window */
7436 this.wbits = 0; /* log base 2 of requested window size */
7437 this.wsize = 0; /* window size or zero if not using window */
7438 this.whave = 0; /* valid bytes in the window */
7439 this.wnext = 0; /* window write index */
7440 this.window = null; /* allocated sliding window, if needed */
7441
7442 /* bit accumulator */
7443 this.hold = 0; /* input bit accumulator */
7444 this.bits = 0; /* number of bits in "in" */
7445
7446 /* for string and stored block copying */
7447 this.length = 0; /* literal or length of data to copy */
7448 this.offset = 0; /* distance back to copy string from */
7449
7450 /* for table and code decoding */
7451 this.extra = 0; /* extra bits needed */
7452
7453 /* fixed and dynamic code tables */
7454 this.lencode = null; /* starting table for length/literal codes */
7455 this.distcode = null; /* starting table for distance codes */
7456 this.lenbits = 0; /* index bits for lencode */
7457 this.distbits = 0; /* index bits for distcode */
7458
7459 /* dynamic table building */
7460 this.ncode = 0; /* number of code length code lengths */
7461 this.nlen = 0; /* number of length code lengths */
7462 this.ndist = 0; /* number of distance code lengths */
7463 this.have = 0; /* number of code lengths in lens[] */
7464 this.next = null; /* next available space in codes[] */
7465
7466 this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
7467 this.work = new utils.Buf16(288); /* work area for code table building */
7468
7469 /*
7470 because we don't have pointers in js, we use lencode and distcode directly
7471 as buffers so we don't need codes
7472 */
7473 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
7474 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
7475 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
7476 this.sane = 0; /* if false, allow invalid distance too far */
7477 this.back = 0; /* bits back of last unprocessed length/lit */
7478 this.was = 0; /* initial length of match */
7479}
7480
7481function inflateResetKeep(strm) {
7482 var state;
7483
7484 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
7485 state = strm.state;
7486 strm.total_in = strm.total_out = state.total = 0;
7487 strm.msg = ''; /*Z_NULL*/
7488 if (state.wrap) { /* to support ill-conceived Java test suite */
7489 strm.adler = state.wrap & 1;
7490 }
7491 state.mode = HEAD;
7492 state.last = 0;
7493 state.havedict = 0;
7494 state.dmax = 32768;
7495 state.head = null/*Z_NULL*/;
7496 state.hold = 0;
7497 state.bits = 0;
7498 //state.lencode = state.distcode = state.next = state.codes;
7499 state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
7500 state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
7501
7502 state.sane = 1;
7503 state.back = -1;
7504 //Tracev((stderr, "inflate: reset\n"));
7505 return Z_OK;
7506}
7507
7508function inflateReset(strm) {
7509 var state;
7510
7511 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
7512 state = strm.state;
7513 state.wsize = 0;
7514 state.whave = 0;
7515 state.wnext = 0;
7516 return inflateResetKeep(strm);
7517
7518}
7519
7520function inflateReset2(strm, windowBits) {
7521 var wrap;
7522 var state;
7523
7524 /* get the state */
7525 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
7526 state = strm.state;
7527
7528 /* extract wrap request from windowBits parameter */
7529 if (windowBits < 0) {
7530 wrap = 0;
7531 windowBits = -windowBits;
7532 }
7533 else {
7534 wrap = (windowBits >> 4) + 1;
7535 if (windowBits < 48) {
7536 windowBits &= 15;
7537 }
7538 }
7539
7540 /* set number of window bits, free window if different */
7541 if (windowBits && (windowBits < 8 || windowBits > 15)) {
7542 return Z_STREAM_ERROR;
7543 }
7544 if (state.window !== null && state.wbits !== windowBits) {
7545 state.window = null;
7546 }
7547
7548 /* update state and reset the rest of it */
7549 state.wrap = wrap;
7550 state.wbits = windowBits;
7551 return inflateReset(strm);
7552}
7553
7554function inflateInit2(strm, windowBits) {
7555 var ret;
7556 var state;
7557
7558 if (!strm) { return Z_STREAM_ERROR; }
7559 //strm.msg = Z_NULL; /* in case we return an error */
7560
7561 state = new InflateState();
7562
7563 //if (state === Z_NULL) return Z_MEM_ERROR;
7564 //Tracev((stderr, "inflate: allocated\n"));
7565 strm.state = state;
7566 state.window = null/*Z_NULL*/;
7567 ret = inflateReset2(strm, windowBits);
7568 if (ret !== Z_OK) {
7569 strm.state = null/*Z_NULL*/;
7570 }
7571 return ret;
7572}
7573
7574function inflateInit(strm) {
7575 return inflateInit2(strm, DEF_WBITS);
7576}
7577
7578
7579/*
7580 Return state with length and distance decoding tables and index sizes set to
7581 fixed code decoding. Normally this returns fixed tables from inffixed.h.
7582 If BUILDFIXED is defined, then instead this routine builds the tables the
7583 first time it's called, and returns those tables the first time and
7584 thereafter. This reduces the size of the code by about 2K bytes, in
7585 exchange for a little execution time. However, BUILDFIXED should not be
7586 used for threaded applications, since the rewriting of the tables and virgin
7587 may not be thread-safe.
7588 */
7589var virgin = true;
7590
7591var lenfix, distfix; // We have no pointers in JS, so keep tables separate
7592
7593function fixedtables(state) {
7594 /* build fixed huffman tables if first call (may not be thread safe) */
7595 if (virgin) {
7596 var sym;
7597
7598 lenfix = new utils.Buf32(512);
7599 distfix = new utils.Buf32(32);
7600
7601 /* literal/length table */
7602 sym = 0;
7603 while (sym < 144) { state.lens[sym++] = 8; }
7604 while (sym < 256) { state.lens[sym++] = 9; }
7605 while (sym < 280) { state.lens[sym++] = 7; }
7606 while (sym < 288) { state.lens[sym++] = 8; }
7607
7608 inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
7609
7610 /* distance table */
7611 sym = 0;
7612 while (sym < 32) { state.lens[sym++] = 5; }
7613
7614 inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
7615
7616 /* do this just once */
7617 virgin = false;
7618 }
7619
7620 state.lencode = lenfix;
7621 state.lenbits = 9;
7622 state.distcode = distfix;
7623 state.distbits = 5;
7624}
7625
7626
7627/*
7628 Update the window with the last wsize (normally 32K) bytes written before
7629 returning. If window does not exist yet, create it. This is only called
7630 when a window is already in use, or when output has been written during this
7631 inflate call, but the end of the deflate stream has not been reached yet.
7632 It is also called to create a window for dictionary data when a dictionary
7633 is loaded.
7634
7635 Providing output buffers larger than 32K to inflate() should provide a speed
7636 advantage, since only the last 32K of output is copied to the sliding window
7637 upon return from inflate(), and since all distances after the first 32K of
7638 output will fall in the output data, making match copies simpler and faster.
7639 The advantage may be dependent on the size of the processor's data caches.
7640 */
7641function updatewindow(strm, src, end, copy) {
7642 var dist;
7643 var state = strm.state;
7644
7645 /* if it hasn't been done already, allocate space for the window */
7646 if (state.window === null) {
7647 state.wsize = 1 << state.wbits;
7648 state.wnext = 0;
7649 state.whave = 0;
7650
7651 state.window = new utils.Buf8(state.wsize);
7652 }
7653
7654 /* copy state->wsize or less output bytes into the circular window */
7655 if (copy >= state.wsize) {
7656 utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
7657 state.wnext = 0;
7658 state.whave = state.wsize;
7659 }
7660 else {
7661 dist = state.wsize - state.wnext;
7662 if (dist > copy) {
7663 dist = copy;
7664 }
7665 //zmemcpy(state->window + state->wnext, end - copy, dist);
7666 utils.arraySet(state.window, src, end - copy, dist, state.wnext);
7667 copy -= dist;
7668 if (copy) {
7669 //zmemcpy(state->window, end - copy, copy);
7670 utils.arraySet(state.window, src, end - copy, copy, 0);
7671 state.wnext = copy;
7672 state.whave = state.wsize;
7673 }
7674 else {
7675 state.wnext += dist;
7676 if (state.wnext === state.wsize) { state.wnext = 0; }
7677 if (state.whave < state.wsize) { state.whave += dist; }
7678 }
7679 }
7680 return 0;
7681}
7682
7683function inflate(strm, flush) {
7684 var state;
7685 var input, output; // input/output buffers
7686 var next; /* next input INDEX */
7687 var put; /* next output INDEX */
7688 var have, left; /* available input and output */
7689 var hold; /* bit buffer */
7690 var bits; /* bits in bit buffer */
7691 var _in, _out; /* save starting available input and output */
7692 var copy; /* number of stored or match bytes to copy */
7693 var from; /* where to copy match bytes from */
7694 var from_source;
7695 var here = 0; /* current decoding table entry */
7696 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
7697 //var last; /* parent table entry */
7698 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
7699 var len; /* length to copy for repeats, bits to drop */
7700 var ret; /* return code */
7701 var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
7702 var opts;
7703
7704 var n; // temporary var for NEED_BITS
7705
7706 var order = /* permutation of code lengths */
7707 [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
7708
7709
7710 if (!strm || !strm.state || !strm.output ||
7711 (!strm.input && strm.avail_in !== 0)) {
7712 return Z_STREAM_ERROR;
7713 }
7714
7715 state = strm.state;
7716 if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
7717
7718
7719 //--- LOAD() ---
7720 put = strm.next_out;
7721 output = strm.output;
7722 left = strm.avail_out;
7723 next = strm.next_in;
7724 input = strm.input;
7725 have = strm.avail_in;
7726 hold = state.hold;
7727 bits = state.bits;
7728 //---
7729
7730 _in = have;
7731 _out = left;
7732 ret = Z_OK;
7733
7734 inf_leave: // goto emulation
7735 for (;;) {
7736 switch (state.mode) {
7737 case HEAD:
7738 if (state.wrap === 0) {
7739 state.mode = TYPEDO;
7740 break;
7741 }
7742 //=== NEEDBITS(16);
7743 while (bits < 16) {
7744 if (have === 0) { break inf_leave; }
7745 have--;
7746 hold += input[next++] << bits;
7747 bits += 8;
7748 }
7749 //===//
7750 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
7751 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
7752 //=== CRC2(state.check, hold);
7753 hbuf[0] = hold & 0xff;
7754 hbuf[1] = (hold >>> 8) & 0xff;
7755 state.check = crc32(state.check, hbuf, 2, 0);
7756 //===//
7757
7758 //=== INITBITS();
7759 hold = 0;
7760 bits = 0;
7761 //===//
7762 state.mode = FLAGS;
7763 break;
7764 }
7765 state.flags = 0; /* expect zlib header */
7766 if (state.head) {
7767 state.head.done = false;
7768 }
7769 if (!(state.wrap & 1) || /* check if zlib header allowed */
7770 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
7771 strm.msg = 'incorrect header check';
7772 state.mode = BAD;
7773 break;
7774 }
7775 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
7776 strm.msg = 'unknown compression method';
7777 state.mode = BAD;
7778 break;
7779 }
7780 //--- DROPBITS(4) ---//
7781 hold >>>= 4;
7782 bits -= 4;
7783 //---//
7784 len = (hold & 0x0f)/*BITS(4)*/ + 8;
7785 if (state.wbits === 0) {
7786 state.wbits = len;
7787 }
7788 else if (len > state.wbits) {
7789 strm.msg = 'invalid window size';
7790 state.mode = BAD;
7791 break;
7792 }
7793 state.dmax = 1 << len;
7794 //Tracev((stderr, "inflate: zlib header ok\n"));
7795 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
7796 state.mode = hold & 0x200 ? DICTID : TYPE;
7797 //=== INITBITS();
7798 hold = 0;
7799 bits = 0;
7800 //===//
7801 break;
7802 case FLAGS:
7803 //=== NEEDBITS(16); */
7804 while (bits < 16) {
7805 if (have === 0) { break inf_leave; }
7806 have--;
7807 hold += input[next++] << bits;
7808 bits += 8;
7809 }
7810 //===//
7811 state.flags = hold;
7812 if ((state.flags & 0xff) !== Z_DEFLATED) {
7813 strm.msg = 'unknown compression method';
7814 state.mode = BAD;
7815 break;
7816 }
7817 if (state.flags & 0xe000) {
7818 strm.msg = 'unknown header flags set';
7819 state.mode = BAD;
7820 break;
7821 }
7822 if (state.head) {
7823 state.head.text = ((hold >> 8) & 1);
7824 }
7825 if (state.flags & 0x0200) {
7826 //=== CRC2(state.check, hold);
7827 hbuf[0] = hold & 0xff;
7828 hbuf[1] = (hold >>> 8) & 0xff;
7829 state.check = crc32(state.check, hbuf, 2, 0);
7830 //===//
7831 }
7832 //=== INITBITS();
7833 hold = 0;
7834 bits = 0;
7835 //===//
7836 state.mode = TIME;
7837 /* falls through */
7838 case TIME:
7839 //=== NEEDBITS(32); */
7840 while (bits < 32) {
7841 if (have === 0) { break inf_leave; }
7842 have--;
7843 hold += input[next++] << bits;
7844 bits += 8;
7845 }
7846 //===//
7847 if (state.head) {
7848 state.head.time = hold;
7849 }
7850 if (state.flags & 0x0200) {
7851 //=== CRC4(state.check, hold)
7852 hbuf[0] = hold & 0xff;
7853 hbuf[1] = (hold >>> 8) & 0xff;
7854 hbuf[2] = (hold >>> 16) & 0xff;
7855 hbuf[3] = (hold >>> 24) & 0xff;
7856 state.check = crc32(state.check, hbuf, 4, 0);
7857 //===
7858 }
7859 //=== INITBITS();
7860 hold = 0;
7861 bits = 0;
7862 //===//
7863 state.mode = OS;
7864 /* falls through */
7865 case OS:
7866 //=== NEEDBITS(16); */
7867 while (bits < 16) {
7868 if (have === 0) { break inf_leave; }
7869 have--;
7870 hold += input[next++] << bits;
7871 bits += 8;
7872 }
7873 //===//
7874 if (state.head) {
7875 state.head.xflags = (hold & 0xff);
7876 state.head.os = (hold >> 8);
7877 }
7878 if (state.flags & 0x0200) {
7879 //=== CRC2(state.check, hold);
7880 hbuf[0] = hold & 0xff;
7881 hbuf[1] = (hold >>> 8) & 0xff;
7882 state.check = crc32(state.check, hbuf, 2, 0);
7883 //===//
7884 }
7885 //=== INITBITS();
7886 hold = 0;
7887 bits = 0;
7888 //===//
7889 state.mode = EXLEN;
7890 /* falls through */
7891 case EXLEN:
7892 if (state.flags & 0x0400) {
7893 //=== NEEDBITS(16); */
7894 while (bits < 16) {
7895 if (have === 0) { break inf_leave; }
7896 have--;
7897 hold += input[next++] << bits;
7898 bits += 8;
7899 }
7900 //===//
7901 state.length = hold;
7902 if (state.head) {
7903 state.head.extra_len = hold;
7904 }
7905 if (state.flags & 0x0200) {
7906 //=== CRC2(state.check, hold);
7907 hbuf[0] = hold & 0xff;
7908 hbuf[1] = (hold >>> 8) & 0xff;
7909 state.check = crc32(state.check, hbuf, 2, 0);
7910 //===//
7911 }
7912 //=== INITBITS();
7913 hold = 0;
7914 bits = 0;
7915 //===//
7916 }
7917 else if (state.head) {
7918 state.head.extra = null/*Z_NULL*/;
7919 }
7920 state.mode = EXTRA;
7921 /* falls through */
7922 case EXTRA:
7923 if (state.flags & 0x0400) {
7924 copy = state.length;
7925 if (copy > have) { copy = have; }
7926 if (copy) {
7927 if (state.head) {
7928 len = state.head.extra_len - state.length;
7929 if (!state.head.extra) {
7930 // Use untyped array for more convenient processing later
7931 state.head.extra = new Array(state.head.extra_len);
7932 }
7933 utils.arraySet(
7934 state.head.extra,
7935 input,
7936 next,
7937 // extra field is limited to 65536 bytes
7938 // - no need for additional size check
7939 copy,
7940 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
7941 len
7942 );
7943 //zmemcpy(state.head.extra + len, next,
7944 // len + copy > state.head.extra_max ?
7945 // state.head.extra_max - len : copy);
7946 }
7947 if (state.flags & 0x0200) {
7948 state.check = crc32(state.check, input, copy, next);
7949 }
7950 have -= copy;
7951 next += copy;
7952 state.length -= copy;
7953 }
7954 if (state.length) { break inf_leave; }
7955 }
7956 state.length = 0;
7957 state.mode = NAME;
7958 /* falls through */
7959 case NAME:
7960 if (state.flags & 0x0800) {
7961 if (have === 0) { break inf_leave; }
7962 copy = 0;
7963 do {
7964 // TODO: 2 or 1 bytes?
7965 len = input[next + copy++];
7966 /* use constant limit because in js we should not preallocate memory */
7967 if (state.head && len &&
7968 (state.length < 65536 /*state.head.name_max*/)) {
7969 state.head.name += String.fromCharCode(len);
7970 }
7971 } while (len && copy < have);
7972
7973 if (state.flags & 0x0200) {
7974 state.check = crc32(state.check, input, copy, next);
7975 }
7976 have -= copy;
7977 next += copy;
7978 if (len) { break inf_leave; }
7979 }
7980 else if (state.head) {
7981 state.head.name = null;
7982 }
7983 state.length = 0;
7984 state.mode = COMMENT;
7985 /* falls through */
7986 case COMMENT:
7987 if (state.flags & 0x1000) {
7988 if (have === 0) { break inf_leave; }
7989 copy = 0;
7990 do {
7991 len = input[next + copy++];
7992 /* use constant limit because in js we should not preallocate memory */
7993 if (state.head && len &&
7994 (state.length < 65536 /*state.head.comm_max*/)) {
7995 state.head.comment += String.fromCharCode(len);
7996 }
7997 } while (len && copy < have);
7998 if (state.flags & 0x0200) {
7999 state.check = crc32(state.check, input, copy, next);
8000 }
8001 have -= copy;
8002 next += copy;
8003 if (len) { break inf_leave; }
8004 }
8005 else if (state.head) {
8006 state.head.comment = null;
8007 }
8008 state.mode = HCRC;
8009 /* falls through */
8010 case HCRC:
8011 if (state.flags & 0x0200) {
8012 //=== NEEDBITS(16); */
8013 while (bits < 16) {
8014 if (have === 0) { break inf_leave; }
8015 have--;
8016 hold += input[next++] << bits;
8017 bits += 8;
8018 }
8019 //===//
8020 if (hold !== (state.check & 0xffff)) {
8021 strm.msg = 'header crc mismatch';
8022 state.mode = BAD;
8023 break;
8024 }
8025 //=== INITBITS();
8026 hold = 0;
8027 bits = 0;
8028 //===//
8029 }
8030 if (state.head) {
8031 state.head.hcrc = ((state.flags >> 9) & 1);
8032 state.head.done = true;
8033 }
8034 strm.adler = state.check = 0;
8035 state.mode = TYPE;
8036 break;
8037 case DICTID:
8038 //=== NEEDBITS(32); */
8039 while (bits < 32) {
8040 if (have === 0) { break inf_leave; }
8041 have--;
8042 hold += input[next++] << bits;
8043 bits += 8;
8044 }
8045 //===//
8046 strm.adler = state.check = zswap32(hold);
8047 //=== INITBITS();
8048 hold = 0;
8049 bits = 0;
8050 //===//
8051 state.mode = DICT;
8052 /* falls through */
8053 case DICT:
8054 if (state.havedict === 0) {
8055 //--- RESTORE() ---
8056 strm.next_out = put;
8057 strm.avail_out = left;
8058 strm.next_in = next;
8059 strm.avail_in = have;
8060 state.hold = hold;
8061 state.bits = bits;
8062 //---
8063 return Z_NEED_DICT;
8064 }
8065 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
8066 state.mode = TYPE;
8067 /* falls through */
8068 case TYPE:
8069 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
8070 /* falls through */
8071 case TYPEDO:
8072 if (state.last) {
8073 //--- BYTEBITS() ---//
8074 hold >>>= bits & 7;
8075 bits -= bits & 7;
8076 //---//
8077 state.mode = CHECK;
8078 break;
8079 }
8080 //=== NEEDBITS(3); */
8081 while (bits < 3) {
8082 if (have === 0) { break inf_leave; }
8083 have--;
8084 hold += input[next++] << bits;
8085 bits += 8;
8086 }
8087 //===//
8088 state.last = (hold & 0x01)/*BITS(1)*/;
8089 //--- DROPBITS(1) ---//
8090 hold >>>= 1;
8091 bits -= 1;
8092 //---//
8093
8094 switch ((hold & 0x03)/*BITS(2)*/) {
8095 case 0: /* stored block */
8096 //Tracev((stderr, "inflate: stored block%s\n",
8097 // state.last ? " (last)" : ""));
8098 state.mode = STORED;
8099 break;
8100 case 1: /* fixed block */
8101 fixedtables(state);
8102 //Tracev((stderr, "inflate: fixed codes block%s\n",
8103 // state.last ? " (last)" : ""));
8104 state.mode = LEN_; /* decode codes */
8105 if (flush === Z_TREES) {
8106 //--- DROPBITS(2) ---//
8107 hold >>>= 2;
8108 bits -= 2;
8109 //---//
8110 break inf_leave;
8111 }
8112 break;
8113 case 2: /* dynamic block */
8114 //Tracev((stderr, "inflate: dynamic codes block%s\n",
8115 // state.last ? " (last)" : ""));
8116 state.mode = TABLE;
8117 break;
8118 case 3:
8119 strm.msg = 'invalid block type';
8120 state.mode = BAD;
8121 }
8122 //--- DROPBITS(2) ---//
8123 hold >>>= 2;
8124 bits -= 2;
8125 //---//
8126 break;
8127 case STORED:
8128 //--- BYTEBITS() ---// /* go to byte boundary */
8129 hold >>>= bits & 7;
8130 bits -= bits & 7;
8131 //---//
8132 //=== NEEDBITS(32); */
8133 while (bits < 32) {
8134 if (have === 0) { break inf_leave; }
8135 have--;
8136 hold += input[next++] << bits;
8137 bits += 8;
8138 }
8139 //===//
8140 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
8141 strm.msg = 'invalid stored block lengths';
8142 state.mode = BAD;
8143 break;
8144 }
8145 state.length = hold & 0xffff;
8146 //Tracev((stderr, "inflate: stored length %u\n",
8147 // state.length));
8148 //=== INITBITS();
8149 hold = 0;
8150 bits = 0;
8151 //===//
8152 state.mode = COPY_;
8153 if (flush === Z_TREES) { break inf_leave; }
8154 /* falls through */
8155 case COPY_:
8156 state.mode = COPY;
8157 /* falls through */
8158 case COPY:
8159 copy = state.length;
8160 if (copy) {
8161 if (copy > have) { copy = have; }
8162 if (copy > left) { copy = left; }
8163 if (copy === 0) { break inf_leave; }
8164 //--- zmemcpy(put, next, copy); ---
8165 utils.arraySet(output, input, next, copy, put);
8166 //---//
8167 have -= copy;
8168 next += copy;
8169 left -= copy;
8170 put += copy;
8171 state.length -= copy;
8172 break;
8173 }
8174 //Tracev((stderr, "inflate: stored end\n"));
8175 state.mode = TYPE;
8176 break;
8177 case TABLE:
8178 //=== NEEDBITS(14); */
8179 while (bits < 14) {
8180 if (have === 0) { break inf_leave; }
8181 have--;
8182 hold += input[next++] << bits;
8183 bits += 8;
8184 }
8185 //===//
8186 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
8187 //--- DROPBITS(5) ---//
8188 hold >>>= 5;
8189 bits -= 5;
8190 //---//
8191 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
8192 //--- DROPBITS(5) ---//
8193 hold >>>= 5;
8194 bits -= 5;
8195 //---//
8196 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
8197 //--- DROPBITS(4) ---//
8198 hold >>>= 4;
8199 bits -= 4;
8200 //---//
8201//#ifndef PKZIP_BUG_WORKAROUND
8202 if (state.nlen > 286 || state.ndist > 30) {
8203 strm.msg = 'too many length or distance symbols';
8204 state.mode = BAD;
8205 break;
8206 }
8207//#endif
8208 //Tracev((stderr, "inflate: table sizes ok\n"));
8209 state.have = 0;
8210 state.mode = LENLENS;
8211 /* falls through */
8212 case LENLENS:
8213 while (state.have < state.ncode) {
8214 //=== NEEDBITS(3);
8215 while (bits < 3) {
8216 if (have === 0) { break inf_leave; }
8217 have--;
8218 hold += input[next++] << bits;
8219 bits += 8;
8220 }
8221 //===//
8222 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
8223 //--- DROPBITS(3) ---//
8224 hold >>>= 3;
8225 bits -= 3;
8226 //---//
8227 }
8228 while (state.have < 19) {
8229 state.lens[order[state.have++]] = 0;
8230 }
8231 // We have separate tables & no pointers. 2 commented lines below not needed.
8232 //state.next = state.codes;
8233 //state.lencode = state.next;
8234 // Switch to use dynamic table
8235 state.lencode = state.lendyn;
8236 state.lenbits = 7;
8237
8238 opts = { bits: state.lenbits };
8239 ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
8240 state.lenbits = opts.bits;
8241
8242 if (ret) {
8243 strm.msg = 'invalid code lengths set';
8244 state.mode = BAD;
8245 break;
8246 }
8247 //Tracev((stderr, "inflate: code lengths ok\n"));
8248 state.have = 0;
8249 state.mode = CODELENS;
8250 /* falls through */
8251 case CODELENS:
8252 while (state.have < state.nlen + state.ndist) {
8253 for (;;) {
8254 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
8255 here_bits = here >>> 24;
8256 here_op = (here >>> 16) & 0xff;
8257 here_val = here & 0xffff;
8258
8259 if ((here_bits) <= bits) { break; }
8260 //--- PULLBYTE() ---//
8261 if (have === 0) { break inf_leave; }
8262 have--;
8263 hold += input[next++] << bits;
8264 bits += 8;
8265 //---//
8266 }
8267 if (here_val < 16) {
8268 //--- DROPBITS(here.bits) ---//
8269 hold >>>= here_bits;
8270 bits -= here_bits;
8271 //---//
8272 state.lens[state.have++] = here_val;
8273 }
8274 else {
8275 if (here_val === 16) {
8276 //=== NEEDBITS(here.bits + 2);
8277 n = here_bits + 2;
8278 while (bits < n) {
8279 if (have === 0) { break inf_leave; }
8280 have--;
8281 hold += input[next++] << bits;
8282 bits += 8;
8283 }
8284 //===//
8285 //--- DROPBITS(here.bits) ---//
8286 hold >>>= here_bits;
8287 bits -= here_bits;
8288 //---//
8289 if (state.have === 0) {
8290 strm.msg = 'invalid bit length repeat';
8291 state.mode = BAD;
8292 break;
8293 }
8294 len = state.lens[state.have - 1];
8295 copy = 3 + (hold & 0x03);//BITS(2);
8296 //--- DROPBITS(2) ---//
8297 hold >>>= 2;
8298 bits -= 2;
8299 //---//
8300 }
8301 else if (here_val === 17) {
8302 //=== NEEDBITS(here.bits + 3);
8303 n = here_bits + 3;
8304 while (bits < n) {
8305 if (have === 0) { break inf_leave; }
8306 have--;
8307 hold += input[next++] << bits;
8308 bits += 8;
8309 }
8310 //===//
8311 //--- DROPBITS(here.bits) ---//
8312 hold >>>= here_bits;
8313 bits -= here_bits;
8314 //---//
8315 len = 0;
8316 copy = 3 + (hold & 0x07);//BITS(3);
8317 //--- DROPBITS(3) ---//
8318 hold >>>= 3;
8319 bits -= 3;
8320 //---//
8321 }
8322 else {
8323 //=== NEEDBITS(here.bits + 7);
8324 n = here_bits + 7;
8325 while (bits < n) {
8326 if (have === 0) { break inf_leave; }
8327 have--;
8328 hold += input[next++] << bits;
8329 bits += 8;
8330 }
8331 //===//
8332 //--- DROPBITS(here.bits) ---//
8333 hold >>>= here_bits;
8334 bits -= here_bits;
8335 //---//
8336 len = 0;
8337 copy = 11 + (hold & 0x7f);//BITS(7);
8338 //--- DROPBITS(7) ---//
8339 hold >>>= 7;
8340 bits -= 7;
8341 //---//
8342 }
8343 if (state.have + copy > state.nlen + state.ndist) {
8344 strm.msg = 'invalid bit length repeat';
8345 state.mode = BAD;
8346 break;
8347 }
8348 while (copy--) {
8349 state.lens[state.have++] = len;
8350 }
8351 }
8352 }
8353
8354 /* handle error breaks in while */
8355 if (state.mode === BAD) { break; }
8356
8357 /* check for end-of-block code (better have one) */
8358 if (state.lens[256] === 0) {
8359 strm.msg = 'invalid code -- missing end-of-block';
8360 state.mode = BAD;
8361 break;
8362 }
8363
8364 /* build code tables -- note: do not change the lenbits or distbits
8365 values here (9 and 6) without reading the comments in inftrees.h
8366 concerning the ENOUGH constants, which depend on those values */
8367 state.lenbits = 9;
8368
8369 opts = { bits: state.lenbits };
8370 ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
8371 // We have separate tables & no pointers. 2 commented lines below not needed.
8372 // state.next_index = opts.table_index;
8373 state.lenbits = opts.bits;
8374 // state.lencode = state.next;
8375
8376 if (ret) {
8377 strm.msg = 'invalid literal/lengths set';
8378 state.mode = BAD;
8379 break;
8380 }
8381
8382 state.distbits = 6;
8383 //state.distcode.copy(state.codes);
8384 // Switch to use dynamic table
8385 state.distcode = state.distdyn;
8386 opts = { bits: state.distbits };
8387 ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
8388 // We have separate tables & no pointers. 2 commented lines below not needed.
8389 // state.next_index = opts.table_index;
8390 state.distbits = opts.bits;
8391 // state.distcode = state.next;
8392
8393 if (ret) {
8394 strm.msg = 'invalid distances set';
8395 state.mode = BAD;
8396 break;
8397 }
8398 //Tracev((stderr, 'inflate: codes ok\n'));
8399 state.mode = LEN_;
8400 if (flush === Z_TREES) { break inf_leave; }
8401 /* falls through */
8402 case LEN_:
8403 state.mode = LEN;
8404 /* falls through */
8405 case LEN:
8406 if (have >= 6 && left >= 258) {
8407 //--- RESTORE() ---
8408 strm.next_out = put;
8409 strm.avail_out = left;
8410 strm.next_in = next;
8411 strm.avail_in = have;
8412 state.hold = hold;
8413 state.bits = bits;
8414 //---
8415 inflate_fast(strm, _out);
8416 //--- LOAD() ---
8417 put = strm.next_out;
8418 output = strm.output;
8419 left = strm.avail_out;
8420 next = strm.next_in;
8421 input = strm.input;
8422 have = strm.avail_in;
8423 hold = state.hold;
8424 bits = state.bits;
8425 //---
8426
8427 if (state.mode === TYPE) {
8428 state.back = -1;
8429 }
8430 break;
8431 }
8432 state.back = 0;
8433 for (;;) {
8434 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
8435 here_bits = here >>> 24;
8436 here_op = (here >>> 16) & 0xff;
8437 here_val = here & 0xffff;
8438
8439 if (here_bits <= bits) { break; }
8440 //--- PULLBYTE() ---//
8441 if (have === 0) { break inf_leave; }
8442 have--;
8443 hold += input[next++] << bits;
8444 bits += 8;
8445 //---//
8446 }
8447 if (here_op && (here_op & 0xf0) === 0) {
8448 last_bits = here_bits;
8449 last_op = here_op;
8450 last_val = here_val;
8451 for (;;) {
8452 here = state.lencode[last_val +
8453 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
8454 here_bits = here >>> 24;
8455 here_op = (here >>> 16) & 0xff;
8456 here_val = here & 0xffff;
8457
8458 if ((last_bits + here_bits) <= bits) { break; }
8459 //--- PULLBYTE() ---//
8460 if (have === 0) { break inf_leave; }
8461 have--;
8462 hold += input[next++] << bits;
8463 bits += 8;
8464 //---//
8465 }
8466 //--- DROPBITS(last.bits) ---//
8467 hold >>>= last_bits;
8468 bits -= last_bits;
8469 //---//
8470 state.back += last_bits;
8471 }
8472 //--- DROPBITS(here.bits) ---//
8473 hold >>>= here_bits;
8474 bits -= here_bits;
8475 //---//
8476 state.back += here_bits;
8477 state.length = here_val;
8478 if (here_op === 0) {
8479 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
8480 // "inflate: literal '%c'\n" :
8481 // "inflate: literal 0x%02x\n", here.val));
8482 state.mode = LIT;
8483 break;
8484 }
8485 if (here_op & 32) {
8486 //Tracevv((stderr, "inflate: end of block\n"));
8487 state.back = -1;
8488 state.mode = TYPE;
8489 break;
8490 }
8491 if (here_op & 64) {
8492 strm.msg = 'invalid literal/length code';
8493 state.mode = BAD;
8494 break;
8495 }
8496 state.extra = here_op & 15;
8497 state.mode = LENEXT;
8498 /* falls through */
8499 case LENEXT:
8500 if (state.extra) {
8501 //=== NEEDBITS(state.extra);
8502 n = state.extra;
8503 while (bits < n) {
8504 if (have === 0) { break inf_leave; }
8505 have--;
8506 hold += input[next++] << bits;
8507 bits += 8;
8508 }
8509 //===//
8510 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
8511 //--- DROPBITS(state.extra) ---//
8512 hold >>>= state.extra;
8513 bits -= state.extra;
8514 //---//
8515 state.back += state.extra;
8516 }
8517 //Tracevv((stderr, "inflate: length %u\n", state.length));
8518 state.was = state.length;
8519 state.mode = DIST;
8520 /* falls through */
8521 case DIST:
8522 for (;;) {
8523 here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
8524 here_bits = here >>> 24;
8525 here_op = (here >>> 16) & 0xff;
8526 here_val = here & 0xffff;
8527
8528 if ((here_bits) <= bits) { break; }
8529 //--- PULLBYTE() ---//
8530 if (have === 0) { break inf_leave; }
8531 have--;
8532 hold += input[next++] << bits;
8533 bits += 8;
8534 //---//
8535 }
8536 if ((here_op & 0xf0) === 0) {
8537 last_bits = here_bits;
8538 last_op = here_op;
8539 last_val = here_val;
8540 for (;;) {
8541 here = state.distcode[last_val +
8542 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
8543 here_bits = here >>> 24;
8544 here_op = (here >>> 16) & 0xff;
8545 here_val = here & 0xffff;
8546
8547 if ((last_bits + here_bits) <= bits) { break; }
8548 //--- PULLBYTE() ---//
8549 if (have === 0) { break inf_leave; }
8550 have--;
8551 hold += input[next++] << bits;
8552 bits += 8;
8553 //---//
8554 }
8555 //--- DROPBITS(last.bits) ---//
8556 hold >>>= last_bits;
8557 bits -= last_bits;
8558 //---//
8559 state.back += last_bits;
8560 }
8561 //--- DROPBITS(here.bits) ---//
8562 hold >>>= here_bits;
8563 bits -= here_bits;
8564 //---//
8565 state.back += here_bits;
8566 if (here_op & 64) {
8567 strm.msg = 'invalid distance code';
8568 state.mode = BAD;
8569 break;
8570 }
8571 state.offset = here_val;
8572 state.extra = (here_op) & 15;
8573 state.mode = DISTEXT;
8574 /* falls through */
8575 case DISTEXT:
8576 if (state.extra) {
8577 //=== NEEDBITS(state.extra);
8578 n = state.extra;
8579 while (bits < n) {
8580 if (have === 0) { break inf_leave; }
8581 have--;
8582 hold += input[next++] << bits;
8583 bits += 8;
8584 }
8585 //===//
8586 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
8587 //--- DROPBITS(state.extra) ---//
8588 hold >>>= state.extra;
8589 bits -= state.extra;
8590 //---//
8591 state.back += state.extra;
8592 }
8593//#ifdef INFLATE_STRICT
8594 if (state.offset > state.dmax) {
8595 strm.msg = 'invalid distance too far back';
8596 state.mode = BAD;
8597 break;
8598 }
8599//#endif
8600 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
8601 state.mode = MATCH;
8602 /* falls through */
8603 case MATCH:
8604 if (left === 0) { break inf_leave; }
8605 copy = _out - left;
8606 if (state.offset > copy) { /* copy from window */
8607 copy = state.offset - copy;
8608 if (copy > state.whave) {
8609 if (state.sane) {
8610 strm.msg = 'invalid distance too far back';
8611 state.mode = BAD;
8612 break;
8613 }
8614// (!) This block is disabled in zlib defaults,
8615// don't enable it for binary compatibility
8616//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
8617// Trace((stderr, "inflate.c too far\n"));
8618// copy -= state.whave;
8619// if (copy > state.length) { copy = state.length; }
8620// if (copy > left) { copy = left; }
8621// left -= copy;
8622// state.length -= copy;
8623// do {
8624// output[put++] = 0;
8625// } while (--copy);
8626// if (state.length === 0) { state.mode = LEN; }
8627// break;
8628//#endif
8629 }
8630 if (copy > state.wnext) {
8631 copy -= state.wnext;
8632 from = state.wsize - copy;
8633 }
8634 else {
8635 from = state.wnext - copy;
8636 }
8637 if (copy > state.length) { copy = state.length; }
8638 from_source = state.window;
8639 }
8640 else { /* copy from output */
8641 from_source = output;
8642 from = put - state.offset;
8643 copy = state.length;
8644 }
8645 if (copy > left) { copy = left; }
8646 left -= copy;
8647 state.length -= copy;
8648 do {
8649 output[put++] = from_source[from++];
8650 } while (--copy);
8651 if (state.length === 0) { state.mode = LEN; }
8652 break;
8653 case LIT:
8654 if (left === 0) { break inf_leave; }
8655 output[put++] = state.length;
8656 left--;
8657 state.mode = LEN;
8658 break;
8659 case CHECK:
8660 if (state.wrap) {
8661 //=== NEEDBITS(32);
8662 while (bits < 32) {
8663 if (have === 0) { break inf_leave; }
8664 have--;
8665 // Use '|' instead of '+' to make sure that result is signed
8666 hold |= input[next++] << bits;
8667 bits += 8;
8668 }
8669 //===//
8670 _out -= left;
8671 strm.total_out += _out;
8672 state.total += _out;
8673 if (_out) {
8674 strm.adler = state.check =
8675 /*UPDATE(state.check, put - _out, _out);*/
8676 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
8677
8678 }
8679 _out = left;
8680 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
8681 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
8682 strm.msg = 'incorrect data check';
8683 state.mode = BAD;
8684 break;
8685 }
8686 //=== INITBITS();
8687 hold = 0;
8688 bits = 0;
8689 //===//
8690 //Tracev((stderr, "inflate: check matches trailer\n"));
8691 }
8692 state.mode = LENGTH;
8693 /* falls through */
8694 case LENGTH:
8695 if (state.wrap && state.flags) {
8696 //=== NEEDBITS(32);
8697 while (bits < 32) {
8698 if (have === 0) { break inf_leave; }
8699 have--;
8700 hold += input[next++] << bits;
8701 bits += 8;
8702 }
8703 //===//
8704 if (hold !== (state.total & 0xffffffff)) {
8705 strm.msg = 'incorrect length check';
8706 state.mode = BAD;
8707 break;
8708 }
8709 //=== INITBITS();
8710 hold = 0;
8711 bits = 0;
8712 //===//
8713 //Tracev((stderr, "inflate: length matches trailer\n"));
8714 }
8715 state.mode = DONE;
8716 /* falls through */
8717 case DONE:
8718 ret = Z_STREAM_END;
8719 break inf_leave;
8720 case BAD:
8721 ret = Z_DATA_ERROR;
8722 break inf_leave;
8723 case MEM:
8724 return Z_MEM_ERROR;
8725 case SYNC:
8726 /* falls through */
8727 default:
8728 return Z_STREAM_ERROR;
8729 }
8730 }
8731
8732 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
8733
8734 /*
8735 Return from inflate(), updating the total counts and the check value.
8736 If there was no progress during the inflate() call, return a buffer
8737 error. Call updatewindow() to create and/or update the window state.
8738 Note: a memory error from inflate() is non-recoverable.
8739 */
8740
8741 //--- RESTORE() ---
8742 strm.next_out = put;
8743 strm.avail_out = left;
8744 strm.next_in = next;
8745 strm.avail_in = have;
8746 state.hold = hold;
8747 state.bits = bits;
8748 //---
8749
8750 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
8751 (state.mode < CHECK || flush !== Z_FINISH))) {
8752 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
8753 state.mode = MEM;
8754 return Z_MEM_ERROR;
8755 }
8756 }
8757 _in -= strm.avail_in;
8758 _out -= strm.avail_out;
8759 strm.total_in += _in;
8760 strm.total_out += _out;
8761 state.total += _out;
8762 if (state.wrap && _out) {
8763 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
8764 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
8765 }
8766 strm.data_type = state.bits + (state.last ? 64 : 0) +
8767 (state.mode === TYPE ? 128 : 0) +
8768 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
8769 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
8770 ret = Z_BUF_ERROR;
8771 }
8772 return ret;
8773}
8774
8775function inflateEnd(strm) {
8776
8777 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
8778 return Z_STREAM_ERROR;
8779 }
8780
8781 var state = strm.state;
8782 if (state.window) {
8783 state.window = null;
8784 }
8785 strm.state = null;
8786 return Z_OK;
8787}
8788
8789function inflateGetHeader(strm, head) {
8790 var state;
8791
8792 /* check state */
8793 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8794 state = strm.state;
8795 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
8796
8797 /* save header structure */
8798 state.head = head;
8799 head.done = false;
8800 return Z_OK;
8801}
8802
8803function inflateSetDictionary(strm, dictionary) {
8804 var dictLength = dictionary.length;
8805
8806 var state;
8807 var dictid;
8808 var ret;
8809
8810 /* check state */
8811 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
8812 state = strm.state;
8813
8814 if (state.wrap !== 0 && state.mode !== DICT) {
8815 return Z_STREAM_ERROR;
8816 }
8817
8818 /* check for correct dictionary identifier */
8819 if (state.mode === DICT) {
8820 dictid = 1; /* adler32(0, null, 0)*/
8821 /* dictid = adler32(dictid, dictionary, dictLength); */
8822 dictid = adler32(dictid, dictionary, dictLength, 0);
8823 if (dictid !== state.check) {
8824 return Z_DATA_ERROR;
8825 }
8826 }
8827 /* copy dictionary to window using updatewindow(), which will amend the
8828 existing dictionary if appropriate */
8829 ret = updatewindow(strm, dictionary, dictLength, dictLength);
8830 if (ret) {
8831 state.mode = MEM;
8832 return Z_MEM_ERROR;
8833 }
8834 state.havedict = 1;
8835 // Tracev((stderr, "inflate: dictionary set\n"));
8836 return Z_OK;
8837}
8838
8839exports.inflateReset = inflateReset;
8840exports.inflateReset2 = inflateReset2;
8841exports.inflateResetKeep = inflateResetKeep;
8842exports.inflateInit = inflateInit;
8843exports.inflateInit2 = inflateInit2;
8844exports.inflate = inflate;
8845exports.inflateEnd = inflateEnd;
8846exports.inflateGetHeader = inflateGetHeader;
8847exports.inflateSetDictionary = inflateSetDictionary;
8848exports.inflateInfo = 'pako inflate (from Nodeca project)';
8849
8850/* Not implemented
8851exports.inflateCopy = inflateCopy;
8852exports.inflateGetDictionary = inflateGetDictionary;
8853exports.inflateMark = inflateMark;
8854exports.inflatePrime = inflatePrime;
8855exports.inflateSync = inflateSync;
8856exports.inflateSyncPoint = inflateSyncPoint;
8857exports.inflateUndermine = inflateUndermine;
8858*/
8859
8860},{"../utils/common":16,"./adler32":17,"./crc32":19,"./inffast":21,"./inftrees":23}],23:[function(require,module,exports){
8861'use strict';
8862
8863// (C) 1995-2013 Jean-loup Gailly and Mark Adler
8864// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
8865//
8866// This software is provided 'as-is', without any express or implied
8867// warranty. In no event will the authors be held liable for any damages
8868// arising from the use of this software.
8869//
8870// Permission is granted to anyone to use this software for any purpose,
8871// including commercial applications, and to alter it and redistribute it
8872// freely, subject to the following restrictions:
8873//
8874// 1. The origin of this software must not be misrepresented; you must not
8875// claim that you wrote the original software. If you use this software
8876// in a product, an acknowledgment in the product documentation would be
8877// appreciated but is not required.
8878// 2. Altered source versions must be plainly marked as such, and must not be
8879// misrepresented as being the original software.
8880// 3. This notice may not be removed or altered from any source distribution.
8881
8882var utils = require('../utils/common');
8883
8884var MAXBITS = 15;
8885var ENOUGH_LENS = 852;
8886var ENOUGH_DISTS = 592;
8887//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
8888
8889var CODES = 0;
8890var LENS = 1;
8891var DISTS = 2;
8892
8893var lbase = [ /* Length codes 257..285 base */
8894 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
8895 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
8896];
8897
8898var lext = [ /* Length codes 257..285 extra */
8899 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
8900 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
8901];
8902
8903var dbase = [ /* Distance codes 0..29 base */
8904 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
8905 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8906 8193, 12289, 16385, 24577, 0, 0
8907];
8908
8909var dext = [ /* Distance codes 0..29 extra */
8910 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
8911 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
8912 28, 28, 29, 29, 64, 64
8913];
8914
8915module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
8916{
8917 var bits = opts.bits;
8918 //here = opts.here; /* table entry for duplication */
8919
8920 var len = 0; /* a code's length in bits */
8921 var sym = 0; /* index of code symbols */
8922 var min = 0, max = 0; /* minimum and maximum code lengths */
8923 var root = 0; /* number of index bits for root table */
8924 var curr = 0; /* number of index bits for current table */
8925 var drop = 0; /* code bits to drop for sub-table */
8926 var left = 0; /* number of prefix codes available */
8927 var used = 0; /* code entries in table used */
8928 var huff = 0; /* Huffman code */
8929 var incr; /* for incrementing code, index */
8930 var fill; /* index for replicating entries */
8931 var low; /* low bits for current root entry */
8932 var mask; /* mask for low root bits */
8933 var next; /* next available space in table */
8934 var base = null; /* base value table to use */
8935 var base_index = 0;
8936// var shoextra; /* extra bits table to use */
8937 var end; /* use base and extra for symbol > end */
8938 var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
8939 var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
8940 var extra = null;
8941 var extra_index = 0;
8942
8943 var here_bits, here_op, here_val;
8944
8945 /*
8946 Process a set of code lengths to create a canonical Huffman code. The
8947 code lengths are lens[0..codes-1]. Each length corresponds to the
8948 symbols 0..codes-1. The Huffman code is generated by first sorting the
8949 symbols by length from short to long, and retaining the symbol order
8950 for codes with equal lengths. Then the code starts with all zero bits
8951 for the first code of the shortest length, and the codes are integer
8952 increments for the same length, and zeros are appended as the length
8953 increases. For the deflate format, these bits are stored backwards
8954 from their more natural integer increment ordering, and so when the
8955 decoding tables are built in the large loop below, the integer codes
8956 are incremented backwards.
8957
8958 This routine assumes, but does not check, that all of the entries in
8959 lens[] are in the range 0..MAXBITS. The caller must assure this.
8960 1..MAXBITS is interpreted as that code length. zero means that that
8961 symbol does not occur in this code.
8962
8963 The codes are sorted by computing a count of codes for each length,
8964 creating from that a table of starting indices for each length in the
8965 sorted table, and then entering the symbols in order in the sorted
8966 table. The sorted table is work[], with that space being provided by
8967 the caller.
8968
8969 The length counts are used for other purposes as well, i.e. finding
8970 the minimum and maximum length codes, determining if there are any
8971 codes at all, checking for a valid set of lengths, and looking ahead
8972 at length counts to determine sub-table sizes when building the
8973 decoding tables.
8974 */
8975
8976 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
8977 for (len = 0; len <= MAXBITS; len++) {
8978 count[len] = 0;
8979 }
8980 for (sym = 0; sym < codes; sym++) {
8981 count[lens[lens_index + sym]]++;
8982 }
8983
8984 /* bound code lengths, force root to be within code lengths */
8985 root = bits;
8986 for (max = MAXBITS; max >= 1; max--) {
8987 if (count[max] !== 0) { break; }
8988 }
8989 if (root > max) {
8990 root = max;
8991 }
8992 if (max === 0) { /* no symbols to code at all */
8993 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
8994 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
8995 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
8996 table[table_index++] = (1 << 24) | (64 << 16) | 0;
8997
8998
8999 //table.op[opts.table_index] = 64;
9000 //table.bits[opts.table_index] = 1;
9001 //table.val[opts.table_index++] = 0;
9002 table[table_index++] = (1 << 24) | (64 << 16) | 0;
9003
9004 opts.bits = 1;
9005 return 0; /* no symbols, but wait for decoding to report error */
9006 }
9007 for (min = 1; min < max; min++) {
9008 if (count[min] !== 0) { break; }
9009 }
9010 if (root < min) {
9011 root = min;
9012 }
9013
9014 /* check for an over-subscribed or incomplete set of lengths */
9015 left = 1;
9016 for (len = 1; len <= MAXBITS; len++) {
9017 left <<= 1;
9018 left -= count[len];
9019 if (left < 0) {
9020 return -1;
9021 } /* over-subscribed */
9022 }
9023 if (left > 0 && (type === CODES || max !== 1)) {
9024 return -1; /* incomplete set */
9025 }
9026
9027 /* generate offsets into symbol table for each length for sorting */
9028 offs[1] = 0;
9029 for (len = 1; len < MAXBITS; len++) {
9030 offs[len + 1] = offs[len] + count[len];
9031 }
9032
9033 /* sort symbols by length, by symbol order within each length */
9034 for (sym = 0; sym < codes; sym++) {
9035 if (lens[lens_index + sym] !== 0) {
9036 work[offs[lens[lens_index + sym]]++] = sym;
9037 }
9038 }
9039
9040 /*
9041 Create and fill in decoding tables. In this loop, the table being
9042 filled is at next and has curr index bits. The code being used is huff
9043 with length len. That code is converted to an index by dropping drop
9044 bits off of the bottom. For codes where len is less than drop + curr,
9045 those top drop + curr - len bits are incremented through all values to
9046 fill the table with replicated entries.
9047
9048 root is the number of index bits for the root table. When len exceeds
9049 root, sub-tables are created pointed to by the root entry with an index
9050 of the low root bits of huff. This is saved in low to check for when a
9051 new sub-table should be started. drop is zero when the root table is
9052 being filled, and drop is root when sub-tables are being filled.
9053
9054 When a new sub-table is needed, it is necessary to look ahead in the
9055 code lengths to determine what size sub-table is needed. The length
9056 counts are used for this, and so count[] is decremented as codes are
9057 entered in the tables.
9058
9059 used keeps track of how many table entries have been allocated from the
9060 provided *table space. It is checked for LENS and DIST tables against
9061 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
9062 the initial root table size constants. See the comments in inftrees.h
9063 for more information.
9064
9065 sym increments through all symbols, and the loop terminates when
9066 all codes of length max, i.e. all codes, have been processed. This
9067 routine permits incomplete codes, so another loop after this one fills
9068 in the rest of the decoding tables with invalid code markers.
9069 */
9070
9071 /* set up for code type */
9072 // poor man optimization - use if-else instead of switch,
9073 // to avoid deopts in old v8
9074 if (type === CODES) {
9075 base = extra = work; /* dummy value--not used */
9076 end = 19;
9077
9078 } else if (type === LENS) {
9079 base = lbase;
9080 base_index -= 257;
9081 extra = lext;
9082 extra_index -= 257;
9083 end = 256;
9084
9085 } else { /* DISTS */
9086 base = dbase;
9087 extra = dext;
9088 end = -1;
9089 }
9090
9091 /* initialize opts for loop */
9092 huff = 0; /* starting code */
9093 sym = 0; /* starting code symbol */
9094 len = min; /* starting code length */
9095 next = table_index; /* current table to fill in */
9096 curr = root; /* current table index bits */
9097 drop = 0; /* current bits to drop from code for index */
9098 low = -1; /* trigger new sub-table when len > root */
9099 used = 1 << root; /* use root table entries */
9100 mask = used - 1; /* mask for comparing low */
9101
9102 /* check available table space */
9103 if ((type === LENS && used > ENOUGH_LENS) ||
9104 (type === DISTS && used > ENOUGH_DISTS)) {
9105 return 1;
9106 }
9107
9108 /* process all codes and make table entries */
9109 for (;;) {
9110 /* create table entry */
9111 here_bits = len - drop;
9112 if (work[sym] < end) {
9113 here_op = 0;
9114 here_val = work[sym];
9115 }
9116 else if (work[sym] > end) {
9117 here_op = extra[extra_index + work[sym]];
9118 here_val = base[base_index + work[sym]];
9119 }
9120 else {
9121 here_op = 32 + 64; /* end of block */
9122 here_val = 0;
9123 }
9124
9125 /* replicate for those indices with low len bits equal to huff */
9126 incr = 1 << (len - drop);
9127 fill = 1 << curr;
9128 min = fill; /* save offset to next table */
9129 do {
9130 fill -= incr;
9131 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
9132 } while (fill !== 0);
9133
9134 /* backwards increment the len-bit code huff */
9135 incr = 1 << (len - 1);
9136 while (huff & incr) {
9137 incr >>= 1;
9138 }
9139 if (incr !== 0) {
9140 huff &= incr - 1;
9141 huff += incr;
9142 } else {
9143 huff = 0;
9144 }
9145
9146 /* go to next symbol, update count, len */
9147 sym++;
9148 if (--count[len] === 0) {
9149 if (len === max) { break; }
9150 len = lens[lens_index + work[sym]];
9151 }
9152
9153 /* create new sub-table if needed */
9154 if (len > root && (huff & mask) !== low) {
9155 /* if first time, transition to sub-tables */
9156 if (drop === 0) {
9157 drop = root;
9158 }
9159
9160 /* increment past last table */
9161 next += min; /* here min is 1 << curr */
9162
9163 /* determine length of next table */
9164 curr = len - drop;
9165 left = 1 << curr;
9166 while (curr + drop < max) {
9167 left -= count[curr + drop];
9168 if (left <= 0) { break; }
9169 curr++;
9170 left <<= 1;
9171 }
9172
9173 /* check for enough space */
9174 used += 1 << curr;
9175 if ((type === LENS && used > ENOUGH_LENS) ||
9176 (type === DISTS && used > ENOUGH_DISTS)) {
9177 return 1;
9178 }
9179
9180 /* point entry in root table to sub-table */
9181 low = huff & mask;
9182 /*table.op[low] = curr;
9183 table.bits[low] = root;
9184 table.val[low] = next - opts.table_index;*/
9185 table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
9186 }
9187 }
9188
9189 /* fill in remaining table entry if code is incomplete (guaranteed to have
9190 at most one remaining entry, since if the code is incomplete, the
9191 maximum code length that was allowed to get this far is one bit) */
9192 if (huff !== 0) {
9193 //table.op[next + huff] = 64; /* invalid code marker */
9194 //table.bits[next + huff] = len - drop;
9195 //table.val[next + huff] = 0;
9196 table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
9197 }
9198
9199 /* set return parameters */
9200 //opts.table_index += used;
9201 opts.bits = root;
9202 return 0;
9203};
9204
9205},{"../utils/common":16}],24:[function(require,module,exports){
9206'use strict';
9207
9208// (C) 1995-2013 Jean-loup Gailly and Mark Adler
9209// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
9210//
9211// This software is provided 'as-is', without any express or implied
9212// warranty. In no event will the authors be held liable for any damages
9213// arising from the use of this software.
9214//
9215// Permission is granted to anyone to use this software for any purpose,
9216// including commercial applications, and to alter it and redistribute it
9217// freely, subject to the following restrictions:
9218//
9219// 1. The origin of this software must not be misrepresented; you must not
9220// claim that you wrote the original software. If you use this software
9221// in a product, an acknowledgment in the product documentation would be
9222// appreciated but is not required.
9223// 2. Altered source versions must be plainly marked as such, and must not be
9224// misrepresented as being the original software.
9225// 3. This notice may not be removed or altered from any source distribution.
9226
9227module.exports = {
9228 2: 'need dictionary', /* Z_NEED_DICT 2 */
9229 1: 'stream end', /* Z_STREAM_END 1 */
9230 0: '', /* Z_OK 0 */
9231 '-1': 'file error', /* Z_ERRNO (-1) */
9232 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
9233 '-3': 'data error', /* Z_DATA_ERROR (-3) */
9234 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
9235 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
9236 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
9237};
9238
9239},{}],25:[function(require,module,exports){
9240'use strict';
9241
9242// (C) 1995-2013 Jean-loup Gailly and Mark Adler
9243// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
9244//
9245// This software is provided 'as-is', without any express or implied
9246// warranty. In no event will the authors be held liable for any damages
9247// arising from the use of this software.
9248//
9249// Permission is granted to anyone to use this software for any purpose,
9250// including commercial applications, and to alter it and redistribute it
9251// freely, subject to the following restrictions:
9252//
9253// 1. The origin of this software must not be misrepresented; you must not
9254// claim that you wrote the original software. If you use this software
9255// in a product, an acknowledgment in the product documentation would be
9256// appreciated but is not required.
9257// 2. Altered source versions must be plainly marked as such, and must not be
9258// misrepresented as being the original software.
9259// 3. This notice may not be removed or altered from any source distribution.
9260
9261var utils = require('../utils/common');
9262
9263/* Public constants ==========================================================*/
9264/* ===========================================================================*/
9265
9266
9267//var Z_FILTERED = 1;
9268//var Z_HUFFMAN_ONLY = 2;
9269//var Z_RLE = 3;
9270var Z_FIXED = 4;
9271//var Z_DEFAULT_STRATEGY = 0;
9272
9273/* Possible values of the data_type field (though see inflate()) */
9274var Z_BINARY = 0;
9275var Z_TEXT = 1;
9276//var Z_ASCII = 1; // = Z_TEXT
9277var Z_UNKNOWN = 2;
9278
9279/*============================================================================*/
9280
9281
9282function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
9283
9284// From zutil.h
9285
9286var STORED_BLOCK = 0;
9287var STATIC_TREES = 1;
9288var DYN_TREES = 2;
9289/* The three kinds of block type */
9290
9291var MIN_MATCH = 3;
9292var MAX_MATCH = 258;
9293/* The minimum and maximum match lengths */
9294
9295// From deflate.h
9296/* ===========================================================================
9297 * Internal compression state.
9298 */
9299
9300var LENGTH_CODES = 29;
9301/* number of length codes, not counting the special END_BLOCK code */
9302
9303var LITERALS = 256;
9304/* number of literal bytes 0..255 */
9305
9306var L_CODES = LITERALS + 1 + LENGTH_CODES;
9307/* number of Literal or Length codes, including the END_BLOCK code */
9308
9309var D_CODES = 30;
9310/* number of distance codes */
9311
9312var BL_CODES = 19;
9313/* number of codes used to transfer the bit lengths */
9314
9315var HEAP_SIZE = 2 * L_CODES + 1;
9316/* maximum heap size */
9317
9318var MAX_BITS = 15;
9319/* All codes must not exceed MAX_BITS bits */
9320
9321var Buf_size = 16;
9322/* size of bit buffer in bi_buf */
9323
9324
9325/* ===========================================================================
9326 * Constants
9327 */
9328
9329var MAX_BL_BITS = 7;
9330/* Bit length codes must not exceed MAX_BL_BITS bits */
9331
9332var END_BLOCK = 256;
9333/* end of block literal code */
9334
9335var REP_3_6 = 16;
9336/* repeat previous bit length 3-6 times (2 bits of repeat count) */
9337
9338var REPZ_3_10 = 17;
9339/* repeat a zero length 3-10 times (3 bits of repeat count) */
9340
9341var REPZ_11_138 = 18;
9342/* repeat a zero length 11-138 times (7 bits of repeat count) */
9343
9344/* eslint-disable comma-spacing,array-bracket-spacing */
9345var extra_lbits = /* extra bits for each length code */
9346 [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
9347
9348var extra_dbits = /* extra bits for each distance code */
9349 [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
9350
9351var extra_blbits = /* extra bits for each bit length code */
9352 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
9353
9354var bl_order =
9355 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
9356/* eslint-enable comma-spacing,array-bracket-spacing */
9357
9358/* The lengths of the bit length codes are sent in order of decreasing
9359 * probability, to avoid transmitting the lengths for unused bit length codes.
9360 */
9361
9362/* ===========================================================================
9363 * Local data. These are initialized only once.
9364 */
9365
9366// We pre-fill arrays with 0 to avoid uninitialized gaps
9367
9368var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
9369
9370// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
9371var static_ltree = new Array((L_CODES + 2) * 2);
9372zero(static_ltree);
9373/* The static literal tree. Since the bit lengths are imposed, there is no
9374 * need for the L_CODES extra codes used during heap construction. However
9375 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
9376 * below).
9377 */
9378
9379var static_dtree = new Array(D_CODES * 2);
9380zero(static_dtree);
9381/* The static distance tree. (Actually a trivial tree since all codes use
9382 * 5 bits.)
9383 */
9384
9385var _dist_code = new Array(DIST_CODE_LEN);
9386zero(_dist_code);
9387/* Distance codes. The first 256 values correspond to the distances
9388 * 3 .. 258, the last 256 values correspond to the top 8 bits of
9389 * the 15 bit distances.
9390 */
9391
9392var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
9393zero(_length_code);
9394/* length code for each normalized match length (0 == MIN_MATCH) */
9395
9396var base_length = new Array(LENGTH_CODES);
9397zero(base_length);
9398/* First normalized length for each code (0 = MIN_MATCH) */
9399
9400var base_dist = new Array(D_CODES);
9401zero(base_dist);
9402/* First normalized distance for each code (0 = distance of 1) */
9403
9404
9405function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
9406
9407 this.static_tree = static_tree; /* static tree or NULL */
9408 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
9409 this.extra_base = extra_base; /* base index for extra_bits */
9410 this.elems = elems; /* max number of elements in the tree */
9411 this.max_length = max_length; /* max bit length for the codes */
9412
9413 // show if `static_tree` has data or dummy - needed for monomorphic objects
9414 this.has_stree = static_tree && static_tree.length;
9415}
9416
9417
9418var static_l_desc;
9419var static_d_desc;
9420var static_bl_desc;
9421
9422
9423function TreeDesc(dyn_tree, stat_desc) {
9424 this.dyn_tree = dyn_tree; /* the dynamic tree */
9425 this.max_code = 0; /* largest code with non zero frequency */
9426 this.stat_desc = stat_desc; /* the corresponding static tree */
9427}
9428
9429
9430
9431function d_code(dist) {
9432 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
9433}
9434
9435
9436/* ===========================================================================
9437 * Output a short LSB first on the stream.
9438 * IN assertion: there is enough room in pendingBuf.
9439 */
9440function put_short(s, w) {
9441// put_byte(s, (uch)((w) & 0xff));
9442// put_byte(s, (uch)((ush)(w) >> 8));
9443 s.pending_buf[s.pending++] = (w) & 0xff;
9444 s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
9445}
9446
9447
9448/* ===========================================================================
9449 * Send a value on a given number of bits.
9450 * IN assertion: length <= 16 and value fits in length bits.
9451 */
9452function send_bits(s, value, length) {
9453 if (s.bi_valid > (Buf_size - length)) {
9454 s.bi_buf |= (value << s.bi_valid) & 0xffff;
9455 put_short(s, s.bi_buf);
9456 s.bi_buf = value >> (Buf_size - s.bi_valid);
9457 s.bi_valid += length - Buf_size;
9458 } else {
9459 s.bi_buf |= (value << s.bi_valid) & 0xffff;
9460 s.bi_valid += length;
9461 }
9462}
9463
9464
9465function send_code(s, c, tree) {
9466 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
9467}
9468
9469
9470/* ===========================================================================
9471 * Reverse the first len bits of a code, using straightforward code (a faster
9472 * method would use a table)
9473 * IN assertion: 1 <= len <= 15
9474 */
9475function bi_reverse(code, len) {
9476 var res = 0;
9477 do {
9478 res |= code & 1;
9479 code >>>= 1;
9480 res <<= 1;
9481 } while (--len > 0);
9482 return res >>> 1;
9483}
9484
9485
9486/* ===========================================================================
9487 * Flush the bit buffer, keeping at most 7 bits in it.
9488 */
9489function bi_flush(s) {
9490 if (s.bi_valid === 16) {
9491 put_short(s, s.bi_buf);
9492 s.bi_buf = 0;
9493 s.bi_valid = 0;
9494
9495 } else if (s.bi_valid >= 8) {
9496 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
9497 s.bi_buf >>= 8;
9498 s.bi_valid -= 8;
9499 }
9500}
9501
9502
9503/* ===========================================================================
9504 * Compute the optimal bit lengths for a tree and update the total bit length
9505 * for the current block.
9506 * IN assertion: the fields freq and dad are set, heap[heap_max] and
9507 * above are the tree nodes sorted by increasing frequency.
9508 * OUT assertions: the field len is set to the optimal bit length, the
9509 * array bl_count contains the frequencies for each bit length.
9510 * The length opt_len is updated; static_len is also updated if stree is
9511 * not null.
9512 */
9513function gen_bitlen(s, desc)
9514// deflate_state *s;
9515// tree_desc *desc; /* the tree descriptor */
9516{
9517 var tree = desc.dyn_tree;
9518 var max_code = desc.max_code;
9519 var stree = desc.stat_desc.static_tree;
9520 var has_stree = desc.stat_desc.has_stree;
9521 var extra = desc.stat_desc.extra_bits;
9522 var base = desc.stat_desc.extra_base;
9523 var max_length = desc.stat_desc.max_length;
9524 var h; /* heap index */
9525 var n, m; /* iterate over the tree elements */
9526 var bits; /* bit length */
9527 var xbits; /* extra bits */
9528 var f; /* frequency */
9529 var overflow = 0; /* number of elements with bit length too large */
9530
9531 for (bits = 0; bits <= MAX_BITS; bits++) {
9532 s.bl_count[bits] = 0;
9533 }
9534
9535 /* In a first pass, compute the optimal bit lengths (which may
9536 * overflow in the case of the bit length tree).
9537 */
9538 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
9539
9540 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
9541 n = s.heap[h];
9542 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
9543 if (bits > max_length) {
9544 bits = max_length;
9545 overflow++;
9546 }
9547 tree[n * 2 + 1]/*.Len*/ = bits;
9548 /* We overwrite tree[n].Dad which is no longer needed */
9549
9550 if (n > max_code) { continue; } /* not a leaf node */
9551
9552 s.bl_count[bits]++;
9553 xbits = 0;
9554 if (n >= base) {
9555 xbits = extra[n - base];
9556 }
9557 f = tree[n * 2]/*.Freq*/;
9558 s.opt_len += f * (bits + xbits);
9559 if (has_stree) {
9560 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
9561 }
9562 }
9563 if (overflow === 0) { return; }
9564
9565 // Trace((stderr,"\nbit length overflow\n"));
9566 /* This happens for example on obj2 and pic of the Calgary corpus */
9567
9568 /* Find the first bit length which could increase: */
9569 do {
9570 bits = max_length - 1;
9571 while (s.bl_count[bits] === 0) { bits--; }
9572 s.bl_count[bits]--; /* move one leaf down the tree */
9573 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
9574 s.bl_count[max_length]--;
9575 /* The brother of the overflow item also moves one step up,
9576 * but this does not affect bl_count[max_length]
9577 */
9578 overflow -= 2;
9579 } while (overflow > 0);
9580
9581 /* Now recompute all bit lengths, scanning in increasing frequency.
9582 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
9583 * lengths instead of fixing only the wrong ones. This idea is taken
9584 * from 'ar' written by Haruhiko Okumura.)
9585 */
9586 for (bits = max_length; bits !== 0; bits--) {
9587 n = s.bl_count[bits];
9588 while (n !== 0) {
9589 m = s.heap[--h];
9590 if (m > max_code) { continue; }
9591 if (tree[m * 2 + 1]/*.Len*/ !== bits) {
9592 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
9593 s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
9594 tree[m * 2 + 1]/*.Len*/ = bits;
9595 }
9596 n--;
9597 }
9598 }
9599}
9600
9601
9602/* ===========================================================================
9603 * Generate the codes for a given tree and bit counts (which need not be
9604 * optimal).
9605 * IN assertion: the array bl_count contains the bit length statistics for
9606 * the given tree and the field len is set for all tree elements.
9607 * OUT assertion: the field code is set for all tree elements of non
9608 * zero code length.
9609 */
9610function gen_codes(tree, max_code, bl_count)
9611// ct_data *tree; /* the tree to decorate */
9612// int max_code; /* largest code with non zero frequency */
9613// ushf *bl_count; /* number of codes at each bit length */
9614{
9615 var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
9616 var code = 0; /* running code value */
9617 var bits; /* bit index */
9618 var n; /* code index */
9619
9620 /* The distribution counts are first used to generate the code values
9621 * without bit reversal.
9622 */
9623 for (bits = 1; bits <= MAX_BITS; bits++) {
9624 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
9625 }
9626 /* Check that the bit counts in bl_count are consistent. The last code
9627 * must be all ones.
9628 */
9629 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
9630 // "inconsistent bit counts");
9631 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
9632
9633 for (n = 0; n <= max_code; n++) {
9634 var len = tree[n * 2 + 1]/*.Len*/;
9635 if (len === 0) { continue; }
9636 /* Now reverse the bits */
9637 tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
9638
9639 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
9640 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
9641 }
9642}
9643
9644
9645/* ===========================================================================
9646 * Initialize the various 'constant' tables.
9647 */
9648function tr_static_init() {
9649 var n; /* iterates over tree elements */
9650 var bits; /* bit counter */
9651 var length; /* length value */
9652 var code; /* code value */
9653 var dist; /* distance index */
9654 var bl_count = new Array(MAX_BITS + 1);
9655 /* number of codes at each bit length for an optimal tree */
9656
9657 // do check in _tr_init()
9658 //if (static_init_done) return;
9659
9660 /* For some embedded targets, global variables are not initialized: */
9661/*#ifdef NO_INIT_GLOBAL_POINTERS
9662 static_l_desc.static_tree = static_ltree;
9663 static_l_desc.extra_bits = extra_lbits;
9664 static_d_desc.static_tree = static_dtree;
9665 static_d_desc.extra_bits = extra_dbits;
9666 static_bl_desc.extra_bits = extra_blbits;
9667#endif*/
9668
9669 /* Initialize the mapping length (0..255) -> length code (0..28) */
9670 length = 0;
9671 for (code = 0; code < LENGTH_CODES - 1; code++) {
9672 base_length[code] = length;
9673 for (n = 0; n < (1 << extra_lbits[code]); n++) {
9674 _length_code[length++] = code;
9675 }
9676 }
9677 //Assert (length == 256, "tr_static_init: length != 256");
9678 /* Note that the length 255 (match length 258) can be represented
9679 * in two different ways: code 284 + 5 bits or code 285, so we
9680 * overwrite length_code[255] to use the best encoding:
9681 */
9682 _length_code[length - 1] = code;
9683
9684 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
9685 dist = 0;
9686 for (code = 0; code < 16; code++) {
9687 base_dist[code] = dist;
9688 for (n = 0; n < (1 << extra_dbits[code]); n++) {
9689 _dist_code[dist++] = code;
9690 }
9691 }
9692 //Assert (dist == 256, "tr_static_init: dist != 256");
9693 dist >>= 7; /* from now on, all distances are divided by 128 */
9694 for (; code < D_CODES; code++) {
9695 base_dist[code] = dist << 7;
9696 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
9697 _dist_code[256 + dist++] = code;
9698 }
9699 }
9700 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
9701
9702 /* Construct the codes of the static literal tree */
9703 for (bits = 0; bits <= MAX_BITS; bits++) {
9704 bl_count[bits] = 0;
9705 }
9706
9707 n = 0;
9708 while (n <= 143) {
9709 static_ltree[n * 2 + 1]/*.Len*/ = 8;
9710 n++;
9711 bl_count[8]++;
9712 }
9713 while (n <= 255) {
9714 static_ltree[n * 2 + 1]/*.Len*/ = 9;
9715 n++;
9716 bl_count[9]++;
9717 }
9718 while (n <= 279) {
9719 static_ltree[n * 2 + 1]/*.Len*/ = 7;
9720 n++;
9721 bl_count[7]++;
9722 }
9723 while (n <= 287) {
9724 static_ltree[n * 2 + 1]/*.Len*/ = 8;
9725 n++;
9726 bl_count[8]++;
9727 }
9728 /* Codes 286 and 287 do not exist, but we must include them in the
9729 * tree construction to get a canonical Huffman tree (longest code
9730 * all ones)
9731 */
9732 gen_codes(static_ltree, L_CODES + 1, bl_count);
9733
9734 /* The static distance tree is trivial: */
9735 for (n = 0; n < D_CODES; n++) {
9736 static_dtree[n * 2 + 1]/*.Len*/ = 5;
9737 static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
9738 }
9739
9740 // Now data ready and we can init static trees
9741 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
9742 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
9743 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
9744
9745 //static_init_done = true;
9746}
9747
9748
9749/* ===========================================================================
9750 * Initialize a new block.
9751 */
9752function init_block(s) {
9753 var n; /* iterates over tree elements */
9754
9755 /* Initialize the trees. */
9756 for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
9757 for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
9758 for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
9759
9760 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
9761 s.opt_len = s.static_len = 0;
9762 s.last_lit = s.matches = 0;
9763}
9764
9765
9766/* ===========================================================================
9767 * Flush the bit buffer and align the output on a byte boundary
9768 */
9769function bi_windup(s)
9770{
9771 if (s.bi_valid > 8) {
9772 put_short(s, s.bi_buf);
9773 } else if (s.bi_valid > 0) {
9774 //put_byte(s, (Byte)s->bi_buf);
9775 s.pending_buf[s.pending++] = s.bi_buf;
9776 }
9777 s.bi_buf = 0;
9778 s.bi_valid = 0;
9779}
9780
9781/* ===========================================================================
9782 * Copy a stored block, storing first the length and its
9783 * one's complement if requested.
9784 */
9785function copy_block(s, buf, len, header)
9786//DeflateState *s;
9787//charf *buf; /* the input data */
9788//unsigned len; /* its length */
9789//int header; /* true if block header must be written */
9790{
9791 bi_windup(s); /* align on byte boundary */
9792
9793 if (header) {
9794 put_short(s, len);
9795 put_short(s, ~len);
9796 }
9797// while (len--) {
9798// put_byte(s, *buf++);
9799// }
9800 utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
9801 s.pending += len;
9802}
9803
9804/* ===========================================================================
9805 * Compares to subtrees, using the tree depth as tie breaker when
9806 * the subtrees have equal frequency. This minimizes the worst case length.
9807 */
9808function smaller(tree, n, m, depth) {
9809 var _n2 = n * 2;
9810 var _m2 = m * 2;
9811 return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
9812 (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
9813}
9814
9815/* ===========================================================================
9816 * Restore the heap property by moving down the tree starting at node k,
9817 * exchanging a node with the smallest of its two sons if necessary, stopping
9818 * when the heap property is re-established (each father smaller than its
9819 * two sons).
9820 */
9821function pqdownheap(s, tree, k)
9822// deflate_state *s;
9823// ct_data *tree; /* the tree to restore */
9824// int k; /* node to move down */
9825{
9826 var v = s.heap[k];
9827 var j = k << 1; /* left son of k */
9828 while (j <= s.heap_len) {
9829 /* Set j to the smallest of the two sons: */
9830 if (j < s.heap_len &&
9831 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
9832 j++;
9833 }
9834 /* Exit if v is smaller than both sons */
9835 if (smaller(tree, v, s.heap[j], s.depth)) { break; }
9836
9837 /* Exchange v with the smallest son */
9838 s.heap[k] = s.heap[j];
9839 k = j;
9840
9841 /* And continue down the tree, setting j to the left son of k */
9842 j <<= 1;
9843 }
9844 s.heap[k] = v;
9845}
9846
9847
9848// inlined manually
9849// var SMALLEST = 1;
9850
9851/* ===========================================================================
9852 * Send the block data compressed using the given Huffman trees
9853 */
9854function compress_block(s, ltree, dtree)
9855// deflate_state *s;
9856// const ct_data *ltree; /* literal tree */
9857// const ct_data *dtree; /* distance tree */
9858{
9859 var dist; /* distance of matched string */
9860 var lc; /* match length or unmatched char (if dist == 0) */
9861 var lx = 0; /* running index in l_buf */
9862 var code; /* the code to send */
9863 var extra; /* number of extra bits to send */
9864
9865 if (s.last_lit !== 0) {
9866 do {
9867 dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
9868 lc = s.pending_buf[s.l_buf + lx];
9869 lx++;
9870
9871 if (dist === 0) {
9872 send_code(s, lc, ltree); /* send a literal byte */
9873 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
9874 } else {
9875 /* Here, lc is the match length - MIN_MATCH */
9876 code = _length_code[lc];
9877 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
9878 extra = extra_lbits[code];
9879 if (extra !== 0) {
9880 lc -= base_length[code];
9881 send_bits(s, lc, extra); /* send the extra length bits */
9882 }
9883 dist--; /* dist is now the match distance - 1 */
9884 code = d_code(dist);
9885 //Assert (code < D_CODES, "bad d_code");
9886
9887 send_code(s, code, dtree); /* send the distance code */
9888 extra = extra_dbits[code];
9889 if (extra !== 0) {
9890 dist -= base_dist[code];
9891 send_bits(s, dist, extra); /* send the extra distance bits */
9892 }
9893 } /* literal or match pair ? */
9894
9895 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
9896 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
9897 // "pendingBuf overflow");
9898
9899 } while (lx < s.last_lit);
9900 }
9901
9902 send_code(s, END_BLOCK, ltree);
9903}
9904
9905
9906/* ===========================================================================
9907 * Construct one Huffman tree and assigns the code bit strings and lengths.
9908 * Update the total bit length for the current block.
9909 * IN assertion: the field freq is set for all tree elements.
9910 * OUT assertions: the fields len and code are set to the optimal bit length
9911 * and corresponding code. The length opt_len is updated; static_len is
9912 * also updated if stree is not null. The field max_code is set.
9913 */
9914function build_tree(s, desc)
9915// deflate_state *s;
9916// tree_desc *desc; /* the tree descriptor */
9917{
9918 var tree = desc.dyn_tree;
9919 var stree = desc.stat_desc.static_tree;
9920 var has_stree = desc.stat_desc.has_stree;
9921 var elems = desc.stat_desc.elems;
9922 var n, m; /* iterate over heap elements */
9923 var max_code = -1; /* largest code with non zero frequency */
9924 var node; /* new node being created */
9925
9926 /* Construct the initial heap, with least frequent element in
9927 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
9928 * heap[0] is not used.
9929 */
9930 s.heap_len = 0;
9931 s.heap_max = HEAP_SIZE;
9932
9933 for (n = 0; n < elems; n++) {
9934 if (tree[n * 2]/*.Freq*/ !== 0) {
9935 s.heap[++s.heap_len] = max_code = n;
9936 s.depth[n] = 0;
9937
9938 } else {
9939 tree[n * 2 + 1]/*.Len*/ = 0;
9940 }
9941 }
9942
9943 /* The pkzip format requires that at least one distance code exists,
9944 * and that at least one bit should be sent even if there is only one
9945 * possible code. So to avoid special checks later on we force at least
9946 * two codes of non zero frequency.
9947 */
9948 while (s.heap_len < 2) {
9949 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
9950 tree[node * 2]/*.Freq*/ = 1;
9951 s.depth[node] = 0;
9952 s.opt_len--;
9953
9954 if (has_stree) {
9955 s.static_len -= stree[node * 2 + 1]/*.Len*/;
9956 }
9957 /* node is 0 or 1 so it does not have extra bits */
9958 }
9959 desc.max_code = max_code;
9960
9961 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
9962 * establish sub-heaps of increasing lengths:
9963 */
9964 for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
9965
9966 /* Construct the Huffman tree by repeatedly combining the least two
9967 * frequent nodes.
9968 */
9969 node = elems; /* next internal node of the tree */
9970 do {
9971 //pqremove(s, tree, n); /* n = node of least frequency */
9972 /*** pqremove ***/
9973 n = s.heap[1/*SMALLEST*/];
9974 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
9975 pqdownheap(s, tree, 1/*SMALLEST*/);
9976 /***/
9977
9978 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
9979
9980 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
9981 s.heap[--s.heap_max] = m;
9982
9983 /* Create a new node father of n and m */
9984 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
9985 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
9986 tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
9987
9988 /* and insert the new node in the heap */
9989 s.heap[1/*SMALLEST*/] = node++;
9990 pqdownheap(s, tree, 1/*SMALLEST*/);
9991
9992 } while (s.heap_len >= 2);
9993
9994 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
9995
9996 /* At this point, the fields freq and dad are set. We can now
9997 * generate the bit lengths.
9998 */
9999 gen_bitlen(s, desc);
10000
10001 /* The field len is now set, we can generate the bit codes */
10002 gen_codes(tree, max_code, s.bl_count);
10003}
10004
10005
10006/* ===========================================================================
10007 * Scan a literal or distance tree to determine the frequencies of the codes
10008 * in the bit length tree.
10009 */
10010function scan_tree(s, tree, max_code)
10011// deflate_state *s;
10012// ct_data *tree; /* the tree to be scanned */
10013// int max_code; /* and its largest code of non zero frequency */
10014{
10015 var n; /* iterates over all tree elements */
10016 var prevlen = -1; /* last emitted length */
10017 var curlen; /* length of current code */
10018
10019 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
10020
10021 var count = 0; /* repeat count of the current code */
10022 var max_count = 7; /* max repeat count */
10023 var min_count = 4; /* min repeat count */
10024
10025 if (nextlen === 0) {
10026 max_count = 138;
10027 min_count = 3;
10028 }
10029 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
10030
10031 for (n = 0; n <= max_code; n++) {
10032 curlen = nextlen;
10033 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
10034
10035 if (++count < max_count && curlen === nextlen) {
10036 continue;
10037
10038 } else if (count < min_count) {
10039 s.bl_tree[curlen * 2]/*.Freq*/ += count;
10040
10041 } else if (curlen !== 0) {
10042
10043 if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
10044 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
10045
10046 } else if (count <= 10) {
10047 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
10048
10049 } else {
10050 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
10051 }
10052
10053 count = 0;
10054 prevlen = curlen;
10055
10056 if (nextlen === 0) {
10057 max_count = 138;
10058 min_count = 3;
10059
10060 } else if (curlen === nextlen) {
10061 max_count = 6;
10062 min_count = 3;
10063
10064 } else {
10065 max_count = 7;
10066 min_count = 4;
10067 }
10068 }
10069}
10070
10071
10072/* ===========================================================================
10073 * Send a literal or distance tree in compressed form, using the codes in
10074 * bl_tree.
10075 */
10076function send_tree(s, tree, max_code)
10077// deflate_state *s;
10078// ct_data *tree; /* the tree to be scanned */
10079// int max_code; /* and its largest code of non zero frequency */
10080{
10081 var n; /* iterates over all tree elements */
10082 var prevlen = -1; /* last emitted length */
10083 var curlen; /* length of current code */
10084
10085 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
10086
10087 var count = 0; /* repeat count of the current code */
10088 var max_count = 7; /* max repeat count */
10089 var min_count = 4; /* min repeat count */
10090
10091 /* tree[max_code+1].Len = -1; */ /* guard already set */
10092 if (nextlen === 0) {
10093 max_count = 138;
10094 min_count = 3;
10095 }
10096
10097 for (n = 0; n <= max_code; n++) {
10098 curlen = nextlen;
10099 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
10100
10101 if (++count < max_count && curlen === nextlen) {
10102 continue;
10103
10104 } else if (count < min_count) {
10105 do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
10106
10107 } else if (curlen !== 0) {
10108 if (curlen !== prevlen) {
10109 send_code(s, curlen, s.bl_tree);
10110 count--;
10111 }
10112 //Assert(count >= 3 && count <= 6, " 3_6?");
10113 send_code(s, REP_3_6, s.bl_tree);
10114 send_bits(s, count - 3, 2);
10115
10116 } else if (count <= 10) {
10117 send_code(s, REPZ_3_10, s.bl_tree);
10118 send_bits(s, count - 3, 3);
10119
10120 } else {
10121 send_code(s, REPZ_11_138, s.bl_tree);
10122 send_bits(s, count - 11, 7);
10123 }
10124
10125 count = 0;
10126 prevlen = curlen;
10127 if (nextlen === 0) {
10128 max_count = 138;
10129 min_count = 3;
10130
10131 } else if (curlen === nextlen) {
10132 max_count = 6;
10133 min_count = 3;
10134
10135 } else {
10136 max_count = 7;
10137 min_count = 4;
10138 }
10139 }
10140}
10141
10142
10143/* ===========================================================================
10144 * Construct the Huffman tree for the bit lengths and return the index in
10145 * bl_order of the last bit length code to send.
10146 */
10147function build_bl_tree(s) {
10148 var max_blindex; /* index of last bit length code of non zero freq */
10149
10150 /* Determine the bit length frequencies for literal and distance trees */
10151 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
10152 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
10153
10154 /* Build the bit length tree: */
10155 build_tree(s, s.bl_desc);
10156 /* opt_len now includes the length of the tree representations, except
10157 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
10158 */
10159
10160 /* Determine the number of bit length codes to send. The pkzip format
10161 * requires that at least 4 bit length codes be sent. (appnote.txt says
10162 * 3 but the actual value used is 4.)
10163 */
10164 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
10165 if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
10166 break;
10167 }
10168 }
10169 /* Update opt_len to include the bit length tree and counts */
10170 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
10171 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
10172 // s->opt_len, s->static_len));
10173
10174 return max_blindex;
10175}
10176
10177
10178/* ===========================================================================
10179 * Send the header for a block using dynamic Huffman trees: the counts, the
10180 * lengths of the bit length codes, the literal tree and the distance tree.
10181 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
10182 */
10183function send_all_trees(s, lcodes, dcodes, blcodes)
10184// deflate_state *s;
10185// int lcodes, dcodes, blcodes; /* number of codes for each tree */
10186{
10187 var rank; /* index in bl_order */
10188
10189 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
10190 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
10191 // "too many codes");
10192 //Tracev((stderr, "\nbl counts: "));
10193 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
10194 send_bits(s, dcodes - 1, 5);
10195 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
10196 for (rank = 0; rank < blcodes; rank++) {
10197 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
10198 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
10199 }
10200 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
10201
10202 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
10203 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
10204
10205 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
10206 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
10207}
10208
10209
10210/* ===========================================================================
10211 * Check if the data type is TEXT or BINARY, using the following algorithm:
10212 * - TEXT if the two conditions below are satisfied:
10213 * a) There are no non-portable control characters belonging to the
10214 * "black list" (0..6, 14..25, 28..31).
10215 * b) There is at least one printable character belonging to the
10216 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
10217 * - BINARY otherwise.
10218 * - The following partially-portable control characters form a
10219 * "gray list" that is ignored in this detection algorithm:
10220 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
10221 * IN assertion: the fields Freq of dyn_ltree are set.
10222 */
10223function detect_data_type(s) {
10224 /* black_mask is the bit mask of black-listed bytes
10225 * set bits 0..6, 14..25, and 28..31
10226 * 0xf3ffc07f = binary 11110011111111111100000001111111
10227 */
10228 var black_mask = 0xf3ffc07f;
10229 var n;
10230
10231 /* Check for non-textual ("black-listed") bytes. */
10232 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
10233 if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
10234 return Z_BINARY;
10235 }
10236 }
10237
10238 /* Check for textual ("white-listed") bytes. */
10239 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
10240 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
10241 return Z_TEXT;
10242 }
10243 for (n = 32; n < LITERALS; n++) {
10244 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
10245 return Z_TEXT;
10246 }
10247 }
10248
10249 /* There are no "black-listed" or "white-listed" bytes:
10250 * this stream either is empty or has tolerated ("gray-listed") bytes only.
10251 */
10252 return Z_BINARY;
10253}
10254
10255
10256var static_init_done = false;
10257
10258/* ===========================================================================
10259 * Initialize the tree data structures for a new zlib stream.
10260 */
10261function _tr_init(s)
10262{
10263
10264 if (!static_init_done) {
10265 tr_static_init();
10266 static_init_done = true;
10267 }
10268
10269 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
10270 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
10271 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
10272
10273 s.bi_buf = 0;
10274 s.bi_valid = 0;
10275
10276 /* Initialize the first block of the first file: */
10277 init_block(s);
10278}
10279
10280
10281/* ===========================================================================
10282 * Send a stored block
10283 */
10284function _tr_stored_block(s, buf, stored_len, last)
10285//DeflateState *s;
10286//charf *buf; /* input block */
10287//ulg stored_len; /* length of input block */
10288//int last; /* one if this is the last block for a file */
10289{
10290 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
10291 copy_block(s, buf, stored_len, true); /* with header */
10292}
10293
10294
10295/* ===========================================================================
10296 * Send one empty static block to give enough lookahead for inflate.
10297 * This takes 10 bits, of which 7 may remain in the bit buffer.
10298 */
10299function _tr_align(s) {
10300 send_bits(s, STATIC_TREES << 1, 3);
10301 send_code(s, END_BLOCK, static_ltree);
10302 bi_flush(s);
10303}
10304
10305
10306/* ===========================================================================
10307 * Determine the best encoding for the current block: dynamic trees, static
10308 * trees or store, and output the encoded block to the zip file.
10309 */
10310function _tr_flush_block(s, buf, stored_len, last)
10311//DeflateState *s;
10312//charf *buf; /* input block, or NULL if too old */
10313//ulg stored_len; /* length of input block */
10314//int last; /* one if this is the last block for a file */
10315{
10316 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
10317 var max_blindex = 0; /* index of last bit length code of non zero freq */
10318
10319 /* Build the Huffman trees unless a stored block is forced */
10320 if (s.level > 0) {
10321
10322 /* Check if the file is binary or text */
10323 if (s.strm.data_type === Z_UNKNOWN) {
10324 s.strm.data_type = detect_data_type(s);
10325 }
10326
10327 /* Construct the literal and distance trees */
10328 build_tree(s, s.l_desc);
10329 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
10330 // s->static_len));
10331
10332 build_tree(s, s.d_desc);
10333 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
10334 // s->static_len));
10335 /* At this point, opt_len and static_len are the total bit lengths of
10336 * the compressed block data, excluding the tree representations.
10337 */
10338
10339 /* Build the bit length tree for the above two trees, and get the index
10340 * in bl_order of the last bit length code to send.
10341 */
10342 max_blindex = build_bl_tree(s);
10343
10344 /* Determine the best encoding. Compute the block lengths in bytes. */
10345 opt_lenb = (s.opt_len + 3 + 7) >>> 3;
10346 static_lenb = (s.static_len + 3 + 7) >>> 3;
10347
10348 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
10349 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
10350 // s->last_lit));
10351
10352 if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
10353
10354 } else {
10355 // Assert(buf != (char*)0, "lost buf");
10356 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
10357 }
10358
10359 if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
10360 /* 4: two words for the lengths */
10361
10362 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
10363 * Otherwise we can't have processed more than WSIZE input bytes since
10364 * the last block flush, because compression would have been
10365 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
10366 * transform a block into a stored block.
10367 */
10368 _tr_stored_block(s, buf, stored_len, last);
10369
10370 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
10371
10372 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
10373 compress_block(s, static_ltree, static_dtree);
10374
10375 } else {
10376 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
10377 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
10378 compress_block(s, s.dyn_ltree, s.dyn_dtree);
10379 }
10380 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
10381 /* The above check is made mod 2^32, for files larger than 512 MB
10382 * and uLong implemented on 32 bits.
10383 */
10384 init_block(s);
10385
10386 if (last) {
10387 bi_windup(s);
10388 }
10389 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
10390 // s->compressed_len-7*last));
10391}
10392
10393/* ===========================================================================
10394 * Save the match info and tally the frequency counts. Return true if
10395 * the current block must be flushed.
10396 */
10397function _tr_tally(s, dist, lc)
10398// deflate_state *s;
10399// unsigned dist; /* distance of matched string */
10400// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
10401{
10402 //var out_length, in_length, dcode;
10403
10404 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
10405 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
10406
10407 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
10408 s.last_lit++;
10409
10410 if (dist === 0) {
10411 /* lc is the unmatched char */
10412 s.dyn_ltree[lc * 2]/*.Freq*/++;
10413 } else {
10414 s.matches++;
10415 /* Here, lc is the match length - MIN_MATCH */
10416 dist--; /* dist = match distance - 1 */
10417 //Assert((ush)dist < (ush)MAX_DIST(s) &&
10418 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
10419 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
10420
10421 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
10422 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
10423 }
10424
10425// (!) This block is disabled in zlib defaults,
10426// don't enable it for binary compatibility
10427
10428//#ifdef TRUNCATE_BLOCK
10429// /* Try to guess if it is profitable to stop the current block here */
10430// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
10431// /* Compute an upper bound for the compressed length */
10432// out_length = s.last_lit*8;
10433// in_length = s.strstart - s.block_start;
10434//
10435// for (dcode = 0; dcode < D_CODES; dcode++) {
10436// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
10437// }
10438// out_length >>>= 3;
10439// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
10440// // s->last_lit, in_length, out_length,
10441// // 100L - out_length*100L/in_length));
10442// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
10443// return true;
10444// }
10445// }
10446//#endif
10447
10448 return (s.last_lit === s.lit_bufsize - 1);
10449 /* We avoid equality with lit_bufsize because of wraparound at 64K
10450 * on 16 bit machines and because stored blocks are restricted to
10451 * 64K-1 bytes.
10452 */
10453}
10454
10455exports._tr_init = _tr_init;
10456exports._tr_stored_block = _tr_stored_block;
10457exports._tr_flush_block = _tr_flush_block;
10458exports._tr_tally = _tr_tally;
10459exports._tr_align = _tr_align;
10460
10461},{"../utils/common":16}],26:[function(require,module,exports){
10462'use strict';
10463
10464// (C) 1995-2013 Jean-loup Gailly and Mark Adler
10465// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
10466//
10467// This software is provided 'as-is', without any express or implied
10468// warranty. In no event will the authors be held liable for any damages
10469// arising from the use of this software.
10470//
10471// Permission is granted to anyone to use this software for any purpose,
10472// including commercial applications, and to alter it and redistribute it
10473// freely, subject to the following restrictions:
10474//
10475// 1. The origin of this software must not be misrepresented; you must not
10476// claim that you wrote the original software. If you use this software
10477// in a product, an acknowledgment in the product documentation would be
10478// appreciated but is not required.
10479// 2. Altered source versions must be plainly marked as such, and must not be
10480// misrepresented as being the original software.
10481// 3. This notice may not be removed or altered from any source distribution.
10482
10483function ZStream() {
10484 /* next input byte */
10485 this.input = null; // JS specific, because we have no pointers
10486 this.next_in = 0;
10487 /* number of bytes available at input */
10488 this.avail_in = 0;
10489 /* total number of input bytes read so far */
10490 this.total_in = 0;
10491 /* next output byte should be put there */
10492 this.output = null; // JS specific, because we have no pointers
10493 this.next_out = 0;
10494 /* remaining free space at output */
10495 this.avail_out = 0;
10496 /* total number of bytes output so far */
10497 this.total_out = 0;
10498 /* last error message, NULL if no error */
10499 this.msg = ''/*Z_NULL*/;
10500 /* not visible by applications */
10501 this.state = null;
10502 /* best guess about the data type: binary or text */
10503 this.data_type = 2/*Z_UNKNOWN*/;
10504 /* adler32 value of the uncompressed data */
10505 this.adler = 0;
10506}
10507
10508module.exports = ZStream;
10509
10510},{}],27:[function(require,module,exports){
10511(function (process){
10512'use strict';
10513
10514if (!process.version ||
10515 process.version.indexOf('v0.') === 0 ||
10516 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
10517 module.exports = { nextTick: nextTick };
10518} else {
10519 module.exports = process
10520}
10521
10522function nextTick(fn, arg1, arg2, arg3) {
10523 if (typeof fn !== 'function') {
10524 throw new TypeError('"callback" argument must be a function');
10525 }
10526 var len = arguments.length;
10527 var args, i;
10528 switch (len) {
10529 case 0:
10530 case 1:
10531 return process.nextTick(fn);
10532 case 2:
10533 return process.nextTick(function afterTickOne() {
10534 fn.call(null, arg1);
10535 });
10536 case 3:
10537 return process.nextTick(function afterTickTwo() {
10538 fn.call(null, arg1, arg2);
10539 });
10540 case 4:
10541 return process.nextTick(function afterTickThree() {
10542 fn.call(null, arg1, arg2, arg3);
10543 });
10544 default:
10545 args = new Array(len - 1);
10546 i = 0;
10547 while (i < args.length) {
10548 args[i++] = arguments[i];
10549 }
10550 return process.nextTick(function afterTick() {
10551 fn.apply(null, args);
10552 });
10553 }
10554}
10555
10556
10557}).call(this,require('_process'))
10558},{"_process":28}],28:[function(require,module,exports){
10559// shim for using process in browser
10560var process = module.exports = {};
10561
10562// cached from whatever global is present so that test runners that stub it
10563// don't break things. But we need to wrap it in a try catch in case it is
10564// wrapped in strict mode code which doesn't define any globals. It's inside a
10565// function because try/catches deoptimize in certain engines.
10566
10567var cachedSetTimeout;
10568var cachedClearTimeout;
10569
10570function defaultSetTimout() {
10571 throw new Error('setTimeout has not been defined');
10572}
10573function defaultClearTimeout () {
10574 throw new Error('clearTimeout has not been defined');
10575}
10576(function () {
10577 try {
10578 if (typeof setTimeout === 'function') {
10579 cachedSetTimeout = setTimeout;
10580 } else {
10581 cachedSetTimeout = defaultSetTimout;
10582 }
10583 } catch (e) {
10584 cachedSetTimeout = defaultSetTimout;
10585 }
10586 try {
10587 if (typeof clearTimeout === 'function') {
10588 cachedClearTimeout = clearTimeout;
10589 } else {
10590 cachedClearTimeout = defaultClearTimeout;
10591 }
10592 } catch (e) {
10593 cachedClearTimeout = defaultClearTimeout;
10594 }
10595} ())
10596function runTimeout(fun) {
10597 if (cachedSetTimeout === setTimeout) {
10598 //normal enviroments in sane situations
10599 return setTimeout(fun, 0);
10600 }
10601 // if setTimeout wasn't available but was latter defined
10602 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
10603 cachedSetTimeout = setTimeout;
10604 return setTimeout(fun, 0);
10605 }
10606 try {
10607 // when when somebody has screwed with setTimeout but no I.E. maddness
10608 return cachedSetTimeout(fun, 0);
10609 } catch(e){
10610 try {
10611 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10612 return cachedSetTimeout.call(null, fun, 0);
10613 } catch(e){
10614 // 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
10615 return cachedSetTimeout.call(this, fun, 0);
10616 }
10617 }
10618
10619
10620}
10621function runClearTimeout(marker) {
10622 if (cachedClearTimeout === clearTimeout) {
10623 //normal enviroments in sane situations
10624 return clearTimeout(marker);
10625 }
10626 // if clearTimeout wasn't available but was latter defined
10627 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
10628 cachedClearTimeout = clearTimeout;
10629 return clearTimeout(marker);
10630 }
10631 try {
10632 // when when somebody has screwed with setTimeout but no I.E. maddness
10633 return cachedClearTimeout(marker);
10634 } catch (e){
10635 try {
10636 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
10637 return cachedClearTimeout.call(null, marker);
10638 } catch (e){
10639 // 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.
10640 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
10641 return cachedClearTimeout.call(this, marker);
10642 }
10643 }
10644
10645
10646
10647}
10648var queue = [];
10649var draining = false;
10650var currentQueue;
10651var queueIndex = -1;
10652
10653function cleanUpNextTick() {
10654 if (!draining || !currentQueue) {
10655 return;
10656 }
10657 draining = false;
10658 if (currentQueue.length) {
10659 queue = currentQueue.concat(queue);
10660 } else {
10661 queueIndex = -1;
10662 }
10663 if (queue.length) {
10664 drainQueue();
10665 }
10666}
10667
10668function drainQueue() {
10669 if (draining) {
10670 return;
10671 }
10672 var timeout = runTimeout(cleanUpNextTick);
10673 draining = true;
10674
10675 var len = queue.length;
10676 while(len) {
10677 currentQueue = queue;
10678 queue = [];
10679 while (++queueIndex < len) {
10680 if (currentQueue) {
10681 currentQueue[queueIndex].run();
10682 }
10683 }
10684 queueIndex = -1;
10685 len = queue.length;
10686 }
10687 currentQueue = null;
10688 draining = false;
10689 runClearTimeout(timeout);
10690}
10691
10692process.nextTick = function (fun) {
10693 var args = new Array(arguments.length - 1);
10694 if (arguments.length > 1) {
10695 for (var i = 1; i < arguments.length; i++) {
10696 args[i - 1] = arguments[i];
10697 }
10698 }
10699 queue.push(new Item(fun, args));
10700 if (queue.length === 1 && !draining) {
10701 runTimeout(drainQueue);
10702 }
10703};
10704
10705// v8 likes predictible objects
10706function Item(fun, array) {
10707 this.fun = fun;
10708 this.array = array;
10709}
10710Item.prototype.run = function () {
10711 this.fun.apply(null, this.array);
10712};
10713process.title = 'browser';
10714process.browser = true;
10715process.env = {};
10716process.argv = [];
10717process.version = ''; // empty string to avoid regexp issues
10718process.versions = {};
10719
10720function noop() {}
10721
10722process.on = noop;
10723process.addListener = noop;
10724process.once = noop;
10725process.off = noop;
10726process.removeListener = noop;
10727process.removeAllListeners = noop;
10728process.emit = noop;
10729process.prependListener = noop;
10730process.prependOnceListener = noop;
10731
10732process.listeners = function (name) { return [] }
10733
10734process.binding = function (name) {
10735 throw new Error('process.binding is not supported');
10736};
10737
10738process.cwd = function () { return '/' };
10739process.chdir = function (dir) {
10740 throw new Error('process.chdir is not supported');
10741};
10742process.umask = function() { return 0; };
10743
10744},{}],29:[function(require,module,exports){
10745module.exports = require('./lib/_stream_duplex.js');
10746
10747},{"./lib/_stream_duplex.js":30}],30:[function(require,module,exports){
10748// Copyright Joyent, Inc. and other Node contributors.
10749//
10750// Permission is hereby granted, free of charge, to any person obtaining a
10751// copy of this software and associated documentation files (the
10752// "Software"), to deal in the Software without restriction, including
10753// without limitation the rights to use, copy, modify, merge, publish,
10754// distribute, sublicense, and/or sell copies of the Software, and to permit
10755// persons to whom the Software is furnished to do so, subject to the
10756// following conditions:
10757//
10758// The above copyright notice and this permission notice shall be included
10759// in all copies or substantial portions of the Software.
10760//
10761// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10762// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10763// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10764// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10765// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10766// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10767// USE OR OTHER DEALINGS IN THE SOFTWARE.
10768
10769// a duplex stream is just a stream that is both readable and writable.
10770// Since JS doesn't have multiple prototypal inheritance, this class
10771// prototypally inherits from Readable, and then parasitically from
10772// Writable.
10773
10774'use strict';
10775
10776/*<replacement>*/
10777
10778var pna = require('process-nextick-args');
10779/*</replacement>*/
10780
10781/*<replacement>*/
10782var objectKeys = Object.keys || function (obj) {
10783 var keys = [];
10784 for (var key in obj) {
10785 keys.push(key);
10786 }return keys;
10787};
10788/*</replacement>*/
10789
10790module.exports = Duplex;
10791
10792/*<replacement>*/
10793var util = require('core-util-is');
10794util.inherits = require('inherits');
10795/*</replacement>*/
10796
10797var Readable = require('./_stream_readable');
10798var Writable = require('./_stream_writable');
10799
10800util.inherits(Duplex, Readable);
10801
10802{
10803 // avoid scope creep, the keys array can then be collected
10804 var keys = objectKeys(Writable.prototype);
10805 for (var v = 0; v < keys.length; v++) {
10806 var method = keys[v];
10807 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
10808 }
10809}
10810
10811function Duplex(options) {
10812 if (!(this instanceof Duplex)) return new Duplex(options);
10813
10814 Readable.call(this, options);
10815 Writable.call(this, options);
10816
10817 if (options && options.readable === false) this.readable = false;
10818
10819 if (options && options.writable === false) this.writable = false;
10820
10821 this.allowHalfOpen = true;
10822 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
10823
10824 this.once('end', onend);
10825}
10826
10827Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
10828 // making it explicit this property is not enumerable
10829 // because otherwise some prototype manipulation in
10830 // userland will fail
10831 enumerable: false,
10832 get: function () {
10833 return this._writableState.highWaterMark;
10834 }
10835});
10836
10837// the no-half-open enforcer
10838function onend() {
10839 // if we allow half-open state, or if the writable side ended,
10840 // then we're ok.
10841 if (this.allowHalfOpen || this._writableState.ended) return;
10842
10843 // no more data can be written.
10844 // But allow more writes to happen in this tick.
10845 pna.nextTick(onEndNT, this);
10846}
10847
10848function onEndNT(self) {
10849 self.end();
10850}
10851
10852Object.defineProperty(Duplex.prototype, 'destroyed', {
10853 get: function () {
10854 if (this._readableState === undefined || this._writableState === undefined) {
10855 return false;
10856 }
10857 return this._readableState.destroyed && this._writableState.destroyed;
10858 },
10859 set: function (value) {
10860 // we ignore the value if the stream
10861 // has not been initialized yet
10862 if (this._readableState === undefined || this._writableState === undefined) {
10863 return;
10864 }
10865
10866 // backward compatibility, the user is explicitly
10867 // managing destroyed
10868 this._readableState.destroyed = value;
10869 this._writableState.destroyed = value;
10870 }
10871});
10872
10873Duplex.prototype._destroy = function (err, cb) {
10874 this.push(null);
10875 this.end();
10876
10877 pna.nextTick(cb, err);
10878};
10879},{"./_stream_readable":32,"./_stream_writable":34,"core-util-is":10,"inherits":13,"process-nextick-args":27}],31:[function(require,module,exports){
10880// Copyright Joyent, Inc. and other Node contributors.
10881//
10882// Permission is hereby granted, free of charge, to any person obtaining a
10883// copy of this software and associated documentation files (the
10884// "Software"), to deal in the Software without restriction, including
10885// without limitation the rights to use, copy, modify, merge, publish,
10886// distribute, sublicense, and/or sell copies of the Software, and to permit
10887// persons to whom the Software is furnished to do so, subject to the
10888// following conditions:
10889//
10890// The above copyright notice and this permission notice shall be included
10891// in all copies or substantial portions of the Software.
10892//
10893// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10894// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10895// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10896// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10897// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10898// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10899// USE OR OTHER DEALINGS IN THE SOFTWARE.
10900
10901// a passthrough stream.
10902// basically just the most minimal sort of Transform stream.
10903// Every written chunk gets output as-is.
10904
10905'use strict';
10906
10907module.exports = PassThrough;
10908
10909var Transform = require('./_stream_transform');
10910
10911/*<replacement>*/
10912var util = require('core-util-is');
10913util.inherits = require('inherits');
10914/*</replacement>*/
10915
10916util.inherits(PassThrough, Transform);
10917
10918function PassThrough(options) {
10919 if (!(this instanceof PassThrough)) return new PassThrough(options);
10920
10921 Transform.call(this, options);
10922}
10923
10924PassThrough.prototype._transform = function (chunk, encoding, cb) {
10925 cb(null, chunk);
10926};
10927},{"./_stream_transform":33,"core-util-is":10,"inherits":13}],32:[function(require,module,exports){
10928(function (process,global){
10929// Copyright Joyent, Inc. and other Node contributors.
10930//
10931// Permission is hereby granted, free of charge, to any person obtaining a
10932// copy of this software and associated documentation files (the
10933// "Software"), to deal in the Software without restriction, including
10934// without limitation the rights to use, copy, modify, merge, publish,
10935// distribute, sublicense, and/or sell copies of the Software, and to permit
10936// persons to whom the Software is furnished to do so, subject to the
10937// following conditions:
10938//
10939// The above copyright notice and this permission notice shall be included
10940// in all copies or substantial portions of the Software.
10941//
10942// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10943// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10944// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10945// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10946// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10947// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10948// USE OR OTHER DEALINGS IN THE SOFTWARE.
10949
10950'use strict';
10951
10952/*<replacement>*/
10953
10954var pna = require('process-nextick-args');
10955/*</replacement>*/
10956
10957module.exports = Readable;
10958
10959/*<replacement>*/
10960var isArray = require('isarray');
10961/*</replacement>*/
10962
10963/*<replacement>*/
10964var Duplex;
10965/*</replacement>*/
10966
10967Readable.ReadableState = ReadableState;
10968
10969/*<replacement>*/
10970var EE = require('events').EventEmitter;
10971
10972var EElistenerCount = function (emitter, type) {
10973 return emitter.listeners(type).length;
10974};
10975/*</replacement>*/
10976
10977/*<replacement>*/
10978var Stream = require('./internal/streams/stream');
10979/*</replacement>*/
10980
10981/*<replacement>*/
10982
10983var Buffer = require('safe-buffer').Buffer;
10984var OurUint8Array = global.Uint8Array || function () {};
10985function _uint8ArrayToBuffer(chunk) {
10986 return Buffer.from(chunk);
10987}
10988function _isUint8Array(obj) {
10989 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
10990}
10991
10992/*</replacement>*/
10993
10994/*<replacement>*/
10995var util = require('core-util-is');
10996util.inherits = require('inherits');
10997/*</replacement>*/
10998
10999/*<replacement>*/
11000var debugUtil = require('util');
11001var debug = void 0;
11002if (debugUtil && debugUtil.debuglog) {
11003 debug = debugUtil.debuglog('stream');
11004} else {
11005 debug = function () {};
11006}
11007/*</replacement>*/
11008
11009var BufferList = require('./internal/streams/BufferList');
11010var destroyImpl = require('./internal/streams/destroy');
11011var StringDecoder;
11012
11013util.inherits(Readable, Stream);
11014
11015var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
11016
11017function prependListener(emitter, event, fn) {
11018 // Sadly this is not cacheable as some libraries bundle their own
11019 // event emitter implementation with them.
11020 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
11021
11022 // This is a hack to make sure that our error handler is attached before any
11023 // userland ones. NEVER DO THIS. This is here only because this code needs
11024 // to continue to work with older versions of Node.js that do not include
11025 // the prependListener() method. The goal is to eventually remove this hack.
11026 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]];
11027}
11028
11029function ReadableState(options, stream) {
11030 Duplex = Duplex || require('./_stream_duplex');
11031
11032 options = options || {};
11033
11034 // Duplex streams are both readable and writable, but share
11035 // the same options object.
11036 // However, some cases require setting options to different
11037 // values for the readable and the writable sides of the duplex stream.
11038 // These options can be provided separately as readableXXX and writableXXX.
11039 var isDuplex = stream instanceof Duplex;
11040
11041 // object stream flag. Used to make read(n) ignore n and to
11042 // make all the buffer merging and length checks go away
11043 this.objectMode = !!options.objectMode;
11044
11045 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
11046
11047 // the point at which it stops calling _read() to fill the buffer
11048 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11049 var hwm = options.highWaterMark;
11050 var readableHwm = options.readableHighWaterMark;
11051 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
11052
11053 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
11054
11055 // cast to ints.
11056 this.highWaterMark = Math.floor(this.highWaterMark);
11057
11058 // A linked list is used to store data chunks instead of an array because the
11059 // linked list can remove elements from the beginning faster than
11060 // array.shift()
11061 this.buffer = new BufferList();
11062 this.length = 0;
11063 this.pipes = null;
11064 this.pipesCount = 0;
11065 this.flowing = null;
11066 this.ended = false;
11067 this.endEmitted = false;
11068 this.reading = false;
11069
11070 // a flag to be able to tell if the event 'readable'/'data' is emitted
11071 // immediately, or on a later tick. We set this to true at first, because
11072 // any actions that shouldn't happen until "later" should generally also
11073 // not happen before the first read call.
11074 this.sync = true;
11075
11076 // whenever we return null, then we set a flag to say
11077 // that we're awaiting a 'readable' event emission.
11078 this.needReadable = false;
11079 this.emittedReadable = false;
11080 this.readableListening = false;
11081 this.resumeScheduled = false;
11082
11083 // has it been destroyed
11084 this.destroyed = false;
11085
11086 // Crypto is kind of old and crusty. Historically, its default string
11087 // encoding is 'binary' so we have to make this configurable.
11088 // Everything else in the universe uses 'utf8', though.
11089 this.defaultEncoding = options.defaultEncoding || 'utf8';
11090
11091 // the number of writers that are awaiting a drain event in .pipe()s
11092 this.awaitDrain = 0;
11093
11094 // if true, a maybeReadMore has been scheduled
11095 this.readingMore = false;
11096
11097 this.decoder = null;
11098 this.encoding = null;
11099 if (options.encoding) {
11100 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
11101 this.decoder = new StringDecoder(options.encoding);
11102 this.encoding = options.encoding;
11103 }
11104}
11105
11106function Readable(options) {
11107 Duplex = Duplex || require('./_stream_duplex');
11108
11109 if (!(this instanceof Readable)) return new Readable(options);
11110
11111 this._readableState = new ReadableState(options, this);
11112
11113 // legacy
11114 this.readable = true;
11115
11116 if (options) {
11117 if (typeof options.read === 'function') this._read = options.read;
11118
11119 if (typeof options.destroy === 'function') this._destroy = options.destroy;
11120 }
11121
11122 Stream.call(this);
11123}
11124
11125Object.defineProperty(Readable.prototype, 'destroyed', {
11126 get: function () {
11127 if (this._readableState === undefined) {
11128 return false;
11129 }
11130 return this._readableState.destroyed;
11131 },
11132 set: function (value) {
11133 // we ignore the value if the stream
11134 // has not been initialized yet
11135 if (!this._readableState) {
11136 return;
11137 }
11138
11139 // backward compatibility, the user is explicitly
11140 // managing destroyed
11141 this._readableState.destroyed = value;
11142 }
11143});
11144
11145Readable.prototype.destroy = destroyImpl.destroy;
11146Readable.prototype._undestroy = destroyImpl.undestroy;
11147Readable.prototype._destroy = function (err, cb) {
11148 this.push(null);
11149 cb(err);
11150};
11151
11152// Manually shove something into the read() buffer.
11153// This returns true if the highWaterMark has not been hit yet,
11154// similar to how Writable.write() returns true if you should
11155// write() some more.
11156Readable.prototype.push = function (chunk, encoding) {
11157 var state = this._readableState;
11158 var skipChunkCheck;
11159
11160 if (!state.objectMode) {
11161 if (typeof chunk === 'string') {
11162 encoding = encoding || state.defaultEncoding;
11163 if (encoding !== state.encoding) {
11164 chunk = Buffer.from(chunk, encoding);
11165 encoding = '';
11166 }
11167 skipChunkCheck = true;
11168 }
11169 } else {
11170 skipChunkCheck = true;
11171 }
11172
11173 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
11174};
11175
11176// Unshift should *always* be something directly out of read()
11177Readable.prototype.unshift = function (chunk) {
11178 return readableAddChunk(this, chunk, null, true, false);
11179};
11180
11181function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
11182 var state = stream._readableState;
11183 if (chunk === null) {
11184 state.reading = false;
11185 onEofChunk(stream, state);
11186 } else {
11187 var er;
11188 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
11189 if (er) {
11190 stream.emit('error', er);
11191 } else if (state.objectMode || chunk && chunk.length > 0) {
11192 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
11193 chunk = _uint8ArrayToBuffer(chunk);
11194 }
11195
11196 if (addToFront) {
11197 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
11198 } else if (state.ended) {
11199 stream.emit('error', new Error('stream.push() after EOF'));
11200 } else {
11201 state.reading = false;
11202 if (state.decoder && !encoding) {
11203 chunk = state.decoder.write(chunk);
11204 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
11205 } else {
11206 addChunk(stream, state, chunk, false);
11207 }
11208 }
11209 } else if (!addToFront) {
11210 state.reading = false;
11211 }
11212 }
11213
11214 return needMoreData(state);
11215}
11216
11217function addChunk(stream, state, chunk, addToFront) {
11218 if (state.flowing && state.length === 0 && !state.sync) {
11219 stream.emit('data', chunk);
11220 stream.read(0);
11221 } else {
11222 // update the buffer info.
11223 state.length += state.objectMode ? 1 : chunk.length;
11224 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
11225
11226 if (state.needReadable) emitReadable(stream);
11227 }
11228 maybeReadMore(stream, state);
11229}
11230
11231function chunkInvalid(state, chunk) {
11232 var er;
11233 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
11234 er = new TypeError('Invalid non-string/buffer chunk');
11235 }
11236 return er;
11237}
11238
11239// if it's past the high water mark, we can push in some more.
11240// Also, if we have no data yet, we can stand some
11241// more bytes. This is to work around cases where hwm=0,
11242// such as the repl. Also, if the push() triggered a
11243// readable event, and the user called read(largeNumber) such that
11244// needReadable was set, then we ought to push more, so that another
11245// 'readable' event will be triggered.
11246function needMoreData(state) {
11247 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
11248}
11249
11250Readable.prototype.isPaused = function () {
11251 return this._readableState.flowing === false;
11252};
11253
11254// backwards compatibility.
11255Readable.prototype.setEncoding = function (enc) {
11256 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
11257 this._readableState.decoder = new StringDecoder(enc);
11258 this._readableState.encoding = enc;
11259 return this;
11260};
11261
11262// Don't raise the hwm > 8MB
11263var MAX_HWM = 0x800000;
11264function computeNewHighWaterMark(n) {
11265 if (n >= MAX_HWM) {
11266 n = MAX_HWM;
11267 } else {
11268 // Get the next highest power of 2 to prevent increasing hwm excessively in
11269 // tiny amounts
11270 n--;
11271 n |= n >>> 1;
11272 n |= n >>> 2;
11273 n |= n >>> 4;
11274 n |= n >>> 8;
11275 n |= n >>> 16;
11276 n++;
11277 }
11278 return n;
11279}
11280
11281// This function is designed to be inlinable, so please take care when making
11282// changes to the function body.
11283function howMuchToRead(n, state) {
11284 if (n <= 0 || state.length === 0 && state.ended) return 0;
11285 if (state.objectMode) return 1;
11286 if (n !== n) {
11287 // Only flow one buffer at a time
11288 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
11289 }
11290 // If we're asking for more than the current hwm, then raise the hwm.
11291 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
11292 if (n <= state.length) return n;
11293 // Don't have enough
11294 if (!state.ended) {
11295 state.needReadable = true;
11296 return 0;
11297 }
11298 return state.length;
11299}
11300
11301// you can override either this method, or the async _read(n) below.
11302Readable.prototype.read = function (n) {
11303 debug('read', n);
11304 n = parseInt(n, 10);
11305 var state = this._readableState;
11306 var nOrig = n;
11307
11308 if (n !== 0) state.emittedReadable = false;
11309
11310 // if we're doing read(0) to trigger a readable event, but we
11311 // already have a bunch of data in the buffer, then just trigger
11312 // the 'readable' event and move on.
11313 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
11314 debug('read: emitReadable', state.length, state.ended);
11315 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
11316 return null;
11317 }
11318
11319 n = howMuchToRead(n, state);
11320
11321 // if we've ended, and we're now clear, then finish it up.
11322 if (n === 0 && state.ended) {
11323 if (state.length === 0) endReadable(this);
11324 return null;
11325 }
11326
11327 // All the actual chunk generation logic needs to be
11328 // *below* the call to _read. The reason is that in certain
11329 // synthetic stream cases, such as passthrough streams, _read
11330 // may be a completely synchronous operation which may change
11331 // the state of the read buffer, providing enough data when
11332 // before there was *not* enough.
11333 //
11334 // So, the steps are:
11335 // 1. Figure out what the state of things will be after we do
11336 // a read from the buffer.
11337 //
11338 // 2. If that resulting state will trigger a _read, then call _read.
11339 // Note that this may be asynchronous, or synchronous. Yes, it is
11340 // deeply ugly to write APIs this way, but that still doesn't mean
11341 // that the Readable class should behave improperly, as streams are
11342 // designed to be sync/async agnostic.
11343 // Take note if the _read call is sync or async (ie, if the read call
11344 // has returned yet), so that we know whether or not it's safe to emit
11345 // 'readable' etc.
11346 //
11347 // 3. Actually pull the requested chunks out of the buffer and return.
11348
11349 // if we need a readable event, then we need to do some reading.
11350 var doRead = state.needReadable;
11351 debug('need readable', doRead);
11352
11353 // if we currently have less than the highWaterMark, then also read some
11354 if (state.length === 0 || state.length - n < state.highWaterMark) {
11355 doRead = true;
11356 debug('length less than watermark', doRead);
11357 }
11358
11359 // however, if we've ended, then there's no point, and if we're already
11360 // reading, then it's unnecessary.
11361 if (state.ended || state.reading) {
11362 doRead = false;
11363 debug('reading or ended', doRead);
11364 } else if (doRead) {
11365 debug('do read');
11366 state.reading = true;
11367 state.sync = true;
11368 // if the length is currently zero, then we *need* a readable event.
11369 if (state.length === 0) state.needReadable = true;
11370 // call internal read method
11371 this._read(state.highWaterMark);
11372 state.sync = false;
11373 // If _read pushed data synchronously, then `reading` will be false,
11374 // and we need to re-evaluate how much data we can return to the user.
11375 if (!state.reading) n = howMuchToRead(nOrig, state);
11376 }
11377
11378 var ret;
11379 if (n > 0) ret = fromList(n, state);else ret = null;
11380
11381 if (ret === null) {
11382 state.needReadable = true;
11383 n = 0;
11384 } else {
11385 state.length -= n;
11386 }
11387
11388 if (state.length === 0) {
11389 // If we have nothing in the buffer, then we want to know
11390 // as soon as we *do* get something into the buffer.
11391 if (!state.ended) state.needReadable = true;
11392
11393 // If we tried to read() past the EOF, then emit end on the next tick.
11394 if (nOrig !== n && state.ended) endReadable(this);
11395 }
11396
11397 if (ret !== null) this.emit('data', ret);
11398
11399 return ret;
11400};
11401
11402function onEofChunk(stream, state) {
11403 if (state.ended) return;
11404 if (state.decoder) {
11405 var chunk = state.decoder.end();
11406 if (chunk && chunk.length) {
11407 state.buffer.push(chunk);
11408 state.length += state.objectMode ? 1 : chunk.length;
11409 }
11410 }
11411 state.ended = true;
11412
11413 // emit 'readable' now to make sure it gets picked up.
11414 emitReadable(stream);
11415}
11416
11417// Don't emit readable right away in sync mode, because this can trigger
11418// another read() call => stack overflow. This way, it might trigger
11419// a nextTick recursion warning, but that's not so bad.
11420function emitReadable(stream) {
11421 var state = stream._readableState;
11422 state.needReadable = false;
11423 if (!state.emittedReadable) {
11424 debug('emitReadable', state.flowing);
11425 state.emittedReadable = true;
11426 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
11427 }
11428}
11429
11430function emitReadable_(stream) {
11431 debug('emit readable');
11432 stream.emit('readable');
11433 flow(stream);
11434}
11435
11436// at this point, the user has presumably seen the 'readable' event,
11437// and called read() to consume some data. that may have triggered
11438// in turn another _read(n) call, in which case reading = true if
11439// it's in progress.
11440// However, if we're not ended, or reading, and the length < hwm,
11441// then go ahead and try to read some more preemptively.
11442function maybeReadMore(stream, state) {
11443 if (!state.readingMore) {
11444 state.readingMore = true;
11445 pna.nextTick(maybeReadMore_, stream, state);
11446 }
11447}
11448
11449function maybeReadMore_(stream, state) {
11450 var len = state.length;
11451 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
11452 debug('maybeReadMore read 0');
11453 stream.read(0);
11454 if (len === state.length)
11455 // didn't get any data, stop spinning.
11456 break;else len = state.length;
11457 }
11458 state.readingMore = false;
11459}
11460
11461// abstract method. to be overridden in specific implementation classes.
11462// call cb(er, data) where data is <= n in length.
11463// for virtual (non-string, non-buffer) streams, "length" is somewhat
11464// arbitrary, and perhaps not very meaningful.
11465Readable.prototype._read = function (n) {
11466 this.emit('error', new Error('_read() is not implemented'));
11467};
11468
11469Readable.prototype.pipe = function (dest, pipeOpts) {
11470 var src = this;
11471 var state = this._readableState;
11472
11473 switch (state.pipesCount) {
11474 case 0:
11475 state.pipes = dest;
11476 break;
11477 case 1:
11478 state.pipes = [state.pipes, dest];
11479 break;
11480 default:
11481 state.pipes.push(dest);
11482 break;
11483 }
11484 state.pipesCount += 1;
11485 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
11486
11487 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
11488
11489 var endFn = doEnd ? onend : unpipe;
11490 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
11491
11492 dest.on('unpipe', onunpipe);
11493 function onunpipe(readable, unpipeInfo) {
11494 debug('onunpipe');
11495 if (readable === src) {
11496 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
11497 unpipeInfo.hasUnpiped = true;
11498 cleanup();
11499 }
11500 }
11501 }
11502
11503 function onend() {
11504 debug('onend');
11505 dest.end();
11506 }
11507
11508 // when the dest drains, it reduces the awaitDrain counter
11509 // on the source. This would be more elegant with a .once()
11510 // handler in flow(), but adding and removing repeatedly is
11511 // too slow.
11512 var ondrain = pipeOnDrain(src);
11513 dest.on('drain', ondrain);
11514
11515 var cleanedUp = false;
11516 function cleanup() {
11517 debug('cleanup');
11518 // cleanup event handlers once the pipe is broken
11519 dest.removeListener('close', onclose);
11520 dest.removeListener('finish', onfinish);
11521 dest.removeListener('drain', ondrain);
11522 dest.removeListener('error', onerror);
11523 dest.removeListener('unpipe', onunpipe);
11524 src.removeListener('end', onend);
11525 src.removeListener('end', unpipe);
11526 src.removeListener('data', ondata);
11527
11528 cleanedUp = true;
11529
11530 // if the reader is waiting for a drain event from this
11531 // specific writer, then it would cause it to never start
11532 // flowing again.
11533 // So, if this is awaiting a drain, then we just call it now.
11534 // If we don't know, then assume that we are waiting for one.
11535 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
11536 }
11537
11538 // If the user pushes more data while we're writing to dest then we'll end up
11539 // in ondata again. However, we only want to increase awaitDrain once because
11540 // dest will only emit one 'drain' event for the multiple writes.
11541 // => Introduce a guard on increasing awaitDrain.
11542 var increasedAwaitDrain = false;
11543 src.on('data', ondata);
11544 function ondata(chunk) {
11545 debug('ondata');
11546 increasedAwaitDrain = false;
11547 var ret = dest.write(chunk);
11548 if (false === ret && !increasedAwaitDrain) {
11549 // If the user unpiped during `dest.write()`, it is possible
11550 // to get stuck in a permanently paused state if that write
11551 // also returned false.
11552 // => Check whether `dest` is still a piping destination.
11553 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
11554 debug('false write response, pause', src._readableState.awaitDrain);
11555 src._readableState.awaitDrain++;
11556 increasedAwaitDrain = true;
11557 }
11558 src.pause();
11559 }
11560 }
11561
11562 // if the dest has an error, then stop piping into it.
11563 // however, don't suppress the throwing behavior for this.
11564 function onerror(er) {
11565 debug('onerror', er);
11566 unpipe();
11567 dest.removeListener('error', onerror);
11568 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
11569 }
11570
11571 // Make sure our error handler is attached before userland ones.
11572 prependListener(dest, 'error', onerror);
11573
11574 // Both close and finish should trigger unpipe, but only once.
11575 function onclose() {
11576 dest.removeListener('finish', onfinish);
11577 unpipe();
11578 }
11579 dest.once('close', onclose);
11580 function onfinish() {
11581 debug('onfinish');
11582 dest.removeListener('close', onclose);
11583 unpipe();
11584 }
11585 dest.once('finish', onfinish);
11586
11587 function unpipe() {
11588 debug('unpipe');
11589 src.unpipe(dest);
11590 }
11591
11592 // tell the dest that it's being piped to
11593 dest.emit('pipe', src);
11594
11595 // start the flow if it hasn't been started already.
11596 if (!state.flowing) {
11597 debug('pipe resume');
11598 src.resume();
11599 }
11600
11601 return dest;
11602};
11603
11604function pipeOnDrain(src) {
11605 return function () {
11606 var state = src._readableState;
11607 debug('pipeOnDrain', state.awaitDrain);
11608 if (state.awaitDrain) state.awaitDrain--;
11609 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
11610 state.flowing = true;
11611 flow(src);
11612 }
11613 };
11614}
11615
11616Readable.prototype.unpipe = function (dest) {
11617 var state = this._readableState;
11618 var unpipeInfo = { hasUnpiped: false };
11619
11620 // if we're not piping anywhere, then do nothing.
11621 if (state.pipesCount === 0) return this;
11622
11623 // just one destination. most common case.
11624 if (state.pipesCount === 1) {
11625 // passed in one, but it's not the right one.
11626 if (dest && dest !== state.pipes) return this;
11627
11628 if (!dest) dest = state.pipes;
11629
11630 // got a match.
11631 state.pipes = null;
11632 state.pipesCount = 0;
11633 state.flowing = false;
11634 if (dest) dest.emit('unpipe', this, unpipeInfo);
11635 return this;
11636 }
11637
11638 // slow case. multiple pipe destinations.
11639
11640 if (!dest) {
11641 // remove all.
11642 var dests = state.pipes;
11643 var len = state.pipesCount;
11644 state.pipes = null;
11645 state.pipesCount = 0;
11646 state.flowing = false;
11647
11648 for (var i = 0; i < len; i++) {
11649 dests[i].emit('unpipe', this, unpipeInfo);
11650 }return this;
11651 }
11652
11653 // try to find the right one.
11654 var index = indexOf(state.pipes, dest);
11655 if (index === -1) return this;
11656
11657 state.pipes.splice(index, 1);
11658 state.pipesCount -= 1;
11659 if (state.pipesCount === 1) state.pipes = state.pipes[0];
11660
11661 dest.emit('unpipe', this, unpipeInfo);
11662
11663 return this;
11664};
11665
11666// set up data events if they are asked for
11667// Ensure readable listeners eventually get something
11668Readable.prototype.on = function (ev, fn) {
11669 var res = Stream.prototype.on.call(this, ev, fn);
11670
11671 if (ev === 'data') {
11672 // Start flowing on next tick if stream isn't explicitly paused
11673 if (this._readableState.flowing !== false) this.resume();
11674 } else if (ev === 'readable') {
11675 var state = this._readableState;
11676 if (!state.endEmitted && !state.readableListening) {
11677 state.readableListening = state.needReadable = true;
11678 state.emittedReadable = false;
11679 if (!state.reading) {
11680 pna.nextTick(nReadingNextTick, this);
11681 } else if (state.length) {
11682 emitReadable(this);
11683 }
11684 }
11685 }
11686
11687 return res;
11688};
11689Readable.prototype.addListener = Readable.prototype.on;
11690
11691function nReadingNextTick(self) {
11692 debug('readable nexttick read 0');
11693 self.read(0);
11694}
11695
11696// pause() and resume() are remnants of the legacy readable stream API
11697// If the user uses them, then switch into old mode.
11698Readable.prototype.resume = function () {
11699 var state = this._readableState;
11700 if (!state.flowing) {
11701 debug('resume');
11702 state.flowing = true;
11703 resume(this, state);
11704 }
11705 return this;
11706};
11707
11708function resume(stream, state) {
11709 if (!state.resumeScheduled) {
11710 state.resumeScheduled = true;
11711 pna.nextTick(resume_, stream, state);
11712 }
11713}
11714
11715function resume_(stream, state) {
11716 if (!state.reading) {
11717 debug('resume read 0');
11718 stream.read(0);
11719 }
11720
11721 state.resumeScheduled = false;
11722 state.awaitDrain = 0;
11723 stream.emit('resume');
11724 flow(stream);
11725 if (state.flowing && !state.reading) stream.read(0);
11726}
11727
11728Readable.prototype.pause = function () {
11729 debug('call pause flowing=%j', this._readableState.flowing);
11730 if (false !== this._readableState.flowing) {
11731 debug('pause');
11732 this._readableState.flowing = false;
11733 this.emit('pause');
11734 }
11735 return this;
11736};
11737
11738function flow(stream) {
11739 var state = stream._readableState;
11740 debug('flow', state.flowing);
11741 while (state.flowing && stream.read() !== null) {}
11742}
11743
11744// wrap an old-style stream as the async data source.
11745// This is *not* part of the readable stream interface.
11746// It is an ugly unfortunate mess of history.
11747Readable.prototype.wrap = function (stream) {
11748 var _this = this;
11749
11750 var state = this._readableState;
11751 var paused = false;
11752
11753 stream.on('end', function () {
11754 debug('wrapped end');
11755 if (state.decoder && !state.ended) {
11756 var chunk = state.decoder.end();
11757 if (chunk && chunk.length) _this.push(chunk);
11758 }
11759
11760 _this.push(null);
11761 });
11762
11763 stream.on('data', function (chunk) {
11764 debug('wrapped data');
11765 if (state.decoder) chunk = state.decoder.write(chunk);
11766
11767 // don't skip over falsy values in objectMode
11768 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
11769
11770 var ret = _this.push(chunk);
11771 if (!ret) {
11772 paused = true;
11773 stream.pause();
11774 }
11775 });
11776
11777 // proxy all the other methods.
11778 // important when wrapping filters and duplexes.
11779 for (var i in stream) {
11780 if (this[i] === undefined && typeof stream[i] === 'function') {
11781 this[i] = function (method) {
11782 return function () {
11783 return stream[method].apply(stream, arguments);
11784 };
11785 }(i);
11786 }
11787 }
11788
11789 // proxy certain important events.
11790 for (var n = 0; n < kProxyEvents.length; n++) {
11791 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
11792 }
11793
11794 // when we try to consume some more bytes, simply unpause the
11795 // underlying stream.
11796 this._read = function (n) {
11797 debug('wrapped _read', n);
11798 if (paused) {
11799 paused = false;
11800 stream.resume();
11801 }
11802 };
11803
11804 return this;
11805};
11806
11807Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
11808 // making it explicit this property is not enumerable
11809 // because otherwise some prototype manipulation in
11810 // userland will fail
11811 enumerable: false,
11812 get: function () {
11813 return this._readableState.highWaterMark;
11814 }
11815});
11816
11817// exposed for testing purposes only.
11818Readable._fromList = fromList;
11819
11820// Pluck off n bytes from an array of buffers.
11821// Length is the combined lengths of all the buffers in the list.
11822// This function is designed to be inlinable, so please take care when making
11823// changes to the function body.
11824function fromList(n, state) {
11825 // nothing buffered
11826 if (state.length === 0) return null;
11827
11828 var ret;
11829 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
11830 // read it all, truncate the list
11831 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);
11832 state.buffer.clear();
11833 } else {
11834 // read part of list
11835 ret = fromListPartial(n, state.buffer, state.decoder);
11836 }
11837
11838 return ret;
11839}
11840
11841// Extracts only enough buffered data to satisfy the amount requested.
11842// This function is designed to be inlinable, so please take care when making
11843// changes to the function body.
11844function fromListPartial(n, list, hasStrings) {
11845 var ret;
11846 if (n < list.head.data.length) {
11847 // slice is the same for buffers and strings
11848 ret = list.head.data.slice(0, n);
11849 list.head.data = list.head.data.slice(n);
11850 } else if (n === list.head.data.length) {
11851 // first chunk is a perfect match
11852 ret = list.shift();
11853 } else {
11854 // result spans more than one buffer
11855 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
11856 }
11857 return ret;
11858}
11859
11860// Copies a specified amount of characters from the list of buffered data
11861// chunks.
11862// This function is designed to be inlinable, so please take care when making
11863// changes to the function body.
11864function copyFromBufferString(n, list) {
11865 var p = list.head;
11866 var c = 1;
11867 var ret = p.data;
11868 n -= ret.length;
11869 while (p = p.next) {
11870 var str = p.data;
11871 var nb = n > str.length ? str.length : n;
11872 if (nb === str.length) ret += str;else ret += str.slice(0, n);
11873 n -= nb;
11874 if (n === 0) {
11875 if (nb === str.length) {
11876 ++c;
11877 if (p.next) list.head = p.next;else list.head = list.tail = null;
11878 } else {
11879 list.head = p;
11880 p.data = str.slice(nb);
11881 }
11882 break;
11883 }
11884 ++c;
11885 }
11886 list.length -= c;
11887 return ret;
11888}
11889
11890// Copies a specified amount of bytes from the list of buffered data chunks.
11891// This function is designed to be inlinable, so please take care when making
11892// changes to the function body.
11893function copyFromBuffer(n, list) {
11894 var ret = Buffer.allocUnsafe(n);
11895 var p = list.head;
11896 var c = 1;
11897 p.data.copy(ret);
11898 n -= p.data.length;
11899 while (p = p.next) {
11900 var buf = p.data;
11901 var nb = n > buf.length ? buf.length : n;
11902 buf.copy(ret, ret.length - n, 0, nb);
11903 n -= nb;
11904 if (n === 0) {
11905 if (nb === buf.length) {
11906 ++c;
11907 if (p.next) list.head = p.next;else list.head = list.tail = null;
11908 } else {
11909 list.head = p;
11910 p.data = buf.slice(nb);
11911 }
11912 break;
11913 }
11914 ++c;
11915 }
11916 list.length -= c;
11917 return ret;
11918}
11919
11920function endReadable(stream) {
11921 var state = stream._readableState;
11922
11923 // If we get here before consuming all the bytes, then that is a
11924 // bug in node. Should never happen.
11925 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
11926
11927 if (!state.endEmitted) {
11928 state.ended = true;
11929 pna.nextTick(endReadableNT, state, stream);
11930 }
11931}
11932
11933function endReadableNT(state, stream) {
11934 // Check that we didn't get one last unshift.
11935 if (!state.endEmitted && state.length === 0) {
11936 state.endEmitted = true;
11937 stream.readable = false;
11938 stream.emit('end');
11939 }
11940}
11941
11942function indexOf(xs, x) {
11943 for (var i = 0, l = xs.length; i < l; i++) {
11944 if (xs[i] === x) return i;
11945 }
11946 return -1;
11947}
11948}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11949},{"./_stream_duplex":30,"./internal/streams/BufferList":35,"./internal/streams/destroy":36,"./internal/streams/stream":37,"_process":28,"core-util-is":10,"events":11,"inherits":13,"isarray":15,"process-nextick-args":27,"safe-buffer":42,"string_decoder/":44,"util":6}],33:[function(require,module,exports){
11950// Copyright Joyent, Inc. and other Node contributors.
11951//
11952// Permission is hereby granted, free of charge, to any person obtaining a
11953// copy of this software and associated documentation files (the
11954// "Software"), to deal in the Software without restriction, including
11955// without limitation the rights to use, copy, modify, merge, publish,
11956// distribute, sublicense, and/or sell copies of the Software, and to permit
11957// persons to whom the Software is furnished to do so, subject to the
11958// following conditions:
11959//
11960// The above copyright notice and this permission notice shall be included
11961// in all copies or substantial portions of the Software.
11962//
11963// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11964// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11965// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11966// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11967// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11968// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11969// USE OR OTHER DEALINGS IN THE SOFTWARE.
11970
11971// a transform stream is a readable/writable stream where you do
11972// something with the data. Sometimes it's called a "filter",
11973// but that's not a great name for it, since that implies a thing where
11974// some bits pass through, and others are simply ignored. (That would
11975// be a valid example of a transform, of course.)
11976//
11977// While the output is causally related to the input, it's not a
11978// necessarily symmetric or synchronous transformation. For example,
11979// a zlib stream might take multiple plain-text writes(), and then
11980// emit a single compressed chunk some time in the future.
11981//
11982// Here's how this works:
11983//
11984// The Transform stream has all the aspects of the readable and writable
11985// stream classes. When you write(chunk), that calls _write(chunk,cb)
11986// internally, and returns false if there's a lot of pending writes
11987// buffered up. When you call read(), that calls _read(n) until
11988// there's enough pending readable data buffered up.
11989//
11990// In a transform stream, the written data is placed in a buffer. When
11991// _read(n) is called, it transforms the queued up data, calling the
11992// buffered _write cb's as it consumes chunks. If consuming a single
11993// written chunk would result in multiple output chunks, then the first
11994// outputted bit calls the readcb, and subsequent chunks just go into
11995// the read buffer, and will cause it to emit 'readable' if necessary.
11996//
11997// This way, back-pressure is actually determined by the reading side,
11998// since _read has to be called to start processing a new chunk. However,
11999// a pathological inflate type of transform can cause excessive buffering
12000// here. For example, imagine a stream where every byte of input is
12001// interpreted as an integer from 0-255, and then results in that many
12002// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12003// 1kb of data being output. In this case, you could write a very small
12004// amount of input, and end up with a very large amount of output. In
12005// such a pathological inflating mechanism, there'd be no way to tell
12006// the system to stop doing the transform. A single 4MB write could
12007// cause the system to run out of memory.
12008//
12009// However, even in such a pathological case, only a single written chunk
12010// would be consumed, and then the rest would wait (un-transformed) until
12011// the results of the previous transformed chunk were consumed.
12012
12013'use strict';
12014
12015module.exports = Transform;
12016
12017var Duplex = require('./_stream_duplex');
12018
12019/*<replacement>*/
12020var util = require('core-util-is');
12021util.inherits = require('inherits');
12022/*</replacement>*/
12023
12024util.inherits(Transform, Duplex);
12025
12026function afterTransform(er, data) {
12027 var ts = this._transformState;
12028 ts.transforming = false;
12029
12030 var cb = ts.writecb;
12031
12032 if (!cb) {
12033 return this.emit('error', new Error('write callback called multiple times'));
12034 }
12035
12036 ts.writechunk = null;
12037 ts.writecb = null;
12038
12039 if (data != null) // single equals check for both `null` and `undefined`
12040 this.push(data);
12041
12042 cb(er);
12043
12044 var rs = this._readableState;
12045 rs.reading = false;
12046 if (rs.needReadable || rs.length < rs.highWaterMark) {
12047 this._read(rs.highWaterMark);
12048 }
12049}
12050
12051function Transform(options) {
12052 if (!(this instanceof Transform)) return new Transform(options);
12053
12054 Duplex.call(this, options);
12055
12056 this._transformState = {
12057 afterTransform: afterTransform.bind(this),
12058 needTransform: false,
12059 transforming: false,
12060 writecb: null,
12061 writechunk: null,
12062 writeencoding: null
12063 };
12064
12065 // start out asking for a readable event once data is transformed.
12066 this._readableState.needReadable = true;
12067
12068 // we have implemented the _read method, and done the other things
12069 // that Readable wants before the first _read call, so unset the
12070 // sync guard flag.
12071 this._readableState.sync = false;
12072
12073 if (options) {
12074 if (typeof options.transform === 'function') this._transform = options.transform;
12075
12076 if (typeof options.flush === 'function') this._flush = options.flush;
12077 }
12078
12079 // When the writable side finishes, then flush out anything remaining.
12080 this.on('prefinish', prefinish);
12081}
12082
12083function prefinish() {
12084 var _this = this;
12085
12086 if (typeof this._flush === 'function') {
12087 this._flush(function (er, data) {
12088 done(_this, er, data);
12089 });
12090 } else {
12091 done(this, null, null);
12092 }
12093}
12094
12095Transform.prototype.push = function (chunk, encoding) {
12096 this._transformState.needTransform = false;
12097 return Duplex.prototype.push.call(this, chunk, encoding);
12098};
12099
12100// This is the part where you do stuff!
12101// override this function in implementation classes.
12102// 'chunk' is an input chunk.
12103//
12104// Call `push(newChunk)` to pass along transformed output
12105// to the readable side. You may call 'push' zero or more times.
12106//
12107// Call `cb(err)` when you are done with this chunk. If you pass
12108// an error, then that'll put the hurt on the whole operation. If you
12109// never call cb(), then you'll never get another chunk.
12110Transform.prototype._transform = function (chunk, encoding, cb) {
12111 throw new Error('_transform() is not implemented');
12112};
12113
12114Transform.prototype._write = function (chunk, encoding, cb) {
12115 var ts = this._transformState;
12116 ts.writecb = cb;
12117 ts.writechunk = chunk;
12118 ts.writeencoding = encoding;
12119 if (!ts.transforming) {
12120 var rs = this._readableState;
12121 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
12122 }
12123};
12124
12125// Doesn't matter what the args are here.
12126// _transform does all the work.
12127// That we got here means that the readable side wants more data.
12128Transform.prototype._read = function (n) {
12129 var ts = this._transformState;
12130
12131 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
12132 ts.transforming = true;
12133 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12134 } else {
12135 // mark that we need a transform, so that any data that comes in
12136 // will get processed, now that we've asked for it.
12137 ts.needTransform = true;
12138 }
12139};
12140
12141Transform.prototype._destroy = function (err, cb) {
12142 var _this2 = this;
12143
12144 Duplex.prototype._destroy.call(this, err, function (err2) {
12145 cb(err2);
12146 _this2.emit('close');
12147 });
12148};
12149
12150function done(stream, er, data) {
12151 if (er) return stream.emit('error', er);
12152
12153 if (data != null) // single equals check for both `null` and `undefined`
12154 stream.push(data);
12155
12156 // if there's nothing in the write buffer, then that means
12157 // that nothing more will ever be provided
12158 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
12159
12160 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
12161
12162 return stream.push(null);
12163}
12164},{"./_stream_duplex":30,"core-util-is":10,"inherits":13}],34:[function(require,module,exports){
12165(function (process,global,setImmediate){
12166// Copyright Joyent, Inc. and other Node contributors.
12167//
12168// Permission is hereby granted, free of charge, to any person obtaining a
12169// copy of this software and associated documentation files (the
12170// "Software"), to deal in the Software without restriction, including
12171// without limitation the rights to use, copy, modify, merge, publish,
12172// distribute, sublicense, and/or sell copies of the Software, and to permit
12173// persons to whom the Software is furnished to do so, subject to the
12174// following conditions:
12175//
12176// The above copyright notice and this permission notice shall be included
12177// in all copies or substantial portions of the Software.
12178//
12179// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12180// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12181// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12182// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12183// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12184// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12185// USE OR OTHER DEALINGS IN THE SOFTWARE.
12186
12187// A bit simpler than readable streams.
12188// Implement an async ._write(chunk, encoding, cb), and it'll handle all
12189// the drain event emission and buffering.
12190
12191'use strict';
12192
12193/*<replacement>*/
12194
12195var pna = require('process-nextick-args');
12196/*</replacement>*/
12197
12198module.exports = Writable;
12199
12200/* <replacement> */
12201function WriteReq(chunk, encoding, cb) {
12202 this.chunk = chunk;
12203 this.encoding = encoding;
12204 this.callback = cb;
12205 this.next = null;
12206}
12207
12208// It seems a linked list but it is not
12209// there will be only 2 of these for each stream
12210function CorkedRequest(state) {
12211 var _this = this;
12212
12213 this.next = null;
12214 this.entry = null;
12215 this.finish = function () {
12216 onCorkedFinish(_this, state);
12217 };
12218}
12219/* </replacement> */
12220
12221/*<replacement>*/
12222var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
12223/*</replacement>*/
12224
12225/*<replacement>*/
12226var Duplex;
12227/*</replacement>*/
12228
12229Writable.WritableState = WritableState;
12230
12231/*<replacement>*/
12232var util = require('core-util-is');
12233util.inherits = require('inherits');
12234/*</replacement>*/
12235
12236/*<replacement>*/
12237var internalUtil = {
12238 deprecate: require('util-deprecate')
12239};
12240/*</replacement>*/
12241
12242/*<replacement>*/
12243var Stream = require('./internal/streams/stream');
12244/*</replacement>*/
12245
12246/*<replacement>*/
12247
12248var Buffer = require('safe-buffer').Buffer;
12249var OurUint8Array = global.Uint8Array || function () {};
12250function _uint8ArrayToBuffer(chunk) {
12251 return Buffer.from(chunk);
12252}
12253function _isUint8Array(obj) {
12254 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
12255}
12256
12257/*</replacement>*/
12258
12259var destroyImpl = require('./internal/streams/destroy');
12260
12261util.inherits(Writable, Stream);
12262
12263function nop() {}
12264
12265function WritableState(options, stream) {
12266 Duplex = Duplex || require('./_stream_duplex');
12267
12268 options = options || {};
12269
12270 // Duplex streams are both readable and writable, but share
12271 // the same options object.
12272 // However, some cases require setting options to different
12273 // values for the readable and the writable sides of the duplex stream.
12274 // These options can be provided separately as readableXXX and writableXXX.
12275 var isDuplex = stream instanceof Duplex;
12276
12277 // object stream flag to indicate whether or not this stream
12278 // contains buffers or objects.
12279 this.objectMode = !!options.objectMode;
12280
12281 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
12282
12283 // the point at which write() starts returning false
12284 // Note: 0 is a valid value, means that we always return false if
12285 // the entire buffer is not flushed immediately on write()
12286 var hwm = options.highWaterMark;
12287 var writableHwm = options.writableHighWaterMark;
12288 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
12289
12290 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
12291
12292 // cast to ints.
12293 this.highWaterMark = Math.floor(this.highWaterMark);
12294
12295 // if _final has been called
12296 this.finalCalled = false;
12297
12298 // drain event flag.
12299 this.needDrain = false;
12300 // at the start of calling end()
12301 this.ending = false;
12302 // when end() has been called, and returned
12303 this.ended = false;
12304 // when 'finish' is emitted
12305 this.finished = false;
12306
12307 // has it been destroyed
12308 this.destroyed = false;
12309
12310 // should we decode strings into buffers before passing to _write?
12311 // this is here so that some node-core streams can optimize string
12312 // handling at a lower level.
12313 var noDecode = options.decodeStrings === false;
12314 this.decodeStrings = !noDecode;
12315
12316 // Crypto is kind of old and crusty. Historically, its default string
12317 // encoding is 'binary' so we have to make this configurable.
12318 // Everything else in the universe uses 'utf8', though.
12319 this.defaultEncoding = options.defaultEncoding || 'utf8';
12320
12321 // not an actual buffer we keep track of, but a measurement
12322 // of how much we're waiting to get pushed to some underlying
12323 // socket or file.
12324 this.length = 0;
12325
12326 // a flag to see when we're in the middle of a write.
12327 this.writing = false;
12328
12329 // when true all writes will be buffered until .uncork() call
12330 this.corked = 0;
12331
12332 // a flag to be able to tell if the onwrite cb is called immediately,
12333 // or on a later tick. We set this to true at first, because any
12334 // actions that shouldn't happen until "later" should generally also
12335 // not happen before the first write call.
12336 this.sync = true;
12337
12338 // a flag to know if we're processing previously buffered items, which
12339 // may call the _write() callback in the same tick, so that we don't
12340 // end up in an overlapped onwrite situation.
12341 this.bufferProcessing = false;
12342
12343 // the callback that's passed to _write(chunk,cb)
12344 this.onwrite = function (er) {
12345 onwrite(stream, er);
12346 };
12347
12348 // the callback that the user supplies to write(chunk,encoding,cb)
12349 this.writecb = null;
12350
12351 // the amount that is being written when _write is called.
12352 this.writelen = 0;
12353
12354 this.bufferedRequest = null;
12355 this.lastBufferedRequest = null;
12356
12357 // number of pending user-supplied write callbacks
12358 // this must be 0 before 'finish' can be emitted
12359 this.pendingcb = 0;
12360
12361 // emit prefinish if the only thing we're waiting for is _write cbs
12362 // This is relevant for synchronous Transform streams
12363 this.prefinished = false;
12364
12365 // True if the error was already emitted and should not be thrown again
12366 this.errorEmitted = false;
12367
12368 // count buffered requests
12369 this.bufferedRequestCount = 0;
12370
12371 // allocate the first CorkedRequest, there is always
12372 // one allocated and free to use, and we maintain at most two
12373 this.corkedRequestsFree = new CorkedRequest(this);
12374}
12375
12376WritableState.prototype.getBuffer = function getBuffer() {
12377 var current = this.bufferedRequest;
12378 var out = [];
12379 while (current) {
12380 out.push(current);
12381 current = current.next;
12382 }
12383 return out;
12384};
12385
12386(function () {
12387 try {
12388 Object.defineProperty(WritableState.prototype, 'buffer', {
12389 get: internalUtil.deprecate(function () {
12390 return this.getBuffer();
12391 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
12392 });
12393 } catch (_) {}
12394})();
12395
12396// Test _writableState for inheritance to account for Duplex streams,
12397// whose prototype chain only points to Readable.
12398var realHasInstance;
12399if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
12400 realHasInstance = Function.prototype[Symbol.hasInstance];
12401 Object.defineProperty(Writable, Symbol.hasInstance, {
12402 value: function (object) {
12403 if (realHasInstance.call(this, object)) return true;
12404 if (this !== Writable) return false;
12405
12406 return object && object._writableState instanceof WritableState;
12407 }
12408 });
12409} else {
12410 realHasInstance = function (object) {
12411 return object instanceof this;
12412 };
12413}
12414
12415function Writable(options) {
12416 Duplex = Duplex || require('./_stream_duplex');
12417
12418 // Writable ctor is applied to Duplexes, too.
12419 // `realHasInstance` is necessary because using plain `instanceof`
12420 // would return false, as no `_writableState` property is attached.
12421
12422 // Trying to use the custom `instanceof` for Writable here will also break the
12423 // Node.js LazyTransform implementation, which has a non-trivial getter for
12424 // `_writableState` that would lead to infinite recursion.
12425 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
12426 return new Writable(options);
12427 }
12428
12429 this._writableState = new WritableState(options, this);
12430
12431 // legacy.
12432 this.writable = true;
12433
12434 if (options) {
12435 if (typeof options.write === 'function') this._write = options.write;
12436
12437 if (typeof options.writev === 'function') this._writev = options.writev;
12438
12439 if (typeof options.destroy === 'function') this._destroy = options.destroy;
12440
12441 if (typeof options.final === 'function') this._final = options.final;
12442 }
12443
12444 Stream.call(this);
12445}
12446
12447// Otherwise people can pipe Writable streams, which is just wrong.
12448Writable.prototype.pipe = function () {
12449 this.emit('error', new Error('Cannot pipe, not readable'));
12450};
12451
12452function writeAfterEnd(stream, cb) {
12453 var er = new Error('write after end');
12454 // TODO: defer error events consistently everywhere, not just the cb
12455 stream.emit('error', er);
12456 pna.nextTick(cb, er);
12457}
12458
12459// Checks that a user-supplied chunk is valid, especially for the particular
12460// mode the stream is in. Currently this means that `null` is never accepted
12461// and undefined/non-string values are only allowed in object mode.
12462function validChunk(stream, state, chunk, cb) {
12463 var valid = true;
12464 var er = false;
12465
12466 if (chunk === null) {
12467 er = new TypeError('May not write null values to stream');
12468 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
12469 er = new TypeError('Invalid non-string/buffer chunk');
12470 }
12471 if (er) {
12472 stream.emit('error', er);
12473 pna.nextTick(cb, er);
12474 valid = false;
12475 }
12476 return valid;
12477}
12478
12479Writable.prototype.write = function (chunk, encoding, cb) {
12480 var state = this._writableState;
12481 var ret = false;
12482 var isBuf = !state.objectMode && _isUint8Array(chunk);
12483
12484 if (isBuf && !Buffer.isBuffer(chunk)) {
12485 chunk = _uint8ArrayToBuffer(chunk);
12486 }
12487
12488 if (typeof encoding === 'function') {
12489 cb = encoding;
12490 encoding = null;
12491 }
12492
12493 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
12494
12495 if (typeof cb !== 'function') cb = nop;
12496
12497 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
12498 state.pendingcb++;
12499 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
12500 }
12501
12502 return ret;
12503};
12504
12505Writable.prototype.cork = function () {
12506 var state = this._writableState;
12507
12508 state.corked++;
12509};
12510
12511Writable.prototype.uncork = function () {
12512 var state = this._writableState;
12513
12514 if (state.corked) {
12515 state.corked--;
12516
12517 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
12518 }
12519};
12520
12521Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
12522 // node::ParseEncoding() requires lower case.
12523 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
12524 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);
12525 this._writableState.defaultEncoding = encoding;
12526 return this;
12527};
12528
12529function decodeChunk(state, chunk, encoding) {
12530 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
12531 chunk = Buffer.from(chunk, encoding);
12532 }
12533 return chunk;
12534}
12535
12536Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
12537 // making it explicit this property is not enumerable
12538 // because otherwise some prototype manipulation in
12539 // userland will fail
12540 enumerable: false,
12541 get: function () {
12542 return this._writableState.highWaterMark;
12543 }
12544});
12545
12546// if we're already writing something, then just put this
12547// in the queue, and wait our turn. Otherwise, call _write
12548// If we return false, then we need a drain event, so set that flag.
12549function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
12550 if (!isBuf) {
12551 var newChunk = decodeChunk(state, chunk, encoding);
12552 if (chunk !== newChunk) {
12553 isBuf = true;
12554 encoding = 'buffer';
12555 chunk = newChunk;
12556 }
12557 }
12558 var len = state.objectMode ? 1 : chunk.length;
12559
12560 state.length += len;
12561
12562 var ret = state.length < state.highWaterMark;
12563 // we must ensure that previous needDrain will not be reset to false.
12564 if (!ret) state.needDrain = true;
12565
12566 if (state.writing || state.corked) {
12567 var last = state.lastBufferedRequest;
12568 state.lastBufferedRequest = {
12569 chunk: chunk,
12570 encoding: encoding,
12571 isBuf: isBuf,
12572 callback: cb,
12573 next: null
12574 };
12575 if (last) {
12576 last.next = state.lastBufferedRequest;
12577 } else {
12578 state.bufferedRequest = state.lastBufferedRequest;
12579 }
12580 state.bufferedRequestCount += 1;
12581 } else {
12582 doWrite(stream, state, false, len, chunk, encoding, cb);
12583 }
12584
12585 return ret;
12586}
12587
12588function doWrite(stream, state, writev, len, chunk, encoding, cb) {
12589 state.writelen = len;
12590 state.writecb = cb;
12591 state.writing = true;
12592 state.sync = true;
12593 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
12594 state.sync = false;
12595}
12596
12597function onwriteError(stream, state, sync, er, cb) {
12598 --state.pendingcb;
12599
12600 if (sync) {
12601 // defer the callback if we are being called synchronously
12602 // to avoid piling up things on the stack
12603 pna.nextTick(cb, er);
12604 // this can emit finish, and it will always happen
12605 // after error
12606 pna.nextTick(finishMaybe, stream, state);
12607 stream._writableState.errorEmitted = true;
12608 stream.emit('error', er);
12609 } else {
12610 // the caller expect this to happen before if
12611 // it is async
12612 cb(er);
12613 stream._writableState.errorEmitted = true;
12614 stream.emit('error', er);
12615 // this can emit finish, but finish must
12616 // always follow error
12617 finishMaybe(stream, state);
12618 }
12619}
12620
12621function onwriteStateUpdate(state) {
12622 state.writing = false;
12623 state.writecb = null;
12624 state.length -= state.writelen;
12625 state.writelen = 0;
12626}
12627
12628function onwrite(stream, er) {
12629 var state = stream._writableState;
12630 var sync = state.sync;
12631 var cb = state.writecb;
12632
12633 onwriteStateUpdate(state);
12634
12635 if (er) onwriteError(stream, state, sync, er, cb);else {
12636 // Check if we're actually ready to finish, but don't emit yet
12637 var finished = needFinish(state);
12638
12639 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
12640 clearBuffer(stream, state);
12641 }
12642
12643 if (sync) {
12644 /*<replacement>*/
12645 asyncWrite(afterWrite, stream, state, finished, cb);
12646 /*</replacement>*/
12647 } else {
12648 afterWrite(stream, state, finished, cb);
12649 }
12650 }
12651}
12652
12653function afterWrite(stream, state, finished, cb) {
12654 if (!finished) onwriteDrain(stream, state);
12655 state.pendingcb--;
12656 cb();
12657 finishMaybe(stream, state);
12658}
12659
12660// Must force callback to be called on nextTick, so that we don't
12661// emit 'drain' before the write() consumer gets the 'false' return
12662// value, and has a chance to attach a 'drain' listener.
12663function onwriteDrain(stream, state) {
12664 if (state.length === 0 && state.needDrain) {
12665 state.needDrain = false;
12666 stream.emit('drain');
12667 }
12668}
12669
12670// if there's something in the buffer waiting, then process it
12671function clearBuffer(stream, state) {
12672 state.bufferProcessing = true;
12673 var entry = state.bufferedRequest;
12674
12675 if (stream._writev && entry && entry.next) {
12676 // Fast case, write everything using _writev()
12677 var l = state.bufferedRequestCount;
12678 var buffer = new Array(l);
12679 var holder = state.corkedRequestsFree;
12680 holder.entry = entry;
12681
12682 var count = 0;
12683 var allBuffers = true;
12684 while (entry) {
12685 buffer[count] = entry;
12686 if (!entry.isBuf) allBuffers = false;
12687 entry = entry.next;
12688 count += 1;
12689 }
12690 buffer.allBuffers = allBuffers;
12691
12692 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
12693
12694 // doWrite is almost always async, defer these to save a bit of time
12695 // as the hot path ends with doWrite
12696 state.pendingcb++;
12697 state.lastBufferedRequest = null;
12698 if (holder.next) {
12699 state.corkedRequestsFree = holder.next;
12700 holder.next = null;
12701 } else {
12702 state.corkedRequestsFree = new CorkedRequest(state);
12703 }
12704 state.bufferedRequestCount = 0;
12705 } else {
12706 // Slow case, write chunks one-by-one
12707 while (entry) {
12708 var chunk = entry.chunk;
12709 var encoding = entry.encoding;
12710 var cb = entry.callback;
12711 var len = state.objectMode ? 1 : chunk.length;
12712
12713 doWrite(stream, state, false, len, chunk, encoding, cb);
12714 entry = entry.next;
12715 state.bufferedRequestCount--;
12716 // if we didn't call the onwrite immediately, then
12717 // it means that we need to wait until it does.
12718 // also, that means that the chunk and cb are currently
12719 // being processed, so move the buffer counter past them.
12720 if (state.writing) {
12721 break;
12722 }
12723 }
12724
12725 if (entry === null) state.lastBufferedRequest = null;
12726 }
12727
12728 state.bufferedRequest = entry;
12729 state.bufferProcessing = false;
12730}
12731
12732Writable.prototype._write = function (chunk, encoding, cb) {
12733 cb(new Error('_write() is not implemented'));
12734};
12735
12736Writable.prototype._writev = null;
12737
12738Writable.prototype.end = function (chunk, encoding, cb) {
12739 var state = this._writableState;
12740
12741 if (typeof chunk === 'function') {
12742 cb = chunk;
12743 chunk = null;
12744 encoding = null;
12745 } else if (typeof encoding === 'function') {
12746 cb = encoding;
12747 encoding = null;
12748 }
12749
12750 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
12751
12752 // .end() fully uncorks
12753 if (state.corked) {
12754 state.corked = 1;
12755 this.uncork();
12756 }
12757
12758 // ignore unnecessary end() calls.
12759 if (!state.ending && !state.finished) endWritable(this, state, cb);
12760};
12761
12762function needFinish(state) {
12763 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
12764}
12765function callFinal(stream, state) {
12766 stream._final(function (err) {
12767 state.pendingcb--;
12768 if (err) {
12769 stream.emit('error', err);
12770 }
12771 state.prefinished = true;
12772 stream.emit('prefinish');
12773 finishMaybe(stream, state);
12774 });
12775}
12776function prefinish(stream, state) {
12777 if (!state.prefinished && !state.finalCalled) {
12778 if (typeof stream._final === 'function') {
12779 state.pendingcb++;
12780 state.finalCalled = true;
12781 pna.nextTick(callFinal, stream, state);
12782 } else {
12783 state.prefinished = true;
12784 stream.emit('prefinish');
12785 }
12786 }
12787}
12788
12789function finishMaybe(stream, state) {
12790 var need = needFinish(state);
12791 if (need) {
12792 prefinish(stream, state);
12793 if (state.pendingcb === 0) {
12794 state.finished = true;
12795 stream.emit('finish');
12796 }
12797 }
12798 return need;
12799}
12800
12801function endWritable(stream, state, cb) {
12802 state.ending = true;
12803 finishMaybe(stream, state);
12804 if (cb) {
12805 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
12806 }
12807 state.ended = true;
12808 stream.writable = false;
12809}
12810
12811function onCorkedFinish(corkReq, state, err) {
12812 var entry = corkReq.entry;
12813 corkReq.entry = null;
12814 while (entry) {
12815 var cb = entry.callback;
12816 state.pendingcb--;
12817 cb(err);
12818 entry = entry.next;
12819 }
12820 if (state.corkedRequestsFree) {
12821 state.corkedRequestsFree.next = corkReq;
12822 } else {
12823 state.corkedRequestsFree = corkReq;
12824 }
12825}
12826
12827Object.defineProperty(Writable.prototype, 'destroyed', {
12828 get: function () {
12829 if (this._writableState === undefined) {
12830 return false;
12831 }
12832 return this._writableState.destroyed;
12833 },
12834 set: function (value) {
12835 // we ignore the value if the stream
12836 // has not been initialized yet
12837 if (!this._writableState) {
12838 return;
12839 }
12840
12841 // backward compatibility, the user is explicitly
12842 // managing destroyed
12843 this._writableState.destroyed = value;
12844 }
12845});
12846
12847Writable.prototype.destroy = destroyImpl.destroy;
12848Writable.prototype._undestroy = destroyImpl.undestroy;
12849Writable.prototype._destroy = function (err, cb) {
12850 this.end();
12851 cb(err);
12852};
12853}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
12854},{"./_stream_duplex":30,"./internal/streams/destroy":36,"./internal/streams/stream":37,"_process":28,"core-util-is":10,"inherits":13,"process-nextick-args":27,"safe-buffer":42,"timers":45,"util-deprecate":46}],35:[function(require,module,exports){
12855'use strict';
12856
12857function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
12858
12859var Buffer = require('safe-buffer').Buffer;
12860var util = require('util');
12861
12862function copyBuffer(src, target, offset) {
12863 src.copy(target, offset);
12864}
12865
12866module.exports = function () {
12867 function BufferList() {
12868 _classCallCheck(this, BufferList);
12869
12870 this.head = null;
12871 this.tail = null;
12872 this.length = 0;
12873 }
12874
12875 BufferList.prototype.push = function push(v) {
12876 var entry = { data: v, next: null };
12877 if (this.length > 0) this.tail.next = entry;else this.head = entry;
12878 this.tail = entry;
12879 ++this.length;
12880 };
12881
12882 BufferList.prototype.unshift = function unshift(v) {
12883 var entry = { data: v, next: this.head };
12884 if (this.length === 0) this.tail = entry;
12885 this.head = entry;
12886 ++this.length;
12887 };
12888
12889 BufferList.prototype.shift = function shift() {
12890 if (this.length === 0) return;
12891 var ret = this.head.data;
12892 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
12893 --this.length;
12894 return ret;
12895 };
12896
12897 BufferList.prototype.clear = function clear() {
12898 this.head = this.tail = null;
12899 this.length = 0;
12900 };
12901
12902 BufferList.prototype.join = function join(s) {
12903 if (this.length === 0) return '';
12904 var p = this.head;
12905 var ret = '' + p.data;
12906 while (p = p.next) {
12907 ret += s + p.data;
12908 }return ret;
12909 };
12910
12911 BufferList.prototype.concat = function concat(n) {
12912 if (this.length === 0) return Buffer.alloc(0);
12913 if (this.length === 1) return this.head.data;
12914 var ret = Buffer.allocUnsafe(n >>> 0);
12915 var p = this.head;
12916 var i = 0;
12917 while (p) {
12918 copyBuffer(p.data, ret, i);
12919 i += p.data.length;
12920 p = p.next;
12921 }
12922 return ret;
12923 };
12924
12925 return BufferList;
12926}();
12927
12928if (util && util.inspect && util.inspect.custom) {
12929 module.exports.prototype[util.inspect.custom] = function () {
12930 var obj = util.inspect({ length: this.length });
12931 return this.constructor.name + ' ' + obj;
12932 };
12933}
12934},{"safe-buffer":42,"util":6}],36:[function(require,module,exports){
12935'use strict';
12936
12937/*<replacement>*/
12938
12939var pna = require('process-nextick-args');
12940/*</replacement>*/
12941
12942// undocumented cb() API, needed for core, not for public API
12943function destroy(err, cb) {
12944 var _this = this;
12945
12946 var readableDestroyed = this._readableState && this._readableState.destroyed;
12947 var writableDestroyed = this._writableState && this._writableState.destroyed;
12948
12949 if (readableDestroyed || writableDestroyed) {
12950 if (cb) {
12951 cb(err);
12952 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
12953 pna.nextTick(emitErrorNT, this, err);
12954 }
12955 return this;
12956 }
12957
12958 // we set destroyed to true before firing error callbacks in order
12959 // to make it re-entrance safe in case destroy() is called within callbacks
12960
12961 if (this._readableState) {
12962 this._readableState.destroyed = true;
12963 }
12964
12965 // if this is a duplex stream mark the writable part as destroyed as well
12966 if (this._writableState) {
12967 this._writableState.destroyed = true;
12968 }
12969
12970 this._destroy(err || null, function (err) {
12971 if (!cb && err) {
12972 pna.nextTick(emitErrorNT, _this, err);
12973 if (_this._writableState) {
12974 _this._writableState.errorEmitted = true;
12975 }
12976 } else if (cb) {
12977 cb(err);
12978 }
12979 });
12980
12981 return this;
12982}
12983
12984function undestroy() {
12985 if (this._readableState) {
12986 this._readableState.destroyed = false;
12987 this._readableState.reading = false;
12988 this._readableState.ended = false;
12989 this._readableState.endEmitted = false;
12990 }
12991
12992 if (this._writableState) {
12993 this._writableState.destroyed = false;
12994 this._writableState.ended = false;
12995 this._writableState.ending = false;
12996 this._writableState.finished = false;
12997 this._writableState.errorEmitted = false;
12998 }
12999}
13000
13001function emitErrorNT(self, err) {
13002 self.emit('error', err);
13003}
13004
13005module.exports = {
13006 destroy: destroy,
13007 undestroy: undestroy
13008};
13009},{"process-nextick-args":27}],37:[function(require,module,exports){
13010module.exports = require('events').EventEmitter;
13011
13012},{"events":11}],38:[function(require,module,exports){
13013module.exports = require('./readable').PassThrough
13014
13015},{"./readable":39}],39:[function(require,module,exports){
13016exports = module.exports = require('./lib/_stream_readable.js');
13017exports.Stream = exports;
13018exports.Readable = exports;
13019exports.Writable = require('./lib/_stream_writable.js');
13020exports.Duplex = require('./lib/_stream_duplex.js');
13021exports.Transform = require('./lib/_stream_transform.js');
13022exports.PassThrough = require('./lib/_stream_passthrough.js');
13023
13024},{"./lib/_stream_duplex.js":30,"./lib/_stream_passthrough.js":31,"./lib/_stream_readable.js":32,"./lib/_stream_transform.js":33,"./lib/_stream_writable.js":34}],40:[function(require,module,exports){
13025module.exports = require('./readable').Transform
13026
13027},{"./readable":39}],41:[function(require,module,exports){
13028module.exports = require('./lib/_stream_writable.js');
13029
13030},{"./lib/_stream_writable.js":34}],42:[function(require,module,exports){
13031/* eslint-disable node/no-deprecated-api */
13032var buffer = require('buffer')
13033var Buffer = buffer.Buffer
13034
13035// alternative to using Object.keys for old browsers
13036function copyProps (src, dst) {
13037 for (var key in src) {
13038 dst[key] = src[key]
13039 }
13040}
13041if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13042 module.exports = buffer
13043} else {
13044 // Copy properties from require('buffer')
13045 copyProps(buffer, exports)
13046 exports.Buffer = SafeBuffer
13047}
13048
13049function SafeBuffer (arg, encodingOrOffset, length) {
13050 return Buffer(arg, encodingOrOffset, length)
13051}
13052
13053// Copy static methods from Buffer
13054copyProps(Buffer, SafeBuffer)
13055
13056SafeBuffer.from = function (arg, encodingOrOffset, length) {
13057 if (typeof arg === 'number') {
13058 throw new TypeError('Argument must not be a number')
13059 }
13060 return Buffer(arg, encodingOrOffset, length)
13061}
13062
13063SafeBuffer.alloc = function (size, fill, encoding) {
13064 if (typeof size !== 'number') {
13065 throw new TypeError('Argument must be a number')
13066 }
13067 var buf = Buffer(size)
13068 if (fill !== undefined) {
13069 if (typeof encoding === 'string') {
13070 buf.fill(fill, encoding)
13071 } else {
13072 buf.fill(fill)
13073 }
13074 } else {
13075 buf.fill(0)
13076 }
13077 return buf
13078}
13079
13080SafeBuffer.allocUnsafe = function (size) {
13081 if (typeof size !== 'number') {
13082 throw new TypeError('Argument must be a number')
13083 }
13084 return Buffer(size)
13085}
13086
13087SafeBuffer.allocUnsafeSlow = function (size) {
13088 if (typeof size !== 'number') {
13089 throw new TypeError('Argument must be a number')
13090 }
13091 return buffer.SlowBuffer(size)
13092}
13093
13094},{"buffer":9}],43:[function(require,module,exports){
13095// Copyright Joyent, Inc. and other Node contributors.
13096//
13097// Permission is hereby granted, free of charge, to any person obtaining a
13098// copy of this software and associated documentation files (the
13099// "Software"), to deal in the Software without restriction, including
13100// without limitation the rights to use, copy, modify, merge, publish,
13101// distribute, sublicense, and/or sell copies of the Software, and to permit
13102// persons to whom the Software is furnished to do so, subject to the
13103// following conditions:
13104//
13105// The above copyright notice and this permission notice shall be included
13106// in all copies or substantial portions of the Software.
13107//
13108// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13109// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13110// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13111// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13112// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13113// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13114// USE OR OTHER DEALINGS IN THE SOFTWARE.
13115
13116module.exports = Stream;
13117
13118var EE = require('events').EventEmitter;
13119var inherits = require('inherits');
13120
13121inherits(Stream, EE);
13122Stream.Readable = require('readable-stream/readable.js');
13123Stream.Writable = require('readable-stream/writable.js');
13124Stream.Duplex = require('readable-stream/duplex.js');
13125Stream.Transform = require('readable-stream/transform.js');
13126Stream.PassThrough = require('readable-stream/passthrough.js');
13127
13128// Backwards-compat with node 0.4.x
13129Stream.Stream = Stream;
13130
13131
13132
13133// old-style streams. Note that the pipe method (the only relevant
13134// part of this class) is overridden in the Readable class.
13135
13136function Stream() {
13137 EE.call(this);
13138}
13139
13140Stream.prototype.pipe = function(dest, options) {
13141 var source = this;
13142
13143 function ondata(chunk) {
13144 if (dest.writable) {
13145 if (false === dest.write(chunk) && source.pause) {
13146 source.pause();
13147 }
13148 }
13149 }
13150
13151 source.on('data', ondata);
13152
13153 function ondrain() {
13154 if (source.readable && source.resume) {
13155 source.resume();
13156 }
13157 }
13158
13159 dest.on('drain', ondrain);
13160
13161 // If the 'end' option is not supplied, dest.end() will be called when
13162 // source gets the 'end' or 'close' events. Only dest.end() once.
13163 if (!dest._isStdio && (!options || options.end !== false)) {
13164 source.on('end', onend);
13165 source.on('close', onclose);
13166 }
13167
13168 var didOnEnd = false;
13169 function onend() {
13170 if (didOnEnd) return;
13171 didOnEnd = true;
13172
13173 dest.end();
13174 }
13175
13176
13177 function onclose() {
13178 if (didOnEnd) return;
13179 didOnEnd = true;
13180
13181 if (typeof dest.destroy === 'function') dest.destroy();
13182 }
13183
13184 // don't leave dangling pipes when there are errors.
13185 function onerror(er) {
13186 cleanup();
13187 if (EE.listenerCount(this, 'error') === 0) {
13188 throw er; // Unhandled stream error in pipe.
13189 }
13190 }
13191
13192 source.on('error', onerror);
13193 dest.on('error', onerror);
13194
13195 // remove all the event listeners that were added.
13196 function cleanup() {
13197 source.removeListener('data', ondata);
13198 dest.removeListener('drain', ondrain);
13199
13200 source.removeListener('end', onend);
13201 source.removeListener('close', onclose);
13202
13203 source.removeListener('error', onerror);
13204 dest.removeListener('error', onerror);
13205
13206 source.removeListener('end', cleanup);
13207 source.removeListener('close', cleanup);
13208
13209 dest.removeListener('close', cleanup);
13210 }
13211
13212 source.on('end', cleanup);
13213 source.on('close', cleanup);
13214
13215 dest.on('close', cleanup);
13216
13217 dest.emit('pipe', source);
13218
13219 // Allow for unix-like usage: A.pipe(B).pipe(C)
13220 return dest;
13221};
13222
13223},{"events":11,"inherits":13,"readable-stream/duplex.js":29,"readable-stream/passthrough.js":38,"readable-stream/readable.js":39,"readable-stream/transform.js":40,"readable-stream/writable.js":41}],44:[function(require,module,exports){
13224// Copyright Joyent, Inc. and other Node contributors.
13225//
13226// Permission is hereby granted, free of charge, to any person obtaining a
13227// copy of this software and associated documentation files (the
13228// "Software"), to deal in the Software without restriction, including
13229// without limitation the rights to use, copy, modify, merge, publish,
13230// distribute, sublicense, and/or sell copies of the Software, and to permit
13231// persons to whom the Software is furnished to do so, subject to the
13232// following conditions:
13233//
13234// The above copyright notice and this permission notice shall be included
13235// in all copies or substantial portions of the Software.
13236//
13237// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13238// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13239// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13240// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13241// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13242// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13243// USE OR OTHER DEALINGS IN THE SOFTWARE.
13244
13245'use strict';
13246
13247/*<replacement>*/
13248
13249var Buffer = require('safe-buffer').Buffer;
13250/*</replacement>*/
13251
13252var isEncoding = Buffer.isEncoding || function (encoding) {
13253 encoding = '' + encoding;
13254 switch (encoding && encoding.toLowerCase()) {
13255 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':
13256 return true;
13257 default:
13258 return false;
13259 }
13260};
13261
13262function _normalizeEncoding(enc) {
13263 if (!enc) return 'utf8';
13264 var retried;
13265 while (true) {
13266 switch (enc) {
13267 case 'utf8':
13268 case 'utf-8':
13269 return 'utf8';
13270 case 'ucs2':
13271 case 'ucs-2':
13272 case 'utf16le':
13273 case 'utf-16le':
13274 return 'utf16le';
13275 case 'latin1':
13276 case 'binary':
13277 return 'latin1';
13278 case 'base64':
13279 case 'ascii':
13280 case 'hex':
13281 return enc;
13282 default:
13283 if (retried) return; // undefined
13284 enc = ('' + enc).toLowerCase();
13285 retried = true;
13286 }
13287 }
13288};
13289
13290// Do not cache `Buffer.isEncoding` when checking encoding names as some
13291// modules monkey-patch it to support additional encodings
13292function normalizeEncoding(enc) {
13293 var nenc = _normalizeEncoding(enc);
13294 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
13295 return nenc || enc;
13296}
13297
13298// StringDecoder provides an interface for efficiently splitting a series of
13299// buffers into a series of JS strings without breaking apart multi-byte
13300// characters.
13301exports.StringDecoder = StringDecoder;
13302function StringDecoder(encoding) {
13303 this.encoding = normalizeEncoding(encoding);
13304 var nb;
13305 switch (this.encoding) {
13306 case 'utf16le':
13307 this.text = utf16Text;
13308 this.end = utf16End;
13309 nb = 4;
13310 break;
13311 case 'utf8':
13312 this.fillLast = utf8FillLast;
13313 nb = 4;
13314 break;
13315 case 'base64':
13316 this.text = base64Text;
13317 this.end = base64End;
13318 nb = 3;
13319 break;
13320 default:
13321 this.write = simpleWrite;
13322 this.end = simpleEnd;
13323 return;
13324 }
13325 this.lastNeed = 0;
13326 this.lastTotal = 0;
13327 this.lastChar = Buffer.allocUnsafe(nb);
13328}
13329
13330StringDecoder.prototype.write = function (buf) {
13331 if (buf.length === 0) return '';
13332 var r;
13333 var i;
13334 if (this.lastNeed) {
13335 r = this.fillLast(buf);
13336 if (r === undefined) return '';
13337 i = this.lastNeed;
13338 this.lastNeed = 0;
13339 } else {
13340 i = 0;
13341 }
13342 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
13343 return r || '';
13344};
13345
13346StringDecoder.prototype.end = utf8End;
13347
13348// Returns only complete characters in a Buffer
13349StringDecoder.prototype.text = utf8Text;
13350
13351// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
13352StringDecoder.prototype.fillLast = function (buf) {
13353 if (this.lastNeed <= buf.length) {
13354 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
13355 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
13356 }
13357 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
13358 this.lastNeed -= buf.length;
13359};
13360
13361// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
13362// continuation byte. If an invalid byte is detected, -2 is returned.
13363function utf8CheckByte(byte) {
13364 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;
13365 return byte >> 6 === 0x02 ? -1 : -2;
13366}
13367
13368// Checks at most 3 bytes at the end of a Buffer in order to detect an
13369// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
13370// needed to complete the UTF-8 character (if applicable) are returned.
13371function utf8CheckIncomplete(self, buf, i) {
13372 var j = buf.length - 1;
13373 if (j < i) return 0;
13374 var nb = utf8CheckByte(buf[j]);
13375 if (nb >= 0) {
13376 if (nb > 0) self.lastNeed = nb - 1;
13377 return nb;
13378 }
13379 if (--j < i || nb === -2) return 0;
13380 nb = utf8CheckByte(buf[j]);
13381 if (nb >= 0) {
13382 if (nb > 0) self.lastNeed = nb - 2;
13383 return nb;
13384 }
13385 if (--j < i || nb === -2) return 0;
13386 nb = utf8CheckByte(buf[j]);
13387 if (nb >= 0) {
13388 if (nb > 0) {
13389 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
13390 }
13391 return nb;
13392 }
13393 return 0;
13394}
13395
13396// Validates as many continuation bytes for a multi-byte UTF-8 character as
13397// needed or are available. If we see a non-continuation byte where we expect
13398// one, we "replace" the validated continuation bytes we've seen so far with
13399// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
13400// behavior. The continuation byte check is included three times in the case
13401// where all of the continuation bytes for a character exist in the same buffer.
13402// It is also done this way as a slight performance increase instead of using a
13403// loop.
13404function utf8CheckExtraBytes(self, buf, p) {
13405 if ((buf[0] & 0xC0) !== 0x80) {
13406 self.lastNeed = 0;
13407 return '\ufffd';
13408 }
13409 if (self.lastNeed > 1 && buf.length > 1) {
13410 if ((buf[1] & 0xC0) !== 0x80) {
13411 self.lastNeed = 1;
13412 return '\ufffd';
13413 }
13414 if (self.lastNeed > 2 && buf.length > 2) {
13415 if ((buf[2] & 0xC0) !== 0x80) {
13416 self.lastNeed = 2;
13417 return '\ufffd';
13418 }
13419 }
13420 }
13421}
13422
13423// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
13424function utf8FillLast(buf) {
13425 var p = this.lastTotal - this.lastNeed;
13426 var r = utf8CheckExtraBytes(this, buf, p);
13427 if (r !== undefined) return r;
13428 if (this.lastNeed <= buf.length) {
13429 buf.copy(this.lastChar, p, 0, this.lastNeed);
13430 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
13431 }
13432 buf.copy(this.lastChar, p, 0, buf.length);
13433 this.lastNeed -= buf.length;
13434}
13435
13436// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
13437// partial character, the character's bytes are buffered until the required
13438// number of bytes are available.
13439function utf8Text(buf, i) {
13440 var total = utf8CheckIncomplete(this, buf, i);
13441 if (!this.lastNeed) return buf.toString('utf8', i);
13442 this.lastTotal = total;
13443 var end = buf.length - (total - this.lastNeed);
13444 buf.copy(this.lastChar, 0, end);
13445 return buf.toString('utf8', i, end);
13446}
13447
13448// For UTF-8, a replacement character is added when ending on a partial
13449// character.
13450function utf8End(buf) {
13451 var r = buf && buf.length ? this.write(buf) : '';
13452 if (this.lastNeed) return r + '\ufffd';
13453 return r;
13454}
13455
13456// UTF-16LE typically needs two bytes per character, but even if we have an even
13457// number of bytes available, we need to check if we end on a leading/high
13458// surrogate. In that case, we need to wait for the next two bytes in order to
13459// decode the last character properly.
13460function utf16Text(buf, i) {
13461 if ((buf.length - i) % 2 === 0) {
13462 var r = buf.toString('utf16le', i);
13463 if (r) {
13464 var c = r.charCodeAt(r.length - 1);
13465 if (c >= 0xD800 && c <= 0xDBFF) {
13466 this.lastNeed = 2;
13467 this.lastTotal = 4;
13468 this.lastChar[0] = buf[buf.length - 2];
13469 this.lastChar[1] = buf[buf.length - 1];
13470 return r.slice(0, -1);
13471 }
13472 }
13473 return r;
13474 }
13475 this.lastNeed = 1;
13476 this.lastTotal = 2;
13477 this.lastChar[0] = buf[buf.length - 1];
13478 return buf.toString('utf16le', i, buf.length - 1);
13479}
13480
13481// For UTF-16LE we do not explicitly append special replacement characters if we
13482// end on a partial character, we simply let v8 handle that.
13483function utf16End(buf) {
13484 var r = buf && buf.length ? this.write(buf) : '';
13485 if (this.lastNeed) {
13486 var end = this.lastTotal - this.lastNeed;
13487 return r + this.lastChar.toString('utf16le', 0, end);
13488 }
13489 return r;
13490}
13491
13492function base64Text(buf, i) {
13493 var n = (buf.length - i) % 3;
13494 if (n === 0) return buf.toString('base64', i);
13495 this.lastNeed = 3 - n;
13496 this.lastTotal = 3;
13497 if (n === 1) {
13498 this.lastChar[0] = buf[buf.length - 1];
13499 } else {
13500 this.lastChar[0] = buf[buf.length - 2];
13501 this.lastChar[1] = buf[buf.length - 1];
13502 }
13503 return buf.toString('base64', i, buf.length - n);
13504}
13505
13506function base64End(buf) {
13507 var r = buf && buf.length ? this.write(buf) : '';
13508 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
13509 return r;
13510}
13511
13512// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
13513function simpleWrite(buf) {
13514 return buf.toString(this.encoding);
13515}
13516
13517function simpleEnd(buf) {
13518 return buf && buf.length ? this.write(buf) : '';
13519}
13520},{"safe-buffer":42}],45:[function(require,module,exports){
13521(function (setImmediate,clearImmediate){
13522var nextTick = require('process/browser.js').nextTick;
13523var apply = Function.prototype.apply;
13524var slice = Array.prototype.slice;
13525var immediateIds = {};
13526var nextImmediateId = 0;
13527
13528// DOM APIs, for completeness
13529
13530exports.setTimeout = function() {
13531 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
13532};
13533exports.setInterval = function() {
13534 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
13535};
13536exports.clearTimeout =
13537exports.clearInterval = function(timeout) { timeout.close(); };
13538
13539function Timeout(id, clearFn) {
13540 this._id = id;
13541 this._clearFn = clearFn;
13542}
13543Timeout.prototype.unref = Timeout.prototype.ref = function() {};
13544Timeout.prototype.close = function() {
13545 this._clearFn.call(window, this._id);
13546};
13547
13548// Does not start the time, just sets up the members needed.
13549exports.enroll = function(item, msecs) {
13550 clearTimeout(item._idleTimeoutId);
13551 item._idleTimeout = msecs;
13552};
13553
13554exports.unenroll = function(item) {
13555 clearTimeout(item._idleTimeoutId);
13556 item._idleTimeout = -1;
13557};
13558
13559exports._unrefActive = exports.active = function(item) {
13560 clearTimeout(item._idleTimeoutId);
13561
13562 var msecs = item._idleTimeout;
13563 if (msecs >= 0) {
13564 item._idleTimeoutId = setTimeout(function onTimeout() {
13565 if (item._onTimeout)
13566 item._onTimeout();
13567 }, msecs);
13568 }
13569};
13570
13571// That's not how node.js implements it but the exposed api is the same.
13572exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
13573 var id = nextImmediateId++;
13574 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
13575
13576 immediateIds[id] = true;
13577
13578 nextTick(function onNextTick() {
13579 if (immediateIds[id]) {
13580 // fn.call() is faster so we optimize for the common use-case
13581 // @see http://jsperf.com/call-apply-segu
13582 if (args) {
13583 fn.apply(null, args);
13584 } else {
13585 fn.call(null);
13586 }
13587 // Prevent ids from leaking
13588 exports.clearImmediate(id);
13589 }
13590 });
13591
13592 return id;
13593};
13594
13595exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
13596 delete immediateIds[id];
13597};
13598}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
13599},{"process/browser.js":28,"timers":45}],46:[function(require,module,exports){
13600(function (global){
13601
13602/**
13603 * Module exports.
13604 */
13605
13606module.exports = deprecate;
13607
13608/**
13609 * Mark that a method should not be used.
13610 * Returns a modified function which warns once by default.
13611 *
13612 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
13613 *
13614 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
13615 * will throw an Error when invoked.
13616 *
13617 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
13618 * will invoke `console.trace()` instead of `console.error()`.
13619 *
13620 * @param {Function} fn - the function to deprecate
13621 * @param {String} msg - the string to print to the console when `fn` is invoked
13622 * @returns {Function} a new "deprecated" version of `fn`
13623 * @api public
13624 */
13625
13626function deprecate (fn, msg) {
13627 if (config('noDeprecation')) {
13628 return fn;
13629 }
13630
13631 var warned = false;
13632 function deprecated() {
13633 if (!warned) {
13634 if (config('throwDeprecation')) {
13635 throw new Error(msg);
13636 } else if (config('traceDeprecation')) {
13637 console.trace(msg);
13638 } else {
13639 console.warn(msg);
13640 }
13641 warned = true;
13642 }
13643 return fn.apply(this, arguments);
13644 }
13645
13646 return deprecated;
13647}
13648
13649/**
13650 * Checks `localStorage` for boolean values for the given `name`.
13651 *
13652 * @param {String} name
13653 * @returns {Boolean}
13654 * @api private
13655 */
13656
13657function config (name) {
13658 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
13659 try {
13660 if (!global.localStorage) return false;
13661 } catch (_) {
13662 return false;
13663 }
13664 var val = global.localStorage[name];
13665 if (null == val) return false;
13666 return String(val).toLowerCase() === 'true';
13667}
13668
13669}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13670},{}],47:[function(require,module,exports){
13671arguments[4][3][0].apply(exports,arguments)
13672},{"dup":3}],48:[function(require,module,exports){
13673arguments[4][4][0].apply(exports,arguments)
13674},{"./support/isBuffer":47,"_process":28,"dup":4,"inherits":13}],49:[function(require,module,exports){
13675(function (Buffer){
13676'use strict';
13677
13678var interlaceUtils = require('./interlace');
13679
13680var pixelBppMap = {
13681 1: { // L
13682 0: 0,
13683 1: 0,
13684 2: 0,
13685 3: 0xff
13686 },
13687 2: { // LA
13688 0: 0,
13689 1: 0,
13690 2: 0,
13691 3: 1
13692 },
13693 3: { // RGB
13694 0: 0,
13695 1: 1,
13696 2: 2,
13697 3: 0xff
13698 },
13699 4: { // RGBA
13700 0: 0,
13701 1: 1,
13702 2: 2,
13703 3: 3
13704 }
13705};
13706
13707function bitRetriever(data, depth) {
13708
13709 var leftOver = [];
13710 var i = 0;
13711
13712 function split() {
13713 if (i === data.length) {
13714 throw new Error('Ran out of data');
13715 }
13716 var byte = data[i];
13717 i++;
13718 var byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
13719 switch (depth) {
13720 default:
13721 throw new Error('unrecognised depth');
13722 case 16:
13723 byte2 = data[i];
13724 i++;
13725 leftOver.push(((byte << 8) + byte2));
13726 break;
13727 case 4:
13728 byte2 = byte & 0x0f;
13729 byte1 = byte >> 4;
13730 leftOver.push(byte1, byte2);
13731 break;
13732 case 2:
13733 byte4 = byte & 3;
13734 byte3 = byte >> 2 & 3;
13735 byte2 = byte >> 4 & 3;
13736 byte1 = byte >> 6 & 3;
13737 leftOver.push(byte1, byte2, byte3, byte4);
13738 break;
13739 case 1:
13740 byte8 = byte & 1;
13741 byte7 = byte >> 1 & 1;
13742 byte6 = byte >> 2 & 1;
13743 byte5 = byte >> 3 & 1;
13744 byte4 = byte >> 4 & 1;
13745 byte3 = byte >> 5 & 1;
13746 byte2 = byte >> 6 & 1;
13747 byte1 = byte >> 7 & 1;
13748 leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
13749 break;
13750 }
13751 }
13752
13753 return {
13754 get: function(count) {
13755 while (leftOver.length < count) {
13756 split();
13757 }
13758 var returner = leftOver.slice(0, count);
13759 leftOver = leftOver.slice(count);
13760 return returner;
13761 },
13762 resetAfterLine: function() {
13763 leftOver.length = 0;
13764 },
13765 end: function() {
13766 if (i !== data.length) {
13767 throw new Error('extra data found');
13768 }
13769 }
13770 };
13771}
13772
13773function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { // eslint-disable-line max-params
13774 var imageWidth = image.width;
13775 var imageHeight = image.height;
13776 var imagePass = image.index;
13777 for (var y = 0; y < imageHeight; y++) {
13778 for (var x = 0; x < imageWidth; x++) {
13779 var pxPos = getPxPos(x, y, imagePass);
13780
13781 for (var i = 0; i < 4; i++) {
13782 var idx = pixelBppMap[bpp][i];
13783 if (idx === 0xff) {
13784 pxData[pxPos + i] = 0xff;
13785 } else {
13786 var dataPos = idx + rawPos;
13787 if (dataPos === data.length) {
13788 throw new Error('Ran out of data');
13789 }
13790 pxData[pxPos + i] = data[dataPos];
13791 }
13792 }
13793 rawPos += bpp; //eslint-disable-line no-param-reassign
13794 }
13795 }
13796 return rawPos;
13797}
13798
13799function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { // eslint-disable-line max-params
13800 var imageWidth = image.width;
13801 var imageHeight = image.height;
13802 var imagePass = image.index;
13803 for (var y = 0; y < imageHeight; y++) {
13804 for (var x = 0; x < imageWidth; x++) {
13805 var pixelData = bits.get(bpp);
13806 var pxPos = getPxPos(x, y, imagePass);
13807
13808 for (var i = 0; i < 4; i++) {
13809 var idx = pixelBppMap[bpp][i];
13810 pxData[pxPos + i] = idx !== 0xff ? pixelData[idx] : maxBit;
13811 }
13812 }
13813 bits.resetAfterLine();
13814 }
13815}
13816
13817exports.dataToBitMap = function(data, bitmapInfo) {
13818
13819 var width = bitmapInfo.width;
13820 var height = bitmapInfo.height;
13821 var depth = bitmapInfo.depth;
13822 var bpp = bitmapInfo.bpp;
13823 var interlace = bitmapInfo.interlace;
13824
13825 if (depth !== 8) {
13826 var bits = bitRetriever(data, depth);
13827 }
13828 var pxData;
13829 if (depth <= 8) {
13830 pxData = new Buffer(width * height * 4);
13831 }
13832 else {
13833 pxData = new Uint16Array(width * height * 4);
13834 }
13835 var maxBit = Math.pow(2, depth) - 1;
13836 var rawPos = 0;
13837 var images;
13838 var getPxPos;
13839
13840 if (interlace) {
13841 images = interlaceUtils.getImagePasses(width, height);
13842 getPxPos = interlaceUtils.getInterlaceIterator(width, height);
13843 }
13844 else {
13845 var nonInterlacedPxPos = 0;
13846 getPxPos = function() {
13847 var returner = nonInterlacedPxPos;
13848 nonInterlacedPxPos += 4;
13849 return returner;
13850 };
13851 images = [{ width: width, height: height }];
13852 }
13853
13854 for (var imageIndex = 0; imageIndex < images.length; imageIndex++) {
13855 if (depth === 8) {
13856 rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos);
13857 }
13858 else {
13859 mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit);
13860 }
13861 }
13862 if (depth === 8) {
13863 if (rawPos !== data.length) {
13864 throw new Error('extra data found');
13865 }
13866 }
13867 else {
13868 bits.end();
13869 }
13870
13871 return pxData;
13872};
13873
13874}).call(this,require("buffer").Buffer)
13875},{"./interlace":59,"buffer":9}],50:[function(require,module,exports){
13876(function (Buffer){
13877'use strict';
13878
13879var constants = require('./constants');
13880
13881module.exports = function(dataIn, width, height, options) {
13882 var outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1;
13883 if (options.colorType === options.inputColorType) {
13884 var bigEndian = (function() {
13885 var buffer = new ArrayBuffer(2);
13886 new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
13887 // Int16Array uses the platform's endianness.
13888 return new Int16Array(buffer)[0] !== 256;
13889 })();
13890 // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
13891 if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)){
13892 return dataIn;
13893 }
13894 }
13895
13896 // map to a UInt16 array if data is 16bit, fix endianness below
13897 var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
13898
13899 var maxValue = 255;
13900 var inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
13901 if (inBpp == 4 && !options.inputHasAlpha) inBpp = 3;
13902 var outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
13903 if (options.bitDepth === 16) {
13904 maxValue = 65535;
13905 outBpp *= 2;
13906 }
13907 var outData = new Buffer(width * height * outBpp);
13908
13909 var inIndex = 0;
13910 var outIndex = 0;
13911
13912 var bgColor = options.bgColor || {};
13913 if (bgColor.red === undefined) {
13914 bgColor.red = maxValue;
13915 }
13916 if (bgColor.green === undefined) {
13917 bgColor.green = maxValue;
13918 }
13919 if (bgColor.blue === undefined) {
13920 bgColor.blue = maxValue;
13921 }
13922
13923 function getRGBA(data, inIndex) {
13924 var red, green, blue, alpha = maxValue;
13925 switch (options.inputColorType) {
13926 case constants.COLORTYPE_COLOR_ALPHA:
13927 alpha = data[inIndex + 3];
13928 red = data[inIndex];
13929 green = data[inIndex+1];
13930 blue = data[inIndex+2];
13931 break;
13932 case constants.COLORTYPE_COLOR:
13933 red = data[inIndex];
13934 green = data[inIndex+1];
13935 blue = data[inIndex+2];
13936 break;
13937 case constants.COLORTYPE_ALPHA:
13938 alpha = data[inIndex + 1];
13939 red = data[inIndex];
13940 green = red;
13941 blue = red;
13942 break;
13943 case constants.COLORTYPE_GRAYSCALE:
13944 red = data[inIndex];
13945 green = red;
13946 blue = red;
13947 break;
13948 default:
13949 throw new Error('input color type:' + options.inputColorType + ' is not supported at present');
13950 }
13951
13952 if (options.inputHasAlpha) {
13953 if (!outHasAlpha) {
13954 alpha /= maxValue;
13955 red = Math.min(Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue);
13956 green = Math.min(Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue);
13957 blue = Math.min(Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue);
13958 }
13959 }
13960 return {red: red, green: green, blue: blue, alpha: alpha};
13961 }
13962
13963 for (var y = 0; y < height; y++) {
13964 for (var x = 0; x < width; x++) {
13965 var rgba = getRGBA(data, inIndex);
13966
13967 switch (options.colorType) {
13968 case constants.COLORTYPE_COLOR_ALPHA:
13969 case constants.COLORTYPE_COLOR:
13970 if (options.bitDepth === 8) {
13971 outData[outIndex] = rgba.red;
13972 outData[outIndex + 1] = rgba.green;
13973 outData[outIndex + 2] = rgba.blue;
13974 if (outHasAlpha) {
13975 outData[outIndex + 3] = rgba.alpha;
13976 }
13977 } else {
13978 outData.writeUInt16BE(rgba.red, outIndex);
13979 outData.writeUInt16BE(rgba.green, outIndex + 2);
13980 outData.writeUInt16BE(rgba.blue, outIndex + 4);
13981 if (outHasAlpha) {
13982 outData.writeUInt16BE(rgba.alpha, outIndex + 6);
13983 }
13984 }
13985 break;
13986 case constants.COLORTYPE_ALPHA:
13987 case constants.COLORTYPE_GRAYSCALE:
13988 // Convert to grayscale and alpha
13989 var grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
13990 if (options.bitDepth === 8) {
13991 outData[outIndex] = grayscale;
13992 if (outHasAlpha) {
13993 outData[outIndex + 1] = rgba.alpha;
13994 }
13995 } else {
13996 outData.writeUInt16BE(grayscale, outIndex);
13997 if (outHasAlpha) {
13998 outData.writeUInt16BE(rgba.alpha, outIndex + 2);
13999 }
14000 }
14001 break;
14002 }
14003
14004 inIndex += inBpp;
14005 outIndex += outBpp;
14006 }
14007 }
14008
14009 return outData;
14010};
14011
14012}).call(this,require("buffer").Buffer)
14013},{"./constants":52,"buffer":9}],51:[function(require,module,exports){
14014(function (process,Buffer){
14015'use strict';
14016
14017
14018var util = require('util');
14019var Stream = require('stream');
14020
14021
14022var ChunkStream = module.exports = function() {
14023 Stream.call(this);
14024
14025 this._buffers = [];
14026 this._buffered = 0;
14027
14028 this._reads = [];
14029 this._paused = false;
14030
14031 this._encoding = 'utf8';
14032 this.writable = true;
14033};
14034util.inherits(ChunkStream, Stream);
14035
14036
14037ChunkStream.prototype.read = function(length, callback) {
14038
14039 this._reads.push({
14040 length: Math.abs(length), // if length < 0 then at most this length
14041 allowLess: length < 0,
14042 func: callback
14043 });
14044
14045 process.nextTick(function() {
14046 this._process();
14047
14048 // its paused and there is not enought data then ask for more
14049 if (this._paused && this._reads.length > 0) {
14050 this._paused = false;
14051
14052 this.emit('drain');
14053 }
14054 }.bind(this));
14055};
14056
14057ChunkStream.prototype.write = function(data, encoding) {
14058
14059 if (!this.writable) {
14060 this.emit('error', new Error('Stream not writable'));
14061 return false;
14062 }
14063
14064 var dataBuffer;
14065 if (Buffer.isBuffer(data)) {
14066 dataBuffer = data;
14067 }
14068 else {
14069 dataBuffer = new Buffer(data, encoding || this._encoding);
14070 }
14071
14072 this._buffers.push(dataBuffer);
14073 this._buffered += dataBuffer.length;
14074
14075 this._process();
14076
14077 // ok if there are no more read requests
14078 if (this._reads && this._reads.length === 0) {
14079 this._paused = true;
14080 }
14081
14082 return this.writable && !this._paused;
14083};
14084
14085ChunkStream.prototype.end = function(data, encoding) {
14086
14087 if (data) {
14088 this.write(data, encoding);
14089 }
14090
14091 this.writable = false;
14092
14093 // already destroyed
14094 if (!this._buffers) {
14095 return;
14096 }
14097
14098 // enqueue or handle end
14099 if (this._buffers.length === 0) {
14100 this._end();
14101 }
14102 else {
14103 this._buffers.push(null);
14104 this._process();
14105 }
14106};
14107
14108ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
14109
14110ChunkStream.prototype._end = function() {
14111
14112 if (this._reads.length > 0) {
14113 this.emit('error',
14114 new Error('There are some read requests waiting on finished stream')
14115 );
14116 }
14117
14118 this.destroy();
14119};
14120
14121ChunkStream.prototype.destroy = function() {
14122
14123 if (!this._buffers) {
14124 return;
14125 }
14126
14127 this.writable = false;
14128 this._reads = null;
14129 this._buffers = null;
14130
14131 this.emit('close');
14132};
14133
14134ChunkStream.prototype._processReadAllowingLess = function(read) {
14135 // ok there is any data so that we can satisfy this request
14136 this._reads.shift(); // == read
14137
14138 // first we need to peek into first buffer
14139 var smallerBuf = this._buffers[0];
14140
14141 // ok there is more data than we need
14142 if (smallerBuf.length > read.length) {
14143
14144 this._buffered -= read.length;
14145 this._buffers[0] = smallerBuf.slice(read.length);
14146
14147 read.func.call(this, smallerBuf.slice(0, read.length));
14148
14149 }
14150 else {
14151 // ok this is less than maximum length so use it all
14152 this._buffered -= smallerBuf.length;
14153 this._buffers.shift(); // == smallerBuf
14154
14155 read.func.call(this, smallerBuf);
14156 }
14157};
14158
14159ChunkStream.prototype._processRead = function(read) {
14160 this._reads.shift(); // == read
14161
14162 var pos = 0;
14163 var count = 0;
14164 var data = new Buffer(read.length);
14165
14166 // create buffer for all data
14167 while (pos < read.length) {
14168
14169 var buf = this._buffers[count++];
14170 var len = Math.min(buf.length, read.length - pos);
14171
14172 buf.copy(data, pos, 0, len);
14173 pos += len;
14174
14175 // last buffer wasn't used all so just slice it and leave
14176 if (len !== buf.length) {
14177 this._buffers[--count] = buf.slice(len);
14178 }
14179 }
14180
14181 // remove all used buffers
14182 if (count > 0) {
14183 this._buffers.splice(0, count);
14184 }
14185
14186 this._buffered -= read.length;
14187
14188 read.func.call(this, data);
14189};
14190
14191ChunkStream.prototype._process = function() {
14192
14193 try {
14194 // as long as there is any data and read requests
14195 while (this._buffered > 0 && this._reads && this._reads.length > 0) {
14196
14197 var read = this._reads[0];
14198
14199 // read any data (but no more than length)
14200 if (read.allowLess) {
14201 this._processReadAllowingLess(read);
14202
14203 }
14204 else if (this._buffered >= read.length) {
14205 // ok we can meet some expectations
14206
14207 this._processRead(read);
14208 }
14209 else {
14210 // not enought data to satisfy first request in queue
14211 // so we need to wait for more
14212 break;
14213 }
14214 }
14215
14216 if (this._buffers && this._buffers.length > 0 && this._buffers[0] === null) {
14217 this._end();
14218 }
14219 }
14220 catch (ex) {
14221 this.emit('error', ex);
14222 }
14223};
14224
14225}).call(this,require('_process'),require("buffer").Buffer)
14226},{"_process":28,"buffer":9,"stream":43,"util":48}],52:[function(require,module,exports){
14227'use strict';
14228
14229
14230module.exports = {
14231
14232 PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
14233
14234 TYPE_IHDR: 0x49484452,
14235 TYPE_IEND: 0x49454e44,
14236 TYPE_IDAT: 0x49444154,
14237 TYPE_PLTE: 0x504c5445,
14238 TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
14239 TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
14240
14241 // color-type bits
14242 COLORTYPE_GRAYSCALE: 0,
14243 COLORTYPE_PALETTE: 1,
14244 COLORTYPE_COLOR: 2,
14245 COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
14246
14247 // color-type combinations
14248 COLORTYPE_PALETTE_COLOR: 3,
14249 COLORTYPE_COLOR_ALPHA: 6,
14250
14251 COLORTYPE_TO_BPP_MAP: {
14252 0: 1,
14253 2: 3,
14254 3: 1,
14255 4: 2,
14256 6: 4
14257 },
14258
14259 GAMMA_DIVISION: 100000
14260};
14261
14262},{}],53:[function(require,module,exports){
14263'use strict';
14264
14265var crcTable = [];
14266
14267(function() {
14268 for (var i = 0; i < 256; i++) {
14269 var currentCrc = i;
14270 for (var j = 0; j < 8; j++) {
14271 if (currentCrc & 1) {
14272 currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
14273 }
14274 else {
14275 currentCrc = currentCrc >>> 1;
14276 }
14277 }
14278 crcTable[i] = currentCrc;
14279 }
14280}());
14281
14282var CrcCalculator = module.exports = function() {
14283 this._crc = -1;
14284};
14285
14286CrcCalculator.prototype.write = function(data) {
14287
14288 for (var i = 0; i < data.length; i++) {
14289 this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
14290 }
14291 return true;
14292};
14293
14294CrcCalculator.prototype.crc32 = function() {
14295 return this._crc ^ -1;
14296};
14297
14298
14299CrcCalculator.crc32 = function(buf) {
14300
14301 var crc = -1;
14302 for (var i = 0; i < buf.length; i++) {
14303 crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
14304 }
14305 return crc ^ -1;
14306};
14307
14308},{}],54:[function(require,module,exports){
14309(function (Buffer){
14310'use strict';
14311
14312var paethPredictor = require('./paeth-predictor');
14313
14314function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
14315
14316 for (var x = 0; x < byteWidth; x++) {
14317 rawData[rawPos + x] = pxData[pxPos + x];
14318 }
14319}
14320
14321function filterSumNone(pxData, pxPos, byteWidth) {
14322
14323 var sum = 0;
14324 var length = pxPos + byteWidth;
14325
14326 for (var i = pxPos; i < length; i++) {
14327 sum += Math.abs(pxData[i]);
14328 }
14329 return sum;
14330}
14331
14332function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
14333
14334 for (var x = 0; x < byteWidth; x++) {
14335
14336 var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
14337 var val = pxData[pxPos + x] - left;
14338
14339 rawData[rawPos + x] = val;
14340 }
14341}
14342
14343function filterSumSub(pxData, pxPos, byteWidth, bpp) {
14344
14345 var sum = 0;
14346 for (var x = 0; x < byteWidth; x++) {
14347
14348 var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
14349 var val = pxData[pxPos + x] - left;
14350
14351 sum += Math.abs(val);
14352 }
14353
14354 return sum;
14355}
14356
14357function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
14358
14359 for (var x = 0; x < byteWidth; x++) {
14360
14361 var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
14362 var val = pxData[pxPos + x] - up;
14363
14364 rawData[rawPos + x] = val;
14365 }
14366}
14367
14368function filterSumUp(pxData, pxPos, byteWidth) {
14369
14370 var sum = 0;
14371 var length = pxPos + byteWidth;
14372 for (var x = pxPos; x < length; x++) {
14373
14374 var up = pxPos > 0 ? pxData[x - byteWidth] : 0;
14375 var val = pxData[x] - up;
14376
14377 sum += Math.abs(val);
14378 }
14379
14380 return sum;
14381}
14382
14383function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
14384
14385 for (var x = 0; x < byteWidth; x++) {
14386
14387 var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
14388 var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
14389 var val = pxData[pxPos + x] - ((left + up) >> 1);
14390
14391 rawData[rawPos + x] = val;
14392 }
14393}
14394
14395function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
14396
14397 var sum = 0;
14398 for (var x = 0; x < byteWidth; x++) {
14399
14400 var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
14401 var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
14402 var val = pxData[pxPos + x] - ((left + up) >> 1);
14403
14404 sum += Math.abs(val);
14405 }
14406
14407 return sum;
14408}
14409
14410function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
14411
14412 for (var x = 0; x < byteWidth; x++) {
14413
14414 var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
14415 var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
14416 var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
14417 var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
14418
14419 rawData[rawPos + x] = val;
14420 }
14421}
14422
14423function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
14424 var sum = 0;
14425 for (var x = 0; x < byteWidth; x++) {
14426
14427 var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
14428 var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
14429 var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
14430 var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
14431
14432 sum += Math.abs(val);
14433 }
14434
14435 return sum;
14436}
14437
14438var filters = {
14439 0: filterNone,
14440 1: filterSub,
14441 2: filterUp,
14442 3: filterAvg,
14443 4: filterPaeth
14444};
14445
14446var filterSums = {
14447 0: filterSumNone,
14448 1: filterSumSub,
14449 2: filterSumUp,
14450 3: filterSumAvg,
14451 4: filterSumPaeth
14452};
14453
14454module.exports = function(pxData, width, height, options, bpp) {
14455
14456 var filterTypes;
14457 if (!('filterType' in options) || options.filterType === -1) {
14458 filterTypes = [0, 1, 2, 3, 4];
14459 }
14460 else if (typeof options.filterType === 'number') {
14461 filterTypes = [options.filterType];
14462 }
14463 else {
14464 throw new Error('unrecognised filter types');
14465 }
14466
14467 if (options.bitDepth === 16) bpp *= 2;
14468 var byteWidth = width * bpp;
14469 var rawPos = 0;
14470 var pxPos = 0;
14471 var rawData = new Buffer((byteWidth + 1) * height);
14472
14473 var sel = filterTypes[0];
14474
14475 for (var y = 0; y < height; y++) {
14476
14477 if (filterTypes.length > 1) {
14478 // find best filter for this line (with lowest sum of values)
14479 var min = Infinity;
14480
14481 for (var i = 0; i < filterTypes.length; i++) {
14482 var sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
14483 if (sum < min) {
14484 sel = filterTypes[i];
14485 min = sum;
14486 }
14487 }
14488 }
14489
14490 rawData[rawPos] = sel;
14491 rawPos++;
14492 filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
14493 rawPos += byteWidth;
14494 pxPos += byteWidth;
14495 }
14496 return rawData;
14497};
14498
14499}).call(this,require("buffer").Buffer)
14500},{"./paeth-predictor":63,"buffer":9}],55:[function(require,module,exports){
14501(function (Buffer){
14502'use strict';
14503
14504var util = require('util');
14505var ChunkStream = require('./chunkstream');
14506var Filter = require('./filter-parse');
14507
14508
14509var FilterAsync = module.exports = function(bitmapInfo) {
14510 ChunkStream.call(this);
14511
14512 var buffers = [];
14513 var that = this;
14514 this._filter = new Filter(bitmapInfo, {
14515 read: this.read.bind(this),
14516 write: function(buffer) {
14517 buffers.push(buffer);
14518 },
14519 complete: function() {
14520 that.emit('complete', Buffer.concat(buffers));
14521 }
14522 });
14523
14524 this._filter.start();
14525};
14526util.inherits(FilterAsync, ChunkStream);
14527
14528}).call(this,require("buffer").Buffer)
14529},{"./chunkstream":51,"./filter-parse":57,"buffer":9,"util":48}],56:[function(require,module,exports){
14530(function (Buffer){
14531'use strict';
14532
14533var SyncReader = require('./sync-reader');
14534var Filter = require('./filter-parse');
14535
14536
14537exports.process = function(inBuffer, bitmapInfo) {
14538
14539 var outBuffers = [];
14540 var reader = new SyncReader(inBuffer);
14541 var filter = new Filter(bitmapInfo, {
14542 read: reader.read.bind(reader),
14543 write: function(bufferPart) {
14544 outBuffers.push(bufferPart);
14545 },
14546 complete: function() {
14547 }
14548 });
14549
14550 filter.start();
14551 reader.process();
14552
14553 return Buffer.concat(outBuffers);
14554};
14555}).call(this,require("buffer").Buffer)
14556},{"./filter-parse":57,"./sync-reader":70,"buffer":9}],57:[function(require,module,exports){
14557(function (Buffer){
14558'use strict';
14559
14560var interlaceUtils = require('./interlace');
14561var paethPredictor = require('./paeth-predictor');
14562
14563function getByteWidth(width, bpp, depth) {
14564 var byteWidth = width * bpp;
14565 if (depth !== 8) {
14566 byteWidth = Math.ceil(byteWidth / (8 / depth));
14567 }
14568 return byteWidth;
14569}
14570
14571var Filter = module.exports = function(bitmapInfo, dependencies) {
14572
14573 var width = bitmapInfo.width;
14574 var height = bitmapInfo.height;
14575 var interlace = bitmapInfo.interlace;
14576 var bpp = bitmapInfo.bpp;
14577 var depth = bitmapInfo.depth;
14578
14579 this.read = dependencies.read;
14580 this.write = dependencies.write;
14581 this.complete = dependencies.complete;
14582
14583 this._imageIndex = 0;
14584 this._images = [];
14585 if (interlace) {
14586 var passes = interlaceUtils.getImagePasses(width, height);
14587 for (var i = 0; i < passes.length; i++) {
14588 this._images.push({
14589 byteWidth: getByteWidth(passes[i].width, bpp, depth),
14590 height: passes[i].height,
14591 lineIndex: 0
14592 });
14593 }
14594 }
14595 else {
14596 this._images.push({
14597 byteWidth: getByteWidth(width, bpp, depth),
14598 height: height,
14599 lineIndex: 0
14600 });
14601 }
14602
14603 // when filtering the line we look at the pixel to the left
14604 // the spec also says it is done on a byte level regardless of the number of pixels
14605 // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
14606 // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
14607 if (depth === 8) {
14608 this._xComparison = bpp;
14609 }
14610 else if (depth === 16) {
14611 this._xComparison = bpp * 2;
14612 }
14613 else {
14614 this._xComparison = 1;
14615 }
14616};
14617
14618Filter.prototype.start = function() {
14619 this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
14620};
14621
14622Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
14623
14624 var xComparison = this._xComparison;
14625 var xBiggerThan = xComparison - 1;
14626
14627 for (var x = 0; x < byteWidth; x++) {
14628 var rawByte = rawData[1 + x];
14629 var f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
14630 unfilteredLine[x] = rawByte + f1Left;
14631 }
14632};
14633
14634Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
14635
14636 var lastLine = this._lastLine;
14637
14638 for (var x = 0; x < byteWidth; x++) {
14639 var rawByte = rawData[1 + x];
14640 var f2Up = lastLine ? lastLine[x] : 0;
14641 unfilteredLine[x] = rawByte + f2Up;
14642 }
14643};
14644
14645Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
14646
14647 var xComparison = this._xComparison;
14648 var xBiggerThan = xComparison - 1;
14649 var lastLine = this._lastLine;
14650
14651 for (var x = 0; x < byteWidth; x++) {
14652 var rawByte = rawData[1 + x];
14653 var f3Up = lastLine ? lastLine[x] : 0;
14654 var f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
14655 var f3Add = Math.floor((f3Left + f3Up) / 2);
14656 unfilteredLine[x] = rawByte + f3Add;
14657 }
14658};
14659
14660Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
14661
14662 var xComparison = this._xComparison;
14663 var xBiggerThan = xComparison - 1;
14664 var lastLine = this._lastLine;
14665
14666 for (var x = 0; x < byteWidth; x++) {
14667 var rawByte = rawData[1 + x];
14668 var f4Up = lastLine ? lastLine[x] : 0;
14669 var f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
14670 var f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
14671 var f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
14672 unfilteredLine[x] = rawByte + f4Add;
14673 }
14674};
14675
14676Filter.prototype._reverseFilterLine = function(rawData) {
14677
14678 var filter = rawData[0];
14679 var unfilteredLine;
14680 var currentImage = this._images[this._imageIndex];
14681 var byteWidth = currentImage.byteWidth;
14682
14683 if (filter === 0) {
14684 unfilteredLine = rawData.slice(1, byteWidth + 1);
14685 }
14686 else {
14687
14688 unfilteredLine = new Buffer(byteWidth);
14689
14690 switch (filter) {
14691 case 1:
14692 this._unFilterType1(rawData, unfilteredLine, byteWidth);
14693 break;
14694 case 2:
14695 this._unFilterType2(rawData, unfilteredLine, byteWidth);
14696 break;
14697 case 3:
14698 this._unFilterType3(rawData, unfilteredLine, byteWidth);
14699 break;
14700 case 4:
14701 this._unFilterType4(rawData, unfilteredLine, byteWidth);
14702 break;
14703 default:
14704 throw new Error('Unrecognised filter type - ' + filter);
14705 }
14706 }
14707
14708 this.write(unfilteredLine);
14709
14710 currentImage.lineIndex++;
14711 if (currentImage.lineIndex >= currentImage.height) {
14712 this._lastLine = null;
14713 this._imageIndex++;
14714 currentImage = this._images[this._imageIndex];
14715 }
14716 else {
14717 this._lastLine = unfilteredLine;
14718 }
14719
14720 if (currentImage) {
14721 // read, using the byte width that may be from the new current image
14722 this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
14723 }
14724 else {
14725 this._lastLine = null;
14726 this.complete();
14727 }
14728};
14729
14730}).call(this,require("buffer").Buffer)
14731},{"./interlace":59,"./paeth-predictor":63,"buffer":9}],58:[function(require,module,exports){
14732(function (Buffer){
14733'use strict';
14734
14735function dePalette(indata, outdata, width, height, palette) {
14736 var pxPos = 0;
14737 // use values from palette
14738 for (var y = 0; y < height; y++) {
14739 for (var x = 0; x < width; x++) {
14740 var color = palette[indata[pxPos]];
14741
14742 if (!color) {
14743 throw new Error('index ' + indata[pxPos] + ' not in palette');
14744 }
14745
14746 for (var i = 0; i < 4; i++) {
14747 outdata[pxPos + i] = color[i];
14748 }
14749 pxPos += 4;
14750 }
14751 }
14752}
14753
14754function replaceTransparentColor(indata, outdata, width, height, transColor) {
14755 var pxPos = 0;
14756 for (var y = 0; y < height; y++) {
14757 for (var x = 0; x < width; x++) {
14758 var makeTrans = false;
14759
14760 if (transColor.length === 1) {
14761 if (transColor[0] === indata[pxPos]) {
14762 makeTrans = true;
14763 }
14764 }
14765 else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
14766 makeTrans = true;
14767 }
14768 if (makeTrans) {
14769 for (var i = 0; i < 4; i++) {
14770 outdata[pxPos + i] = 0;
14771 }
14772 }
14773 pxPos += 4;
14774 }
14775 }
14776}
14777
14778function scaleDepth(indata, outdata, width, height, depth) {
14779 var maxOutSample = 255;
14780 var maxInSample = Math.pow(2, depth) - 1;
14781 var pxPos = 0;
14782
14783 for (var y = 0; y < height; y++) {
14784 for (var x = 0; x < width; x++) {
14785 for (var i = 0; i < 4; i++) {
14786 outdata[pxPos + i] = Math.floor((indata[pxPos + i] * maxOutSample) / maxInSample + 0.5);
14787 }
14788 pxPos += 4;
14789 }
14790 }
14791}
14792
14793module.exports = function(indata, imageData) {
14794
14795 var depth = imageData.depth;
14796 var width = imageData.width;
14797 var height = imageData.height;
14798 var colorType = imageData.colorType;
14799 var transColor = imageData.transColor;
14800 var palette = imageData.palette;
14801
14802 var outdata = indata; // only different for 16 bits
14803
14804 if (colorType === 3) { // paletted
14805 dePalette(indata, outdata, width, height, palette);
14806 }
14807 else {
14808 if (transColor) {
14809 replaceTransparentColor(indata, outdata, width, height, transColor);
14810 }
14811 // if it needs scaling
14812 if (depth !== 8) {
14813 // if we need to change the buffer size
14814 if (depth === 16) {
14815 outdata = new Buffer(width * height * 4);
14816 }
14817 scaleDepth(indata, outdata, width, height, depth);
14818 }
14819 }
14820 return outdata;
14821};
14822
14823}).call(this,require("buffer").Buffer)
14824},{"buffer":9}],59:[function(require,module,exports){
14825'use strict';
14826
14827// Adam 7
14828// 0 1 2 3 4 5 6 7
14829// 0 x 6 4 6 x 6 4 6
14830// 1 7 7 7 7 7 7 7 7
14831// 2 5 6 5 6 5 6 5 6
14832// 3 7 7 7 7 7 7 7 7
14833// 4 3 6 4 6 3 6 4 6
14834// 5 7 7 7 7 7 7 7 7
14835// 6 5 6 5 6 5 6 5 6
14836// 7 7 7 7 7 7 7 7 7
14837
14838
14839var imagePasses = [
14840 { // pass 1 - 1px
14841 x: [0],
14842 y: [0]
14843 },
14844 { // pass 2 - 1px
14845 x: [4],
14846 y: [0]
14847 },
14848 { // pass 3 - 2px
14849 x: [0, 4],
14850 y: [4]
14851 },
14852 { // pass 4 - 4px
14853 x: [2, 6],
14854 y: [0, 4]
14855 },
14856 { // pass 5 - 8px
14857 x: [0, 2, 4, 6],
14858 y: [2, 6]
14859 },
14860 { // pass 6 - 16px
14861 x: [1, 3, 5, 7],
14862 y: [0, 2, 4, 6]
14863 },
14864 { // pass 7 - 32px
14865 x: [0, 1, 2, 3, 4, 5, 6, 7],
14866 y: [1, 3, 5, 7]
14867 }
14868];
14869
14870exports.getImagePasses = function(width, height) {
14871 var images = [];
14872 var xLeftOver = width % 8;
14873 var yLeftOver = height % 8;
14874 var xRepeats = (width - xLeftOver) / 8;
14875 var yRepeats = (height - yLeftOver) / 8;
14876 for (var i = 0; i < imagePasses.length; i++) {
14877 var pass = imagePasses[i];
14878 var passWidth = xRepeats * pass.x.length;
14879 var passHeight = yRepeats * pass.y.length;
14880 for (var j = 0; j < pass.x.length; j++) {
14881 if (pass.x[j] < xLeftOver) {
14882 passWidth++;
14883 }
14884 else {
14885 break;
14886 }
14887 }
14888 for (j = 0; j < pass.y.length; j++) {
14889 if (pass.y[j] < yLeftOver) {
14890 passHeight++;
14891 }
14892 else {
14893 break;
14894 }
14895 }
14896 if (passWidth > 0 && passHeight > 0) {
14897 images.push({ width: passWidth, height: passHeight, index: i });
14898 }
14899 }
14900 return images;
14901};
14902
14903exports.getInterlaceIterator = function(width) {
14904 return function(x, y, pass) {
14905 var outerXLeftOver = x % imagePasses[pass].x.length;
14906 var outerX = (((x - outerXLeftOver) / imagePasses[pass].x.length) * 8) + imagePasses[pass].x[outerXLeftOver];
14907 var outerYLeftOver = y % imagePasses[pass].y.length;
14908 var outerY = (((y - outerYLeftOver) / imagePasses[pass].y.length) * 8) + imagePasses[pass].y[outerYLeftOver];
14909 return (outerX * 4) + (outerY * width * 4);
14910 };
14911};
14912},{}],60:[function(require,module,exports){
14913(function (Buffer){
14914'use strict';
14915
14916var util = require('util');
14917var Stream = require('stream');
14918var constants = require('./constants');
14919var Packer = require('./packer');
14920
14921var PackerAsync = module.exports = function(opt) {
14922 Stream.call(this);
14923
14924 var options = opt || {};
14925
14926 this._packer = new Packer(options);
14927 this._deflate = this._packer.createDeflate();
14928
14929 this.readable = true;
14930};
14931util.inherits(PackerAsync, Stream);
14932
14933
14934PackerAsync.prototype.pack = function(data, width, height, gamma) {
14935 // Signature
14936 this.emit('data', new Buffer(constants.PNG_SIGNATURE));
14937 this.emit('data', this._packer.packIHDR(width, height));
14938
14939 if (gamma) {
14940 this.emit('data', this._packer.packGAMA(gamma));
14941 }
14942
14943 var filteredData = this._packer.filterData(data, width, height);
14944
14945 // compress it
14946 this._deflate.on('error', this.emit.bind(this, 'error'));
14947
14948 this._deflate.on('data', function(compressedData) {
14949 this.emit('data', this._packer.packIDAT(compressedData));
14950 }.bind(this));
14951
14952 this._deflate.on('end', function() {
14953 this.emit('data', this._packer.packIEND());
14954 this.emit('end');
14955 }.bind(this));
14956
14957 this._deflate.end(filteredData);
14958};
14959
14960}).call(this,require("buffer").Buffer)
14961},{"./constants":52,"./packer":62,"buffer":9,"stream":43,"util":48}],61:[function(require,module,exports){
14962(function (Buffer){
14963'use strict';
14964
14965var hasSyncZlib = true;
14966var zlib = require('zlib');
14967if (!zlib.deflateSync) {
14968 hasSyncZlib = false;
14969}
14970var constants = require('./constants');
14971var Packer = require('./packer');
14972
14973module.exports = function(metaData, opt) {
14974
14975 if (!hasSyncZlib) {
14976 throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
14977 }
14978
14979 var options = opt || {};
14980
14981 var packer = new Packer(options);
14982
14983 var chunks = [];
14984
14985 // Signature
14986 chunks.push(new Buffer(constants.PNG_SIGNATURE));
14987
14988 // Header
14989 chunks.push(packer.packIHDR(metaData.width, metaData.height));
14990
14991 if (metaData.gamma) {
14992 chunks.push(packer.packGAMA(metaData.gamma));
14993 }
14994
14995 var filteredData = packer.filterData(metaData.data, metaData.width, metaData.height);
14996
14997 // compress it
14998 var compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions());
14999 filteredData = null;
15000
15001 if (!compressedData || !compressedData.length) {
15002 throw new Error('bad png - invalid compressed data response');
15003 }
15004 chunks.push(packer.packIDAT(compressedData));
15005
15006 // End
15007 chunks.push(packer.packIEND());
15008
15009 return Buffer.concat(chunks);
15010};
15011
15012}).call(this,require("buffer").Buffer)
15013},{"./constants":52,"./packer":62,"buffer":9,"zlib":8}],62:[function(require,module,exports){
15014(function (Buffer){
15015'use strict';
15016
15017var constants = require('./constants');
15018var CrcStream = require('./crc');
15019var bitPacker = require('./bitpacker');
15020var filter = require('./filter-pack');
15021var zlib = require('zlib');
15022
15023var Packer = module.exports = function(options) {
15024 this._options = options;
15025
15026 options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
15027 options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
15028 options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
15029 options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
15030 options.deflateFactory = options.deflateFactory || zlib.createDeflate;
15031 options.bitDepth = options.bitDepth || 8;
15032 // This is outputColorType
15033 options.colorType = (typeof options.colorType === 'number') ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
15034 options.inputColorType = (typeof options.inputColorType === 'number') ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
15035
15036 if ([
15037 constants.COLORTYPE_GRAYSCALE,
15038 constants.COLORTYPE_COLOR,
15039 constants.COLORTYPE_COLOR_ALPHA,
15040 constants.COLORTYPE_ALPHA
15041 ].indexOf(options.colorType) === -1) {
15042 throw new Error('option color type:' + options.colorType + ' is not supported at present');
15043 }
15044 if ([
15045 constants.COLORTYPE_GRAYSCALE,
15046 constants.COLORTYPE_COLOR,
15047 constants.COLORTYPE_COLOR_ALPHA,
15048 constants.COLORTYPE_ALPHA
15049 ].indexOf(options.inputColorType) === -1) {
15050 throw new Error('option input color type:' + options.inputColorType + ' is not supported at present');
15051 }
15052 if (options.bitDepth !== 8 && options.bitDepth !== 16) {
15053 throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present');
15054 }
15055};
15056
15057Packer.prototype.getDeflateOptions = function() {
15058 return {
15059 chunkSize: this._options.deflateChunkSize,
15060 level: this._options.deflateLevel,
15061 strategy: this._options.deflateStrategy
15062 };
15063};
15064
15065Packer.prototype.createDeflate = function() {
15066 return this._options.deflateFactory(this.getDeflateOptions());
15067};
15068
15069Packer.prototype.filterData = function(data, width, height) {
15070 // convert to correct format for filtering (e.g. right bpp and bit depth)
15071 var packedData = bitPacker(data, width, height, this._options);
15072
15073 // filter pixel data
15074 var bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
15075 var filteredData = filter(packedData, width, height, this._options, bpp);
15076 return filteredData;
15077};
15078
15079Packer.prototype._packChunk = function(type, data) {
15080
15081 var len = (data ? data.length : 0);
15082 var buf = new Buffer(len + 12);
15083
15084 buf.writeUInt32BE(len, 0);
15085 buf.writeUInt32BE(type, 4);
15086
15087 if (data) {
15088 data.copy(buf, 8);
15089 }
15090
15091 buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
15092 return buf;
15093};
15094
15095Packer.prototype.packGAMA = function(gamma) {
15096 var buf = new Buffer(4);
15097 buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
15098 return this._packChunk(constants.TYPE_gAMA, buf);
15099};
15100
15101Packer.prototype.packIHDR = function(width, height) {
15102
15103 var buf = new Buffer(13);
15104 buf.writeUInt32BE(width, 0);
15105 buf.writeUInt32BE(height, 4);
15106 buf[8] = this._options.bitDepth; // Bit depth
15107 buf[9] = this._options.colorType; // colorType
15108 buf[10] = 0; // compression
15109 buf[11] = 0; // filter
15110 buf[12] = 0; // interlace
15111
15112 return this._packChunk(constants.TYPE_IHDR, buf);
15113};
15114
15115Packer.prototype.packIDAT = function(data) {
15116 return this._packChunk(constants.TYPE_IDAT, data);
15117};
15118
15119Packer.prototype.packIEND = function() {
15120 return this._packChunk(constants.TYPE_IEND, null);
15121};
15122
15123}).call(this,require("buffer").Buffer)
15124},{"./bitpacker":50,"./constants":52,"./crc":53,"./filter-pack":54,"buffer":9,"zlib":8}],63:[function(require,module,exports){
15125'use strict';
15126
15127module.exports = function paethPredictor(left, above, upLeft) {
15128
15129 var paeth = left + above - upLeft;
15130 var pLeft = Math.abs(paeth - left);
15131 var pAbove = Math.abs(paeth - above);
15132 var pUpLeft = Math.abs(paeth - upLeft);
15133
15134 if (pLeft <= pAbove && pLeft <= pUpLeft) {
15135 return left;
15136 }
15137 if (pAbove <= pUpLeft) {
15138 return above;
15139 }
15140 return upLeft;
15141};
15142},{}],64:[function(require,module,exports){
15143'use strict';
15144
15145var util = require('util');
15146var zlib = require('zlib');
15147var ChunkStream = require('./chunkstream');
15148var FilterAsync = require('./filter-parse-async');
15149var Parser = require('./parser');
15150var bitmapper = require('./bitmapper');
15151var formatNormaliser = require('./format-normaliser');
15152
15153var ParserAsync = module.exports = function(options) {
15154 ChunkStream.call(this);
15155
15156 this._parser = new Parser(options, {
15157 read: this.read.bind(this),
15158 error: this._handleError.bind(this),
15159 metadata: this._handleMetaData.bind(this),
15160 gamma: this.emit.bind(this, 'gamma'),
15161 palette: this._handlePalette.bind(this),
15162 transColor: this._handleTransColor.bind(this),
15163 finished: this._finished.bind(this),
15164 inflateData: this._inflateData.bind(this)
15165 });
15166 this._options = options;
15167 this.writable = true;
15168
15169 this._parser.start();
15170};
15171util.inherits(ParserAsync, ChunkStream);
15172
15173
15174ParserAsync.prototype._handleError = function(err) {
15175
15176 this.emit('error', err);
15177
15178 this.writable = false;
15179
15180 this.destroy();
15181
15182 if (this._inflate && this._inflate.destroy) {
15183 this._inflate.destroy();
15184 }
15185
15186 if (this._filter) {
15187 this._filter.destroy();
15188 // For backward compatibility with Node 7 and below.
15189 // Suppress errors due to _inflate calling write() even after
15190 // it's destroy()'ed.
15191 this._filter.on('error', function() {});
15192 }
15193
15194 this.errord = true;
15195};
15196
15197ParserAsync.prototype._inflateData = function(data) {
15198 if (!this._inflate) {
15199 if (this._bitmapInfo.interlace) {
15200 this._inflate = zlib.createInflate();
15201
15202 this._inflate.on('error', this.emit.bind(this, 'error'));
15203 this._filter.on('complete', this._complete.bind(this));
15204
15205 this._inflate.pipe(this._filter);
15206 } else {
15207 var rowSize = ((this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7) >> 3) + 1;
15208 var imageSize = rowSize * this._bitmapInfo.height;
15209 var chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
15210
15211 this._inflate = zlib.createInflate({ chunkSize: chunkSize });
15212 var leftToInflate = imageSize;
15213
15214 var emitError = this.emit.bind(this, 'error');
15215 this._inflate.on('error', function(err) {
15216 if (!leftToInflate) {
15217 return;
15218 }
15219
15220 emitError(err);
15221 });
15222 this._filter.on('complete', this._complete.bind(this));
15223
15224 var filterWrite = this._filter.write.bind(this._filter);
15225 this._inflate.on('data', function(chunk) {
15226 if (!leftToInflate) {
15227 return;
15228 }
15229
15230 if (chunk.length > leftToInflate) {
15231 chunk = chunk.slice(0, leftToInflate);
15232 }
15233
15234 leftToInflate -= chunk.length;
15235
15236 filterWrite(chunk);
15237 });
15238
15239 this._inflate.on('end', this._filter.end.bind(this._filter));
15240 }
15241 }
15242 this._inflate.write(data);
15243};
15244
15245ParserAsync.prototype._handleMetaData = function(metaData) {
15246
15247 this.emit('metadata', metaData);
15248
15249 this._bitmapInfo = Object.create(metaData);
15250
15251 this._filter = new FilterAsync(this._bitmapInfo);
15252};
15253
15254ParserAsync.prototype._handleTransColor = function(transColor) {
15255 this._bitmapInfo.transColor = transColor;
15256};
15257
15258ParserAsync.prototype._handlePalette = function(palette) {
15259 this._bitmapInfo.palette = palette;
15260};
15261
15262
15263ParserAsync.prototype._finished = function() {
15264 if (this.errord) {
15265 return;
15266 }
15267
15268 if (!this._inflate) {
15269 this.emit('error', 'No Inflate block');
15270 }
15271 else {
15272 // no more data to inflate
15273 this._inflate.end();
15274 }
15275 this.destroySoon();
15276};
15277
15278ParserAsync.prototype._complete = function(filteredData) {
15279
15280 if (this.errord) {
15281 return;
15282 }
15283
15284 try {
15285 var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
15286
15287 var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
15288 bitmapData = null;
15289 }
15290 catch (ex) {
15291 this._handleError(ex);
15292 return;
15293 }
15294
15295 this.emit('parsed', normalisedBitmapData);
15296};
15297
15298},{"./bitmapper":49,"./chunkstream":51,"./filter-parse-async":55,"./format-normaliser":58,"./parser":66,"util":48,"zlib":8}],65:[function(require,module,exports){
15299(function (Buffer){
15300'use strict';
15301
15302var hasSyncZlib = true;
15303var zlib = require('zlib');
15304var inflateSync = require('./sync-inflate');
15305if (!zlib.deflateSync) {
15306 hasSyncZlib = false;
15307}
15308var SyncReader = require('./sync-reader');
15309var FilterSync = require('./filter-parse-sync');
15310var Parser = require('./parser');
15311var bitmapper = require('./bitmapper');
15312var formatNormaliser = require('./format-normaliser');
15313
15314
15315module.exports = function(buffer, options) {
15316
15317 if (!hasSyncZlib) {
15318 throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
15319 }
15320
15321 var err;
15322 function handleError(_err_) {
15323 err = _err_;
15324 }
15325
15326 var metaData;
15327 function handleMetaData(_metaData_) {
15328 metaData = _metaData_;
15329 }
15330
15331 function handleTransColor(transColor) {
15332 metaData.transColor = transColor;
15333 }
15334
15335 function handlePalette(palette) {
15336 metaData.palette = palette;
15337 }
15338
15339 var gamma;
15340 function handleGamma(_gamma_) {
15341 gamma = _gamma_;
15342 }
15343
15344 var inflateDataList = [];
15345 function handleInflateData(inflatedData) {
15346 inflateDataList.push(inflatedData);
15347 }
15348
15349 var reader = new SyncReader(buffer);
15350
15351 var parser = new Parser(options, {
15352 read: reader.read.bind(reader),
15353 error: handleError,
15354 metadata: handleMetaData,
15355 gamma: handleGamma,
15356 palette: handlePalette,
15357 transColor: handleTransColor,
15358 inflateData: handleInflateData
15359 });
15360
15361 parser.start();
15362 reader.process();
15363
15364 if (err) {
15365 throw err;
15366 }
15367
15368 //join together the inflate datas
15369 var inflateData = Buffer.concat(inflateDataList);
15370 inflateDataList.length = 0;
15371
15372 var inflatedData;
15373 if (metaData.interlace) {
15374 inflatedData = zlib.inflateSync(inflateData);
15375 } else {
15376 var rowSize = ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
15377 var imageSize = rowSize * metaData.height;
15378 inflatedData = inflateSync(inflateData, { chunkSize: imageSize, maxLength: imageSize });
15379 }
15380 inflateData = null;
15381
15382 if (!inflatedData || !inflatedData.length) {
15383 throw new Error('bad png - invalid inflate data response');
15384 }
15385
15386 var unfilteredData = FilterSync.process(inflatedData, metaData);
15387 inflateData = null;
15388
15389 var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
15390 unfilteredData = null;
15391
15392 var normalisedBitmapData = formatNormaliser(bitmapData, metaData);
15393
15394 metaData.data = normalisedBitmapData;
15395 metaData.gamma = gamma || 0;
15396
15397 return metaData;
15398};
15399
15400}).call(this,require("buffer").Buffer)
15401},{"./bitmapper":49,"./filter-parse-sync":56,"./format-normaliser":58,"./parser":66,"./sync-inflate":69,"./sync-reader":70,"buffer":9,"zlib":8}],66:[function(require,module,exports){
15402(function (Buffer){
15403'use strict';
15404
15405var constants = require('./constants');
15406var CrcCalculator = require('./crc');
15407
15408
15409var Parser = module.exports = function(options, dependencies) {
15410
15411 this._options = options;
15412 options.checkCRC = options.checkCRC !== false;
15413
15414 this._hasIHDR = false;
15415 this._hasIEND = false;
15416
15417 // input flags/metadata
15418 this._palette = [];
15419 this._colorType = 0;
15420
15421 this._chunks = {};
15422 this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
15423 this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
15424 this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
15425 this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
15426 this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
15427 this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
15428
15429 this.read = dependencies.read;
15430 this.error = dependencies.error;
15431 this.metadata = dependencies.metadata;
15432 this.gamma = dependencies.gamma;
15433 this.transColor = dependencies.transColor;
15434 this.palette = dependencies.palette;
15435 this.parsed = dependencies.parsed;
15436 this.inflateData = dependencies.inflateData;
15437 this.finished = dependencies.finished;
15438};
15439
15440Parser.prototype.start = function() {
15441 this.read(constants.PNG_SIGNATURE.length,
15442 this._parseSignature.bind(this)
15443 );
15444};
15445
15446Parser.prototype._parseSignature = function(data) {
15447
15448 var signature = constants.PNG_SIGNATURE;
15449
15450 for (var i = 0; i < signature.length; i++) {
15451 if (data[i] !== signature[i]) {
15452 this.error(new Error('Invalid file signature'));
15453 return;
15454 }
15455 }
15456 this.read(8, this._parseChunkBegin.bind(this));
15457};
15458
15459Parser.prototype._parseChunkBegin = function(data) {
15460
15461 // chunk content length
15462 var length = data.readUInt32BE(0);
15463
15464 // chunk type
15465 var type = data.readUInt32BE(4);
15466 var name = '';
15467 for (var i = 4; i < 8; i++) {
15468 name += String.fromCharCode(data[i]);
15469 }
15470
15471 //console.log('chunk ', name, length);
15472
15473 // chunk flags
15474 var ancillary = Boolean(data[4] & 0x20); // or critical
15475// priv = Boolean(data[5] & 0x20), // or public
15476// safeToCopy = Boolean(data[7] & 0x20); // or unsafe
15477
15478 if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
15479 this.error(new Error('Expected IHDR on beggining'));
15480 return;
15481 }
15482
15483 this._crc = new CrcCalculator();
15484 this._crc.write(new Buffer(name));
15485
15486 if (this._chunks[type]) {
15487 return this._chunks[type](length);
15488 }
15489
15490 if (!ancillary) {
15491 this.error(new Error('Unsupported critical chunk type ' + name));
15492 return;
15493 }
15494
15495 this.read(length + 4, this._skipChunk.bind(this));
15496};
15497
15498Parser.prototype._skipChunk = function(/*data*/) {
15499 this.read(8, this._parseChunkBegin.bind(this));
15500};
15501
15502Parser.prototype._handleChunkEnd = function() {
15503 this.read(4, this._parseChunkEnd.bind(this));
15504};
15505
15506Parser.prototype._parseChunkEnd = function(data) {
15507
15508 var fileCrc = data.readInt32BE(0);
15509 var calcCrc = this._crc.crc32();
15510
15511 // check CRC
15512 if (this._options.checkCRC && calcCrc !== fileCrc) {
15513 this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc));
15514 return;
15515 }
15516
15517 if (!this._hasIEND) {
15518 this.read(8, this._parseChunkBegin.bind(this));
15519 }
15520};
15521
15522Parser.prototype._handleIHDR = function(length) {
15523 this.read(length, this._parseIHDR.bind(this));
15524};
15525Parser.prototype._parseIHDR = function(data) {
15526
15527 this._crc.write(data);
15528
15529 var width = data.readUInt32BE(0);
15530 var height = data.readUInt32BE(4);
15531 var depth = data[8];
15532 var colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
15533 var compr = data[10];
15534 var filter = data[11];
15535 var interlace = data[12];
15536
15537 // console.log(' width', width, 'height', height,
15538 // 'depth', depth, 'colorType', colorType,
15539 // 'compr', compr, 'filter', filter, 'interlace', interlace
15540 // );
15541
15542 if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
15543 this.error(new Error('Unsupported bit depth ' + depth));
15544 return;
15545 }
15546 if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
15547 this.error(new Error('Unsupported color type'));
15548 return;
15549 }
15550 if (compr !== 0) {
15551 this.error(new Error('Unsupported compression method'));
15552 return;
15553 }
15554 if (filter !== 0) {
15555 this.error(new Error('Unsupported filter method'));
15556 return;
15557 }
15558 if (interlace !== 0 && interlace !== 1) {
15559 this.error(new Error('Unsupported interlace method'));
15560 return;
15561 }
15562
15563 this._colorType = colorType;
15564
15565 var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
15566
15567 this._hasIHDR = true;
15568
15569 this.metadata({
15570 width: width,
15571 height: height,
15572 depth: depth,
15573 interlace: Boolean(interlace),
15574 palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
15575 color: Boolean(colorType & constants.COLORTYPE_COLOR),
15576 alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
15577 bpp: bpp,
15578 colorType: colorType
15579 });
15580
15581 this._handleChunkEnd();
15582};
15583
15584
15585Parser.prototype._handlePLTE = function(length) {
15586 this.read(length, this._parsePLTE.bind(this));
15587};
15588Parser.prototype._parsePLTE = function(data) {
15589
15590 this._crc.write(data);
15591
15592 var entries = Math.floor(data.length / 3);
15593 // console.log('Palette:', entries);
15594
15595 for (var i = 0; i < entries; i++) {
15596 this._palette.push([
15597 data[i * 3],
15598 data[i * 3 + 1],
15599 data[i * 3 + 2],
15600 0xff
15601 ]);
15602 }
15603
15604 this.palette(this._palette);
15605
15606 this._handleChunkEnd();
15607};
15608
15609Parser.prototype._handleTRNS = function(length) {
15610 this.read(length, this._parseTRNS.bind(this));
15611};
15612Parser.prototype._parseTRNS = function(data) {
15613
15614 this._crc.write(data);
15615
15616 // palette
15617 if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
15618 if (this._palette.length === 0) {
15619 this.error(new Error('Transparency chunk must be after palette'));
15620 return;
15621 }
15622 if (data.length > this._palette.length) {
15623 this.error(new Error('More transparent colors than palette size'));
15624 return;
15625 }
15626 for (var i = 0; i < data.length; i++) {
15627 this._palette[i][3] = data[i];
15628 }
15629 this.palette(this._palette);
15630 }
15631
15632 // for colorType 0 (grayscale) and 2 (rgb)
15633 // there might be one gray/color defined as transparent
15634 if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
15635 // grey, 2 bytes
15636 this.transColor([data.readUInt16BE(0)]);
15637 }
15638 if (this._colorType === constants.COLORTYPE_COLOR) {
15639 this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]);
15640 }
15641
15642 this._handleChunkEnd();
15643};
15644
15645Parser.prototype._handleGAMA = function(length) {
15646 this.read(length, this._parseGAMA.bind(this));
15647};
15648Parser.prototype._parseGAMA = function(data) {
15649
15650 this._crc.write(data);
15651 this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
15652
15653 this._handleChunkEnd();
15654};
15655
15656Parser.prototype._handleIDAT = function(length) {
15657 this.read(-length, this._parseIDAT.bind(this, length));
15658};
15659Parser.prototype._parseIDAT = function(length, data) {
15660
15661 this._crc.write(data);
15662
15663 if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
15664 throw new Error('Expected palette not found');
15665 }
15666
15667 this.inflateData(data);
15668 var leftOverLength = length - data.length;
15669
15670 if (leftOverLength > 0) {
15671 this._handleIDAT(leftOverLength);
15672 }
15673 else {
15674 this._handleChunkEnd();
15675 }
15676};
15677
15678Parser.prototype._handleIEND = function(length) {
15679 this.read(length, this._parseIEND.bind(this));
15680};
15681Parser.prototype._parseIEND = function(data) {
15682
15683 this._crc.write(data);
15684
15685 this._hasIEND = true;
15686 this._handleChunkEnd();
15687
15688 if (this.finished) {
15689 this.finished();
15690 }
15691};
15692
15693}).call(this,require("buffer").Buffer)
15694},{"./constants":52,"./crc":53,"buffer":9}],67:[function(require,module,exports){
15695'use strict';
15696
15697
15698var parse = require('./parser-sync');
15699var pack = require('./packer-sync');
15700
15701
15702exports.read = function(buffer, options) {
15703
15704 return parse(buffer, options || {});
15705};
15706
15707exports.write = function(png, options) {
15708
15709 return pack(png, options);
15710};
15711
15712},{"./packer-sync":61,"./parser-sync":65}],68:[function(require,module,exports){
15713(function (process,Buffer){
15714'use strict';
15715
15716var util = require('util');
15717var Stream = require('stream');
15718var Parser = require('./parser-async');
15719var Packer = require('./packer-async');
15720var PNGSync = require('./png-sync');
15721
15722
15723var PNG = exports.PNG = function(options) {
15724 Stream.call(this);
15725
15726 options = options || {}; // eslint-disable-line no-param-reassign
15727
15728 // coerce pixel dimensions to integers (also coerces undefined -> 0):
15729 this.width = options.width | 0;
15730 this.height = options.height | 0;
15731
15732 this.data = this.width > 0 && this.height > 0 ?
15733 new Buffer(4 * this.width * this.height) : null;
15734
15735 if (options.fill && this.data) {
15736 this.data.fill(0);
15737 }
15738
15739 this.gamma = 0;
15740 this.readable = this.writable = true;
15741
15742 this._parser = new Parser(options);
15743
15744 this._parser.on('error', this.emit.bind(this, 'error'));
15745 this._parser.on('close', this._handleClose.bind(this));
15746 this._parser.on('metadata', this._metadata.bind(this));
15747 this._parser.on('gamma', this._gamma.bind(this));
15748 this._parser.on('parsed', function(data) {
15749 this.data = data;
15750 this.emit('parsed', data);
15751 }.bind(this));
15752
15753 this._packer = new Packer(options);
15754 this._packer.on('data', this.emit.bind(this, 'data'));
15755 this._packer.on('end', this.emit.bind(this, 'end'));
15756 this._parser.on('close', this._handleClose.bind(this));
15757 this._packer.on('error', this.emit.bind(this, 'error'));
15758
15759};
15760util.inherits(PNG, Stream);
15761
15762PNG.sync = PNGSync;
15763
15764PNG.prototype.pack = function() {
15765
15766 if (!this.data || !this.data.length) {
15767 this.emit('error', 'No data provided');
15768 return this;
15769 }
15770
15771 process.nextTick(function() {
15772 this._packer.pack(this.data, this.width, this.height, this.gamma);
15773 }.bind(this));
15774
15775 return this;
15776};
15777
15778
15779PNG.prototype.parse = function(data, callback) {
15780
15781 if (callback) {
15782 var onParsed, onError;
15783
15784 onParsed = function(parsedData) {
15785 this.removeListener('error', onError);
15786
15787 this.data = parsedData;
15788 callback(null, this);
15789 }.bind(this);
15790
15791 onError = function(err) {
15792 this.removeListener('parsed', onParsed);
15793
15794 callback(err, null);
15795 }.bind(this);
15796
15797 this.once('parsed', onParsed);
15798 this.once('error', onError);
15799 }
15800
15801 this.end(data);
15802 return this;
15803};
15804
15805PNG.prototype.write = function(data) {
15806 this._parser.write(data);
15807 return true;
15808};
15809
15810PNG.prototype.end = function(data) {
15811 this._parser.end(data);
15812};
15813
15814PNG.prototype._metadata = function(metadata) {
15815 this.width = metadata.width;
15816 this.height = metadata.height;
15817
15818 this.emit('metadata', metadata);
15819};
15820
15821PNG.prototype._gamma = function(gamma) {
15822 this.gamma = gamma;
15823};
15824
15825PNG.prototype._handleClose = function() {
15826 if (!this._parser.writable && !this._packer.readable) {
15827 this.emit('close');
15828 }
15829};
15830
15831
15832PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
15833 // coerce pixel dimensions to integers (also coerces undefined -> 0):
15834 /* eslint-disable no-param-reassign */
15835 srcX |= 0;
15836 srcY |= 0;
15837 width |= 0;
15838 height |= 0;
15839 deltaX |= 0;
15840 deltaY |= 0;
15841 /* eslint-enable no-param-reassign */
15842
15843 if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
15844 throw new Error('bitblt reading outside image');
15845 }
15846
15847 if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
15848 throw new Error('bitblt writing outside image');
15849 }
15850
15851 for (var y = 0; y < height; y++) {
15852 src.data.copy(dst.data,
15853 ((deltaY + y) * dst.width + deltaX) << 2,
15854 ((srcY + y) * src.width + srcX) << 2,
15855 ((srcY + y) * src.width + srcX + width) << 2
15856 );
15857 }
15858};
15859
15860
15861PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
15862
15863 PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
15864 return this;
15865};
15866
15867PNG.adjustGamma = function(src) {
15868 if (src.gamma) {
15869 for (var y = 0; y < src.height; y++) {
15870 for (var x = 0; x < src.width; x++) {
15871 var idx = (src.width * y + x) << 2;
15872
15873 for (var i = 0; i < 3; i++) {
15874 var sample = src.data[idx + i] / 255;
15875 sample = Math.pow(sample, 1 / 2.2 / src.gamma);
15876 src.data[idx + i] = Math.round(sample * 255);
15877 }
15878 }
15879 }
15880 src.gamma = 0;
15881 }
15882};
15883
15884PNG.prototype.adjustGamma = function() {
15885 PNG.adjustGamma(this);
15886};
15887
15888}).call(this,require('_process'),require("buffer").Buffer)
15889},{"./packer-async":60,"./parser-async":64,"./png-sync":67,"_process":28,"buffer":9,"stream":43,"util":48}],69:[function(require,module,exports){
15890(function (process,Buffer){
15891'use strict';
15892
15893var assert = require('assert').ok;
15894var zlib = require('zlib');
15895var util = require('util');
15896
15897var kMaxLength = require('buffer').kMaxLength;
15898
15899function Inflate(opts) {
15900 if (!(this instanceof Inflate)) {
15901 return new Inflate(opts);
15902 }
15903
15904 if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
15905 opts.chunkSize = zlib.Z_MIN_CHUNK;
15906 }
15907
15908 zlib.Inflate.call(this, opts);
15909
15910 // Node 8 --> 9 compatibility check
15911 this._offset = this._offset === undefined ? this._outOffset : this._offset;
15912 this._buffer = this._buffer || this._outBuffer;
15913
15914 if (opts && opts.maxLength != null) {
15915 this._maxLength = opts.maxLength;
15916 }
15917}
15918
15919function createInflate(opts) {
15920 return new Inflate(opts);
15921}
15922
15923function _close(engine, callback) {
15924 if (callback) {
15925 process.nextTick(callback);
15926 }
15927
15928 // Caller may invoke .close after a zlib error (which will null _handle).
15929 if (!engine._handle) {
15930 return;
15931 }
15932
15933 engine._handle.close();
15934 engine._handle = null;
15935}
15936
15937Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
15938 if (typeof asyncCb === 'function') {
15939 return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
15940 }
15941
15942 var self = this;
15943
15944 var availInBefore = chunk && chunk.length;
15945 var availOutBefore = this._chunkSize - this._offset;
15946 var leftToInflate = this._maxLength;
15947 var inOff = 0;
15948
15949 var buffers = [];
15950 var nread = 0;
15951
15952 var error;
15953 this.on('error', function(err) {
15954 error = err;
15955 });
15956
15957 function handleChunk(availInAfter, availOutAfter) {
15958 if (self._hadError) {
15959 return;
15960 }
15961
15962 var have = availOutBefore - availOutAfter;
15963 assert(have >= 0, 'have should not go down');
15964
15965 if (have > 0) {
15966 var out = self._buffer.slice(self._offset, self._offset + have);
15967 self._offset += have;
15968
15969 if (out.length > leftToInflate) {
15970 out = out.slice(0, leftToInflate);
15971 }
15972
15973 buffers.push(out);
15974 nread += out.length;
15975 leftToInflate -= out.length;
15976
15977 if (leftToInflate === 0) {
15978 return false;
15979 }
15980 }
15981
15982 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
15983 availOutBefore = self._chunkSize;
15984 self._offset = 0;
15985 self._buffer = Buffer.allocUnsafe(self._chunkSize);
15986 }
15987
15988 if (availOutAfter === 0) {
15989 inOff += (availInBefore - availInAfter);
15990 availInBefore = availInAfter;
15991
15992 return true;
15993 }
15994
15995 return false;
15996 }
15997
15998 assert(this._handle, 'zlib binding closed');
15999 do {
16000 var res = this._handle.writeSync(flushFlag,
16001 chunk, // in
16002 inOff, // in_off
16003 availInBefore, // in_len
16004 this._buffer, // out
16005 this._offset, //out_off
16006 availOutBefore); // out_len
16007 // Node 8 --> 9 compatibility check
16008 res = res || this._writeState;
16009 } while (!this._hadError && handleChunk(res[0], res[1]));
16010
16011 if (this._hadError) {
16012 throw error;
16013 }
16014
16015 if (nread >= kMaxLength) {
16016 _close(this);
16017 throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes');
16018 }
16019
16020 var buf = Buffer.concat(buffers, nread);
16021 _close(this);
16022
16023 return buf;
16024};
16025
16026util.inherits(Inflate, zlib.Inflate);
16027
16028function zlibBufferSync(engine, buffer) {
16029 if (typeof buffer === 'string') {
16030 buffer = Buffer.from(buffer);
16031 }
16032 if (!(buffer instanceof Buffer)) {
16033 throw new TypeError('Not a string or buffer');
16034 }
16035
16036 var flushFlag = engine._finishFlushFlag;
16037 if (flushFlag == null) {
16038 flushFlag = zlib.Z_FINISH;
16039 }
16040
16041 return engine._processChunk(buffer, flushFlag);
16042}
16043
16044function inflateSync(buffer, opts) {
16045 return zlibBufferSync(new Inflate(opts), buffer);
16046}
16047
16048module.exports = exports = inflateSync;
16049exports.Inflate = Inflate;
16050exports.createInflate = createInflate;
16051exports.inflateSync = inflateSync;
16052
16053}).call(this,require('_process'),require("buffer").Buffer)
16054},{"_process":28,"assert":1,"buffer":9,"util":48,"zlib":8}],70:[function(require,module,exports){
16055'use strict';
16056
16057var SyncReader = module.exports = function(buffer) {
16058
16059 this._buffer = buffer;
16060 this._reads = [];
16061};
16062
16063SyncReader.prototype.read = function(length, callback) {
16064
16065 this._reads.push({
16066 length: Math.abs(length), // if length < 0 then at most this length
16067 allowLess: length < 0,
16068 func: callback
16069 });
16070};
16071
16072SyncReader.prototype.process = function() {
16073
16074 // as long as there is any data and read requests
16075 while (this._reads.length > 0 && this._buffer.length) {
16076
16077 var read = this._reads[0];
16078
16079 if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
16080
16081 // ok there is any data so that we can satisfy this request
16082 this._reads.shift(); // == read
16083
16084 var buf = this._buffer;
16085
16086 this._buffer = buf.slice(read.length);
16087
16088 read.func.call(this, buf.slice(0, read.length));
16089
16090 }
16091 else {
16092 break;
16093 }
16094
16095 }
16096
16097 if (this._reads.length > 0) {
16098 return new Error('There are some read requests waitng on finished stream');
16099 }
16100
16101 if (this._buffer.length > 0) {
16102 return new Error('unrecognised content at end of stream');
16103 }
16104
16105};
16106
16107},{}]},{},[68])(68)
16108});