1/*!
2
3JSZip v3.10.1 - A JavaScript class for generating and reading zip files
4<http://stuartk.com/jszip>
5
6(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
7Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
8
9JSZip uses the library pako released under the MIT license :
10https://github.com/nodeca/pako/blob/main/LICENSE
11*/
12
13(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.JSZip = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
14"use strict";
15var utils = require("./utils");
16var support = require("./support");
17// private property
18var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
19
20
21// public method for encoding
22exports.encode = function(input) {
23    var output = [];
24    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
25    var i = 0, len = input.length, remainingBytes = len;
26
27    var isArray = utils.getTypeOf(input) !== "string";
28    while (i < input.length) {
29        remainingBytes = len - i;
30
31        if (!isArray) {
32            chr1 = input.charCodeAt(i++);
33            chr2 = i < len ? input.charCodeAt(i++) : 0;
34            chr3 = i < len ? input.charCodeAt(i++) : 0;
35        } else {
36            chr1 = input[i++];
37            chr2 = i < len ? input[i++] : 0;
38            chr3 = i < len ? input[i++] : 0;
39        }
40
41        enc1 = chr1 >> 2;
42        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
43        enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
44        enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
45
46        output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
47
48    }
49
50    return output.join("");
51};
52
53// public method for decoding
54exports.decode = function(input) {
55    var chr1, chr2, chr3;
56    var enc1, enc2, enc3, enc4;
57    var i = 0, resultIndex = 0;
58
59    var dataUrlPrefix = "data:";
60
61    if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
62        // This is a common error: people give a data url
63        // (data:image/png;base64,iVBOR...) with a {base64: true} and
64        // wonders why things don't work.
65        // We can detect that the string input looks like a data url but we
66        // *can't* be sure it is one: removing everything up to the comma would
67        // be too dangerous.
68        throw new Error("Invalid base64 input, it looks like a data url.");
69    }
70
71    input = input.replace(/[^A-Za-z0-9+/=]/g, "");
72
73    var totalLength = input.length * 3 / 4;
74    if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {
75        totalLength--;
76    }
77    if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {
78        totalLength--;
79    }
80    if (totalLength % 1 !== 0) {
81        // totalLength is not an integer, the length does not match a valid
82        // base64 content. That can happen if:
83        // - the input is not a base64 content
84        // - the input is *almost* a base64 content, with a extra chars at the
85        //   beginning or at the end
86        // - the input uses a base64 variant (base64url for example)
87        throw new Error("Invalid base64 input, bad content length.");
88    }
89    var output;
90    if (support.uint8array) {
91        output = new Uint8Array(totalLength|0);
92    } else {
93        output = new Array(totalLength|0);
94    }
95
96    while (i < input.length) {
97
98        enc1 = _keyStr.indexOf(input.charAt(i++));
99        enc2 = _keyStr.indexOf(input.charAt(i++));
100        enc3 = _keyStr.indexOf(input.charAt(i++));
101        enc4 = _keyStr.indexOf(input.charAt(i++));
102
103        chr1 = (enc1 << 2) | (enc2 >> 4);
104        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
105        chr3 = ((enc3 & 3) << 6) | enc4;
106
107        output[resultIndex++] = chr1;
108
109        if (enc3 !== 64) {
110            output[resultIndex++] = chr2;
111        }
112        if (enc4 !== 64) {
113            output[resultIndex++] = chr3;
114        }
115
116    }
117
118    return output;
119};
120
121},{"./support":30,"./utils":32}],2:[function(require,module,exports){
122"use strict";
123
124var external = require("./external");
125var DataWorker = require("./stream/DataWorker");
126var Crc32Probe = require("./stream/Crc32Probe");
127var DataLengthProbe = require("./stream/DataLengthProbe");
128
129/**
130 * Represent a compressed object, with everything needed to decompress it.
131 * @constructor
132 * @param {number} compressedSize the size of the data compressed.
133 * @param {number} uncompressedSize the size of the data after decompression.
134 * @param {number} crc32 the crc32 of the decompressed file.
135 * @param {object} compression the type of compression, see lib/compressions.js.
136 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
137 */
138function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
139    this.compressedSize = compressedSize;
140    this.uncompressedSize = uncompressedSize;
141    this.crc32 = crc32;
142    this.compression = compression;
143    this.compressedContent = data;
144}
145
146CompressedObject.prototype = {
147    /**
148     * Create a worker to get the uncompressed content.
149     * @return {GenericWorker} the worker.
150     */
151    getContentWorker: function () {
152        var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
153            .pipe(this.compression.uncompressWorker())
154            .pipe(new DataLengthProbe("data_length"));
155
156        var that = this;
157        worker.on("end", function () {
158            if (this.streamInfo["data_length"] !== that.uncompressedSize) {
159                throw new Error("Bug : uncompressed data size mismatch");
160            }
161        });
162        return worker;
163    },
164    /**
165     * Create a worker to get the compressed content.
166     * @return {GenericWorker} the worker.
167     */
168    getCompressedWorker: function () {
169        return new DataWorker(external.Promise.resolve(this.compressedContent))
170            .withStreamInfo("compressedSize", this.compressedSize)
171            .withStreamInfo("uncompressedSize", this.uncompressedSize)
172            .withStreamInfo("crc32", this.crc32)
173            .withStreamInfo("compression", this.compression)
174        ;
175    }
176};
177
178/**
179 * Chain the given worker with other workers to compress the content with the
180 * given compression.
181 * @param {GenericWorker} uncompressedWorker the worker to pipe.
182 * @param {Object} compression the compression object.
183 * @param {Object} compressionOptions the options to use when compressing.
184 * @return {GenericWorker} the new worker compressing the content.
185 */
186CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
187    return uncompressedWorker
188        .pipe(new Crc32Probe())
189        .pipe(new DataLengthProbe("uncompressedSize"))
190        .pipe(compression.compressWorker(compressionOptions))
191        .pipe(new DataLengthProbe("compressedSize"))
192        .withStreamInfo("compression", compression);
193};
194
195module.exports = CompressedObject;
196
197},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){
198"use strict";
199
200var GenericWorker = require("./stream/GenericWorker");
201
202exports.STORE = {
203    magic: "\x00\x00",
204    compressWorker : function () {
205        return new GenericWorker("STORE compression");
206    },
207    uncompressWorker : function () {
208        return new GenericWorker("STORE decompression");
209    }
210};
211exports.DEFLATE = require("./flate");
212
213},{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){
214"use strict";
215
216var utils = require("./utils");
217
218/**
219 * The following functions come from pako, from pako/lib/zlib/crc32.js
220 * released under the MIT license, see pako https://github.com/nodeca/pako/
221 */
222
223// Use ordinary array, since untyped makes no boost here
224function makeTable() {
225    var c, table = [];
226
227    for(var n =0; n < 256; n++){
228        c = n;
229        for(var k =0; k < 8; k++){
230            c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
231        }
232        table[n] = c;
233    }
234
235    return table;
236}
237
238// Create table on load. Just 255 signed longs. Not a problem.
239var crcTable = makeTable();
240
241
242function crc32(crc, buf, len, pos) {
243    var t = crcTable, end = pos + len;
244
245    crc = crc ^ (-1);
246
247    for (var i = pos; i < end; i++ ) {
248        crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
249    }
250
251    return (crc ^ (-1)); // >>> 0;
252}
253
254// That's all for the pako functions.
255
256/**
257 * Compute the crc32 of a string.
258 * This is almost the same as the function crc32, but for strings. Using the
259 * same function for the two use cases leads to horrible performances.
260 * @param {Number} crc the starting value of the crc.
261 * @param {String} str the string to use.
262 * @param {Number} len the length of the string.
263 * @param {Number} pos the starting position for the crc32 computation.
264 * @return {Number} the computed crc32.
265 */
266function crc32str(crc, str, len, pos) {
267    var t = crcTable, end = pos + len;
268
269    crc = crc ^ (-1);
270
271    for (var i = pos; i < end; i++ ) {
272        crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
273    }
274
275    return (crc ^ (-1)); // >>> 0;
276}
277
278module.exports = function crc32wrapper(input, crc) {
279    if (typeof input === "undefined" || !input.length) {
280        return 0;
281    }
282
283    var isArray = utils.getTypeOf(input) !== "string";
284
285    if(isArray) {
286        return crc32(crc|0, input, input.length, 0);
287    } else {
288        return crc32str(crc|0, input, input.length, 0);
289    }
290};
291
292},{"./utils":32}],5:[function(require,module,exports){
293"use strict";
294exports.base64 = false;
295exports.binary = false;
296exports.dir = false;
297exports.createFolders = true;
298exports.date = null;
299exports.compression = null;
300exports.compressionOptions = null;
301exports.comment = null;
302exports.unixPermissions = null;
303exports.dosPermissions = null;
304
305},{}],6:[function(require,module,exports){
306"use strict";
307
308// load the global object first:
309// - it should be better integrated in the system (unhandledRejection in node)
310// - the environment may have a custom Promise implementation (see zone.js)
311var ES6Promise = null;
312if (typeof Promise !== "undefined") {
313    ES6Promise = Promise;
314} else {
315    ES6Promise = require("lie");
316}
317
318/**
319 * Let the user use/change some implementations.
320 */
321module.exports = {
322    Promise: ES6Promise
323};
324
325},{"lie":37}],7:[function(require,module,exports){
326"use strict";
327var USE_TYPEDARRAY = (typeof Uint8Array !== "undefined") && (typeof Uint16Array !== "undefined") && (typeof Uint32Array !== "undefined");
328
329var pako = require("pako");
330var utils = require("./utils");
331var GenericWorker = require("./stream/GenericWorker");
332
333var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
334
335exports.magic = "\x08\x00";
336
337/**
338 * Create a worker that uses pako to inflate/deflate.
339 * @constructor
340 * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
341 * @param {Object} options the options to use when (de)compressing.
342 */
343function FlateWorker(action, options) {
344    GenericWorker.call(this, "FlateWorker/" + action);
345
346    this._pako = null;
347    this._pakoAction = action;
348    this._pakoOptions = options;
349    // the `meta` object from the last chunk received
350    // this allow this worker to pass around metadata
351    this.meta = {};
352}
353
354utils.inherits(FlateWorker, GenericWorker);
355
356/**
357 * @see GenericWorker.processChunk
358 */
359FlateWorker.prototype.processChunk = function (chunk) {
360    this.meta = chunk.meta;
361    if (this._pako === null) {
362        this._createPako();
363    }
364    this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
365};
366
367/**
368 * @see GenericWorker.flush
369 */
370FlateWorker.prototype.flush = function () {
371    GenericWorker.prototype.flush.call(this);
372    if (this._pako === null) {
373        this._createPako();
374    }
375    this._pako.push([], true);
376};
377/**
378 * @see GenericWorker.cleanUp
379 */
380FlateWorker.prototype.cleanUp = function () {
381    GenericWorker.prototype.cleanUp.call(this);
382    this._pako = null;
383};
384
385/**
386 * Create the _pako object.
387 * TODO: lazy-loading this object isn't the best solution but it's the
388 * quickest. The best solution is to lazy-load the worker list. See also the
389 * issue #446.
390 */
391FlateWorker.prototype._createPako = function () {
392    this._pako = new pako[this._pakoAction]({
393        raw: true,
394        level: this._pakoOptions.level || -1 // default compression
395    });
396    var self = this;
397    this._pako.onData = function(data) {
398        self.push({
399            data : data,
400            meta : self.meta
401        });
402    };
403};
404
405exports.compressWorker = function (compressionOptions) {
406    return new FlateWorker("Deflate", compressionOptions);
407};
408exports.uncompressWorker = function () {
409    return new FlateWorker("Inflate", {});
410};
411
412},{"./stream/GenericWorker":28,"./utils":32,"pako":38}],8:[function(require,module,exports){
413"use strict";
414
415var utils = require("../utils");
416var GenericWorker = require("../stream/GenericWorker");
417var utf8 = require("../utf8");
418var crc32 = require("../crc32");
419var signature = require("../signature");
420
421/**
422 * Transform an integer into a string in hexadecimal.
423 * @private
424 * @param {number} dec the number to convert.
425 * @param {number} bytes the number of bytes to generate.
426 * @returns {string} the result.
427 */
428var decToHex = function(dec, bytes) {
429    var hex = "", i;
430    for (i = 0; i < bytes; i++) {
431        hex += String.fromCharCode(dec & 0xff);
432        dec = dec >>> 8;
433    }
434    return hex;
435};
436
437/**
438 * Generate the UNIX part of the external file attributes.
439 * @param {Object} unixPermissions the unix permissions or null.
440 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
441 * @return {Number} a 32 bit integer.
442 *
443 * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
444 *
445 * TTTTsstrwxrwxrwx0000000000ADVSHR
446 * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
447 *     ^^^_________________________ setuid, setgid, sticky
448 *        ^^^^^^^^^________________ permissions
449 *                 ^^^^^^^^^^______ not used ?
450 *                           ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
451 */
452var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
453
454    var result = unixPermissions;
455    if (!unixPermissions) {
456        // I can't use octal values in strict mode, hence the hexa.
457        //  040775 => 0x41fd
458        // 0100664 => 0x81b4
459        result = isDir ? 0x41fd : 0x81b4;
460    }
461    return (result & 0xFFFF) << 16;
462};
463
464/**
465 * Generate the DOS part of the external file attributes.
466 * @param {Object} dosPermissions the dos permissions or null.
467 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
468 * @return {Number} a 32 bit integer.
469 *
470 * Bit 0     Read-Only
471 * Bit 1     Hidden
472 * Bit 2     System
473 * Bit 3     Volume Label
474 * Bit 4     Directory
475 * Bit 5     Archive
476 */
477var generateDosExternalFileAttr = function (dosPermissions) {
478    // the dir flag is already set for compatibility
479    return (dosPermissions || 0)  & 0x3F;
480};
481
482/**
483 * Generate the various parts used in the construction of the final zip file.
484 * @param {Object} streamInfo the hash with information about the compressed file.
485 * @param {Boolean} streamedContent is the content streamed ?
486 * @param {Boolean} streamingEnded is the stream finished ?
487 * @param {number} offset the current offset from the start of the zip file.
488 * @param {String} platform let's pretend we are this platform (change platform dependents fields)
489 * @param {Function} encodeFileName the function to encode the file name / comment.
490 * @return {Object} the zip parts.
491 */
492var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
493    var file = streamInfo["file"],
494        compression = streamInfo["compression"],
495        useCustomEncoding = encodeFileName !== utf8.utf8encode,
496        encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
497        utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
498        comment = file.comment,
499        encodedComment = utils.transformTo("string", encodeFileName(comment)),
500        utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
501        useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
502        useUTF8ForComment = utfEncodedComment.length !== comment.length,
503        dosTime,
504        dosDate,
505        extraFields = "",
506        unicodePathExtraField = "",
507        unicodeCommentExtraField = "",
508        dir = file.dir,
509        date = file.date;
510
511
512    var dataInfo = {
513        crc32 : 0,
514        compressedSize : 0,
515        uncompressedSize : 0
516    };
517
518    // if the content is streamed, the sizes/crc32 are only available AFTER
519    // the end of the stream.
520    if (!streamedContent || streamingEnded) {
521        dataInfo.crc32 = streamInfo["crc32"];
522        dataInfo.compressedSize = streamInfo["compressedSize"];
523        dataInfo.uncompressedSize = streamInfo["uncompressedSize"];
524    }
525
526    var bitflag = 0;
527    if (streamedContent) {
528        // Bit 3: the sizes/crc32 are set to zero in the local header.
529        // The correct values are put in the data descriptor immediately
530        // following the compressed data.
531        bitflag |= 0x0008;
532    }
533    if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
534        // Bit 11: Language encoding flag (EFS).
535        bitflag |= 0x0800;
536    }
537
538
539    var extFileAttr = 0;
540    var versionMadeBy = 0;
541    if (dir) {
542        // dos or unix, we set the dos dir flag
543        extFileAttr |= 0x00010;
544    }
545    if(platform === "UNIX") {
546        versionMadeBy = 0x031E; // UNIX, version 3.0
547        extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
548    } else { // DOS or other, fallback to DOS
549        versionMadeBy = 0x0014; // DOS, version 2.0
550        extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
551    }
552
553    // date
554    // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
555    // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
556    // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
557
558    dosTime = date.getUTCHours();
559    dosTime = dosTime << 6;
560    dosTime = dosTime | date.getUTCMinutes();
561    dosTime = dosTime << 5;
562    dosTime = dosTime | date.getUTCSeconds() / 2;
563
564    dosDate = date.getUTCFullYear() - 1980;
565    dosDate = dosDate << 4;
566    dosDate = dosDate | (date.getUTCMonth() + 1);
567    dosDate = dosDate << 5;
568    dosDate = dosDate | date.getUTCDate();
569
570    if (useUTF8ForFileName) {
571        // set the unicode path extra field. unzip needs at least one extra
572        // field to correctly handle unicode path, so using the path is as good
573        // as any other information. This could improve the situation with
574        // other archive managers too.
575        // This field is usually used without the utf8 flag, with a non
576        // unicode path in the header (winrar, winzip). This helps (a bit)
577        // with the messy Windows' default compressed folders feature but
578        // breaks on p7zip which doesn't seek the unicode path extra field.
579        // So for now, UTF-8 everywhere !
580        unicodePathExtraField =
581            // Version
582            decToHex(1, 1) +
583            // NameCRC32
584            decToHex(crc32(encodedFileName), 4) +
585            // UnicodeName
586            utfEncodedFileName;
587
588        extraFields +=
589            // Info-ZIP Unicode Path Extra Field
590            "\x75\x70" +
591            // size
592            decToHex(unicodePathExtraField.length, 2) +
593            // content
594            unicodePathExtraField;
595    }
596
597    if(useUTF8ForComment) {
598
599        unicodeCommentExtraField =
600            // Version
601            decToHex(1, 1) +
602            // CommentCRC32
603            decToHex(crc32(encodedComment), 4) +
604            // UnicodeName
605            utfEncodedComment;
606
607        extraFields +=
608            // Info-ZIP Unicode Path Extra Field
609            "\x75\x63" +
610            // size
611            decToHex(unicodeCommentExtraField.length, 2) +
612            // content
613            unicodeCommentExtraField;
614    }
615
616    var header = "";
617
618    // version needed to extract
619    header += "\x0A\x00";
620    // general purpose bit flag
621    header += decToHex(bitflag, 2);
622    // compression method
623    header += compression.magic;
624    // last mod file time
625    header += decToHex(dosTime, 2);
626    // last mod file date
627    header += decToHex(dosDate, 2);
628    // crc-32
629    header += decToHex(dataInfo.crc32, 4);
630    // compressed size
631    header += decToHex(dataInfo.compressedSize, 4);
632    // uncompressed size
633    header += decToHex(dataInfo.uncompressedSize, 4);
634    // file name length
635    header += decToHex(encodedFileName.length, 2);
636    // extra field length
637    header += decToHex(extraFields.length, 2);
638
639
640    var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
641
642    var dirRecord = signature.CENTRAL_FILE_HEADER +
643        // version made by (00: DOS)
644        decToHex(versionMadeBy, 2) +
645        // file header (common to file and central directory)
646        header +
647        // file comment length
648        decToHex(encodedComment.length, 2) +
649        // disk number start
650        "\x00\x00" +
651        // internal file attributes TODO
652        "\x00\x00" +
653        // external file attributes
654        decToHex(extFileAttr, 4) +
655        // relative offset of local header
656        decToHex(offset, 4) +
657        // file name
658        encodedFileName +
659        // extra field
660        extraFields +
661        // file comment
662        encodedComment;
663
664    return {
665        fileRecord: fileRecord,
666        dirRecord: dirRecord
667    };
668};
669
670/**
671 * Generate the EOCD record.
672 * @param {Number} entriesCount the number of entries in the zip file.
673 * @param {Number} centralDirLength the length (in bytes) of the central dir.
674 * @param {Number} localDirLength the length (in bytes) of the local dir.
675 * @param {String} comment the zip file comment as a binary string.
676 * @param {Function} encodeFileName the function to encode the comment.
677 * @return {String} the EOCD record.
678 */
679var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
680    var dirEnd = "";
681    var encodedComment = utils.transformTo("string", encodeFileName(comment));
682
683    // end of central dir signature
684    dirEnd = signature.CENTRAL_DIRECTORY_END +
685        // number of this disk
686        "\x00\x00" +
687        // number of the disk with the start of the central directory
688        "\x00\x00" +
689        // total number of entries in the central directory on this disk
690        decToHex(entriesCount, 2) +
691        // total number of entries in the central directory
692        decToHex(entriesCount, 2) +
693        // size of the central directory   4 bytes
694        decToHex(centralDirLength, 4) +
695        // offset of start of central directory with respect to the starting disk number
696        decToHex(localDirLength, 4) +
697        // .ZIP file comment length
698        decToHex(encodedComment.length, 2) +
699        // .ZIP file comment
700        encodedComment;
701
702    return dirEnd;
703};
704
705/**
706 * Generate data descriptors for a file entry.
707 * @param {Object} streamInfo the hash generated by a worker, containing information
708 * on the file entry.
709 * @return {String} the data descriptors.
710 */
711var generateDataDescriptors = function (streamInfo) {
712    var descriptor = "";
713    descriptor = signature.DATA_DESCRIPTOR +
714        // crc-32                          4 bytes
715        decToHex(streamInfo["crc32"], 4) +
716        // compressed size                 4 bytes
717        decToHex(streamInfo["compressedSize"], 4) +
718        // uncompressed size               4 bytes
719        decToHex(streamInfo["uncompressedSize"], 4);
720
721    return descriptor;
722};
723
724
725/**
726 * A worker to concatenate other workers to create a zip file.
727 * @param {Boolean} streamFiles `true` to stream the content of the files,
728 * `false` to accumulate it.
729 * @param {String} comment the comment to use.
730 * @param {String} platform the platform to use, "UNIX" or "DOS".
731 * @param {Function} encodeFileName the function to encode file names and comments.
732 */
733function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
734    GenericWorker.call(this, "ZipFileWorker");
735    // The number of bytes written so far. This doesn't count accumulated chunks.
736    this.bytesWritten = 0;
737    // The comment of the zip file
738    this.zipComment = comment;
739    // The platform "generating" the zip file.
740    this.zipPlatform = platform;
741    // the function to encode file names and comments.
742    this.encodeFileName = encodeFileName;
743    // Should we stream the content of the files ?
744    this.streamFiles = streamFiles;
745    // If `streamFiles` is false, we will need to accumulate the content of the
746    // files to calculate sizes / crc32 (and write them *before* the content).
747    // This boolean indicates if we are accumulating chunks (it will change a lot
748    // during the lifetime of this worker).
749    this.accumulate = false;
750    // The buffer receiving chunks when accumulating content.
751    this.contentBuffer = [];
752    // The list of generated directory records.
753    this.dirRecords = [];
754    // The offset (in bytes) from the beginning of the zip file for the current source.
755    this.currentSourceOffset = 0;
756    // The total number of entries in this zip file.
757    this.entriesCount = 0;
758    // the name of the file currently being added, null when handling the end of the zip file.
759    // Used for the emitted metadata.
760    this.currentFile = null;
761
762
763
764    this._sources = [];
765}
766utils.inherits(ZipFileWorker, GenericWorker);
767
768/**
769 * @see GenericWorker.push
770 */
771ZipFileWorker.prototype.push = function (chunk) {
772
773    var currentFilePercent = chunk.meta.percent || 0;
774    var entriesCount = this.entriesCount;
775    var remainingFiles = this._sources.length;
776
777    if(this.accumulate) {
778        this.contentBuffer.push(chunk);
779    } else {
780        this.bytesWritten += chunk.data.length;
781
782        GenericWorker.prototype.push.call(this, {
783            data : chunk.data,
784            meta : {
785                currentFile : this.currentFile,
786                percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
787            }
788        });
789    }
790};
791
792/**
793 * The worker started a new source (an other worker).
794 * @param {Object} streamInfo the streamInfo object from the new source.
795 */
796ZipFileWorker.prototype.openedSource = function (streamInfo) {
797    this.currentSourceOffset = this.bytesWritten;
798    this.currentFile = streamInfo["file"].name;
799
800    var streamedContent = this.streamFiles && !streamInfo["file"].dir;
801
802    // don't stream folders (because they don't have any content)
803    if(streamedContent) {
804        var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
805        this.push({
806            data : record.fileRecord,
807            meta : {percent:0}
808        });
809    } else {
810        // we need to wait for the whole file before pushing anything
811        this.accumulate = true;
812    }
813};
814
815/**
816 * The worker finished a source (an other worker).
817 * @param {Object} streamInfo the streamInfo object from the finished source.
818 */
819ZipFileWorker.prototype.closedSource = function (streamInfo) {
820    this.accumulate = false;
821    var streamedContent = this.streamFiles && !streamInfo["file"].dir;
822    var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
823
824    this.dirRecords.push(record.dirRecord);
825    if(streamedContent) {
826        // after the streamed file, we put data descriptors
827        this.push({
828            data : generateDataDescriptors(streamInfo),
829            meta : {percent:100}
830        });
831    } else {
832        // the content wasn't streamed, we need to push everything now
833        // first the file record, then the content
834        this.push({
835            data : record.fileRecord,
836            meta : {percent:0}
837        });
838        while(this.contentBuffer.length) {
839            this.push(this.contentBuffer.shift());
840        }
841    }
842    this.currentFile = null;
843};
844
845/**
846 * @see GenericWorker.flush
847 */
848ZipFileWorker.prototype.flush = function () {
849
850    var localDirLength = this.bytesWritten;
851    for(var i = 0; i < this.dirRecords.length; i++) {
852        this.push({
853            data : this.dirRecords[i],
854            meta : {percent:100}
855        });
856    }
857    var centralDirLength = this.bytesWritten - localDirLength;
858
859    var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
860
861    this.push({
862        data : dirEnd,
863        meta : {percent:100}
864    });
865};
866
867/**
868 * Prepare the next source to be read.
869 */
870ZipFileWorker.prototype.prepareNextSource = function () {
871    this.previous = this._sources.shift();
872    this.openedSource(this.previous.streamInfo);
873    if (this.isPaused) {
874        this.previous.pause();
875    } else {
876        this.previous.resume();
877    }
878};
879
880/**
881 * @see GenericWorker.registerPrevious
882 */
883ZipFileWorker.prototype.registerPrevious = function (previous) {
884    this._sources.push(previous);
885    var self = this;
886
887    previous.on("data", function (chunk) {
888        self.processChunk(chunk);
889    });
890    previous.on("end", function () {
891        self.closedSource(self.previous.streamInfo);
892        if(self._sources.length) {
893            self.prepareNextSource();
894        } else {
895            self.end();
896        }
897    });
898    previous.on("error", function (e) {
899        self.error(e);
900    });
901    return this;
902};
903
904/**
905 * @see GenericWorker.resume
906 */
907ZipFileWorker.prototype.resume = function () {
908    if(!GenericWorker.prototype.resume.call(this)) {
909        return false;
910    }
911
912    if (!this.previous && this._sources.length) {
913        this.prepareNextSource();
914        return true;
915    }
916    if (!this.previous && !this._sources.length && !this.generatedError) {
917        this.end();
918        return true;
919    }
920};
921
922/**
923 * @see GenericWorker.error
924 */
925ZipFileWorker.prototype.error = function (e) {
926    var sources = this._sources;
927    if(!GenericWorker.prototype.error.call(this, e)) {
928        return false;
929    }
930    for(var i = 0; i < sources.length; i++) {
931        try {
932            sources[i].error(e);
933        } catch(e) {
934            // the `error` exploded, nothing to do
935        }
936    }
937    return true;
938};
939
940/**
941 * @see GenericWorker.lock
942 */
943ZipFileWorker.prototype.lock = function () {
944    GenericWorker.prototype.lock.call(this);
945    var sources = this._sources;
946    for(var i = 0; i < sources.length; i++) {
947        sources[i].lock();
948    }
949};
950
951module.exports = ZipFileWorker;
952
953},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
954"use strict";
955
956var compressions = require("../compressions");
957var ZipFileWorker = require("./ZipFileWorker");
958
959/**
960 * Find the compression to use.
961 * @param {String} fileCompression the compression defined at the file level, if any.
962 * @param {String} zipCompression the compression defined at the load() level.
963 * @return {Object} the compression object to use.
964 */
965var getCompression = function (fileCompression, zipCompression) {
966
967    var compressionName = fileCompression || zipCompression;
968    var compression = compressions[compressionName];
969    if (!compression) {
970        throw new Error(compressionName + " is not a valid compression method !");
971    }
972    return compression;
973};
974
975/**
976 * Create a worker to generate a zip file.
977 * @param {JSZip} zip the JSZip instance at the right root level.
978 * @param {Object} options to generate the zip file.
979 * @param {String} comment the comment to use.
980 */
981exports.generateWorker = function (zip, options, comment) {
982
983    var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
984    var entriesCount = 0;
985    try {
986
987        zip.forEach(function (relativePath, file) {
988            entriesCount++;
989            var compression = getCompression(file.options.compression, options.compression);
990            var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
991            var dir = file.dir, date = file.date;
992
993            file._compressWorker(compression, compressionOptions)
994                .withStreamInfo("file", {
995                    name : relativePath,
996                    dir : dir,
997                    date : date,
998                    comment : file.comment || "",
999                    unixPermissions : file.unixPermissions,
1000                    dosPermissions : file.dosPermissions
1001                })
1002                .pipe(zipFileWorker);
1003        });
1004        zipFileWorker.entriesCount = entriesCount;
1005    } catch (e) {
1006        zipFileWorker.error(e);
1007    }
1008
1009    return zipFileWorker;
1010};
1011
1012},{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
1013"use strict";
1014
1015/**
1016 * Representation a of zip file in js
1017 * @constructor
1018 */
1019function JSZip() {
1020    // if this constructor is used without `new`, it adds `new` before itself:
1021    if(!(this instanceof JSZip)) {
1022        return new JSZip();
1023    }
1024
1025    if(arguments.length) {
1026        throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
1027    }
1028
1029    // object containing the files :
1030    // {
1031    //   "folder/" : {...},
1032    //   "folder/data.txt" : {...}
1033    // }
1034    // NOTE: we use a null prototype because we do not
1035    // want filenames like "toString" coming from a zip file
1036    // to overwrite methods and attributes in a normal Object.
1037    this.files = Object.create(null);
1038
1039    this.comment = null;
1040
1041    // Where we are in the hierarchy
1042    this.root = "";
1043    this.clone = function() {
1044        var newObj = new JSZip();
1045        for (var i in this) {
1046            if (typeof this[i] !== "function") {
1047                newObj[i] = this[i];
1048            }
1049        }
1050        return newObj;
1051    };
1052}
1053JSZip.prototype = require("./object");
1054JSZip.prototype.loadAsync = require("./load");
1055JSZip.support = require("./support");
1056JSZip.defaults = require("./defaults");
1057
1058// TODO find a better way to handle this version,
1059// a require('package.json').version doesn't work with webpack, see #327
1060JSZip.version = "3.10.1";
1061
1062JSZip.loadAsync = function (content, options) {
1063    return new JSZip().loadAsync(content, options);
1064};
1065
1066JSZip.external = require("./external");
1067module.exports = JSZip;
1068
1069},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
1070"use strict";
1071var utils = require("./utils");
1072var external = require("./external");
1073var utf8 = require("./utf8");
1074var ZipEntries = require("./zipEntries");
1075var Crc32Probe = require("./stream/Crc32Probe");
1076var nodejsUtils = require("./nodejsUtils");
1077
1078/**
1079 * Check the CRC32 of an entry.
1080 * @param {ZipEntry} zipEntry the zip entry to check.
1081 * @return {Promise} the result.
1082 */
1083function checkEntryCRC32(zipEntry) {
1084    return new external.Promise(function (resolve, reject) {
1085        var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
1086        worker.on("error", function (e) {
1087            reject(e);
1088        })
1089            .on("end", function () {
1090                if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
1091                    reject(new Error("Corrupted zip : CRC32 mismatch"));
1092                } else {
1093                    resolve();
1094                }
1095            })
1096            .resume();
1097    });
1098}
1099
1100module.exports = function (data, options) {
1101    var zip = this;
1102    options = utils.extend(options || {}, {
1103        base64: false,
1104        checkCRC32: false,
1105        optimizedBinaryString: false,
1106        createFolders: false,
1107        decodeFileName: utf8.utf8decode
1108    });
1109
1110    if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
1111        return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
1112    }
1113
1114    return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
1115        .then(function (data) {
1116            var zipEntries = new ZipEntries(options);
1117            zipEntries.load(data);
1118            return zipEntries;
1119        }).then(function checkCRC32(zipEntries) {
1120            var promises = [external.Promise.resolve(zipEntries)];
1121            var files = zipEntries.files;
1122            if (options.checkCRC32) {
1123                for (var i = 0; i < files.length; i++) {
1124                    promises.push(checkEntryCRC32(files[i]));
1125                }
1126            }
1127            return external.Promise.all(promises);
1128        }).then(function addFiles(results) {
1129            var zipEntries = results.shift();
1130            var files = zipEntries.files;
1131            for (var i = 0; i < files.length; i++) {
1132                var input = files[i];
1133
1134                var unsafeName = input.fileNameStr;
1135                var safeName = utils.resolve(input.fileNameStr);
1136
1137                zip.file(safeName, input.decompressed, {
1138                    binary: true,
1139                    optimizedBinaryString: true,
1140                    date: input.date,
1141                    dir: input.dir,
1142                    comment: input.fileCommentStr.length ? input.fileCommentStr : null,
1143                    unixPermissions: input.unixPermissions,
1144                    dosPermissions: input.dosPermissions,
1145                    createFolders: options.createFolders
1146                });
1147                if (!input.dir) {
1148                    zip.file(safeName).unsafeOriginalName = unsafeName;
1149                }
1150            }
1151            if (zipEntries.zipComment.length) {
1152                zip.comment = zipEntries.zipComment;
1153            }
1154
1155            return zip;
1156        });
1157};
1158
1159},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
1160"use strict";
1161
1162var utils = require("../utils");
1163var GenericWorker = require("../stream/GenericWorker");
1164
1165/**
1166 * A worker that use a nodejs stream as source.
1167 * @constructor
1168 * @param {String} filename the name of the file entry for this stream.
1169 * @param {Readable} stream the nodejs stream.
1170 */
1171function NodejsStreamInputAdapter(filename, stream) {
1172    GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
1173    this._upstreamEnded = false;
1174    this._bindStream(stream);
1175}
1176
1177utils.inherits(NodejsStreamInputAdapter, GenericWorker);
1178
1179/**
1180 * Prepare the stream and bind the callbacks on it.
1181 * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
1182 * @param {Stream} stream the nodejs stream to use.
1183 */
1184NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
1185    var self = this;
1186    this._stream = stream;
1187    stream.pause();
1188    stream
1189        .on("data", function (chunk) {
1190            self.push({
1191                data: chunk,
1192                meta : {
1193                    percent : 0
1194                }
1195            });
1196        })
1197        .on("error", function (e) {
1198            if(self.isPaused) {
1199                this.generatedError = e;
1200            } else {
1201                self.error(e);
1202            }
1203        })
1204        .on("end", function () {
1205            if(self.isPaused) {
1206                self._upstreamEnded = true;
1207            } else {
1208                self.end();
1209            }
1210        });
1211};
1212NodejsStreamInputAdapter.prototype.pause = function () {
1213    if(!GenericWorker.prototype.pause.call(this)) {
1214        return false;
1215    }
1216    this._stream.pause();
1217    return true;
1218};
1219NodejsStreamInputAdapter.prototype.resume = function () {
1220    if(!GenericWorker.prototype.resume.call(this)) {
1221        return false;
1222    }
1223
1224    if(this._upstreamEnded) {
1225        this.end();
1226    } else {
1227        this._stream.resume();
1228    }
1229
1230    return true;
1231};
1232
1233module.exports = NodejsStreamInputAdapter;
1234
1235},{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
1236"use strict";
1237
1238var Readable = require("readable-stream").Readable;
1239
1240var utils = require("../utils");
1241utils.inherits(NodejsStreamOutputAdapter, Readable);
1242
1243/**
1244* A nodejs stream using a worker as source.
1245* @see the SourceWrapper in http://nodejs.org/api/stream.html
1246* @constructor
1247* @param {StreamHelper} helper the helper wrapping the worker
1248* @param {Object} options the nodejs stream options
1249* @param {Function} updateCb the update callback.
1250*/
1251function NodejsStreamOutputAdapter(helper, options, updateCb) {
1252    Readable.call(this, options);
1253    this._helper = helper;
1254
1255    var self = this;
1256    helper.on("data", function (data, meta) {
1257        if (!self.push(data)) {
1258            self._helper.pause();
1259        }
1260        if(updateCb) {
1261            updateCb(meta);
1262        }
1263    })
1264        .on("error", function(e) {
1265            self.emit("error", e);
1266        })
1267        .on("end", function () {
1268            self.push(null);
1269        });
1270}
1271
1272
1273NodejsStreamOutputAdapter.prototype._read = function() {
1274    this._helper.resume();
1275};
1276
1277module.exports = NodejsStreamOutputAdapter;
1278
1279},{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){
1280"use strict";
1281
1282module.exports = {
1283    /**
1284     * True if this is running in Nodejs, will be undefined in a browser.
1285     * In a browser, browserify won't include this file and the whole module
1286     * will be resolved an empty object.
1287     */
1288    isNode : typeof Buffer !== "undefined",
1289    /**
1290     * Create a new nodejs Buffer from an existing content.
1291     * @param {Object} data the data to pass to the constructor.
1292     * @param {String} encoding the encoding to use.
1293     * @return {Buffer} a new Buffer.
1294     */
1295    newBufferFrom: function(data, encoding) {
1296        if (Buffer.from && Buffer.from !== Uint8Array.from) {
1297            return Buffer.from(data, encoding);
1298        } else {
1299            if (typeof data === "number") {
1300                // Safeguard for old Node.js versions. On newer versions,
1301                // Buffer.from(number) / Buffer(number, encoding) already throw.
1302                throw new Error("The \"data\" argument must not be a number");
1303            }
1304            return new Buffer(data, encoding);
1305        }
1306    },
1307    /**
1308     * Create a new nodejs Buffer with the specified size.
1309     * @param {Integer} size the size of the buffer.
1310     * @return {Buffer} a new Buffer.
1311     */
1312    allocBuffer: function (size) {
1313        if (Buffer.alloc) {
1314            return Buffer.alloc(size);
1315        } else {
1316            var buf = new Buffer(size);
1317            buf.fill(0);
1318            return buf;
1319        }
1320    },
1321    /**
1322     * Find out if an object is a Buffer.
1323     * @param {Object} b the object to test.
1324     * @return {Boolean} true if the object is a Buffer, false otherwise.
1325     */
1326    isBuffer : function(b){
1327        return Buffer.isBuffer(b);
1328    },
1329
1330    isStream : function (obj) {
1331        return obj &&
1332            typeof obj.on === "function" &&
1333            typeof obj.pause === "function" &&
1334            typeof obj.resume === "function";
1335    }
1336};
1337
1338},{}],15:[function(require,module,exports){
1339"use strict";
1340var utf8 = require("./utf8");
1341var utils = require("./utils");
1342var GenericWorker = require("./stream/GenericWorker");
1343var StreamHelper = require("./stream/StreamHelper");
1344var defaults = require("./defaults");
1345var CompressedObject = require("./compressedObject");
1346var ZipObject = require("./zipObject");
1347var generate = require("./generate");
1348var nodejsUtils = require("./nodejsUtils");
1349var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
1350
1351
1352/**
1353 * Add a file in the current folder.
1354 * @private
1355 * @param {string} name the name of the file
1356 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
1357 * @param {Object} originalOptions the options of the file
1358 * @return {Object} the new file.
1359 */
1360var fileAdd = function(name, data, originalOptions) {
1361    // be sure sub folders exist
1362    var dataType = utils.getTypeOf(data),
1363        parent;
1364
1365
1366    /*
1367     * Correct options.
1368     */
1369
1370    var o = utils.extend(originalOptions || {}, defaults);
1371    o.date = o.date || new Date();
1372    if (o.compression !== null) {
1373        o.compression = o.compression.toUpperCase();
1374    }
1375
1376    if (typeof o.unixPermissions === "string") {
1377        o.unixPermissions = parseInt(o.unixPermissions, 8);
1378    }
1379
1380    // UNX_IFDIR  0040000 see zipinfo.c
1381    if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
1382        o.dir = true;
1383    }
1384    // Bit 4    Directory
1385    if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
1386        o.dir = true;
1387    }
1388
1389    if (o.dir) {
1390        name = forceTrailingSlash(name);
1391    }
1392    if (o.createFolders && (parent = parentFolder(name))) {
1393        folderAdd.call(this, parent, true);
1394    }
1395
1396    var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
1397    if (!originalOptions || typeof originalOptions.binary === "undefined") {
1398        o.binary = !isUnicodeString;
1399    }
1400
1401
1402    var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
1403
1404    if (isCompressedEmpty || o.dir || !data || data.length === 0) {
1405        o.base64 = false;
1406        o.binary = true;
1407        data = "";
1408        o.compression = "STORE";
1409        dataType = "string";
1410    }
1411
1412    /*
1413     * Convert content to fit.
1414     */
1415
1416    var zipObjectContent = null;
1417    if (data instanceof CompressedObject || data instanceof GenericWorker) {
1418        zipObjectContent = data;
1419    } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
1420        zipObjectContent = new NodejsStreamInputAdapter(name, data);
1421    } else {
1422        zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
1423    }
1424
1425    var object = new ZipObject(name, zipObjectContent, o);
1426    this.files[name] = object;
1427    /*
1428    TODO: we can't throw an exception because we have async promises
1429    (we can have a promise of a Date() for example) but returning a
1430    promise is useless because file(name, data) returns the JSZip
1431    object for chaining. Should we break that to allow the user
1432    to catch the error ?
1433
1434    return external.Promise.resolve(zipObjectContent)
1435    .then(function () {
1436        return object;
1437    });
1438    */
1439};
1440
1441/**
1442 * Find the parent folder of the path.
1443 * @private
1444 * @param {string} path the path to use
1445 * @return {string} the parent folder, or ""
1446 */
1447var parentFolder = function (path) {
1448    if (path.slice(-1) === "/") {
1449        path = path.substring(0, path.length - 1);
1450    }
1451    var lastSlash = path.lastIndexOf("/");
1452    return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
1453};
1454
1455/**
1456 * Returns the path with a slash at the end.
1457 * @private
1458 * @param {String} path the path to check.
1459 * @return {String} the path with a trailing slash.
1460 */
1461var forceTrailingSlash = function(path) {
1462    // Check the name ends with a /
1463    if (path.slice(-1) !== "/") {
1464        path += "/"; // IE doesn't like substr(-1)
1465    }
1466    return path;
1467};
1468
1469/**
1470 * Add a (sub) folder in the current folder.
1471 * @private
1472 * @param {string} name the folder's name
1473 * @param {boolean=} [createFolders] If true, automatically create sub
1474 *  folders. Defaults to false.
1475 * @return {Object} the new folder.
1476 */
1477var folderAdd = function(name, createFolders) {
1478    createFolders = (typeof createFolders !== "undefined") ? createFolders : defaults.createFolders;
1479
1480    name = forceTrailingSlash(name);
1481
1482    // Does this folder already exist?
1483    if (!this.files[name]) {
1484        fileAdd.call(this, name, null, {
1485            dir: true,
1486            createFolders: createFolders
1487        });
1488    }
1489    return this.files[name];
1490};
1491
1492/**
1493* Cross-window, cross-Node-context regular expression detection
1494* @param  {Object}  object Anything
1495* @return {Boolean}        true if the object is a regular expression,
1496* false otherwise
1497*/
1498function isRegExp(object) {
1499    return Object.prototype.toString.call(object) === "[object RegExp]";
1500}
1501
1502// return the actual prototype of JSZip
1503var out = {
1504    /**
1505     * @see loadAsync
1506     */
1507    load: function() {
1508        throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
1509    },
1510
1511
1512    /**
1513     * Call a callback function for each entry at this folder level.
1514     * @param {Function} cb the callback function:
1515     * function (relativePath, file) {...}
1516     * It takes 2 arguments : the relative path and the file.
1517     */
1518    forEach: function(cb) {
1519        var filename, relativePath, file;
1520        // ignore warning about unwanted properties because this.files is a null prototype object
1521        /* eslint-disable-next-line guard-for-in */
1522        for (filename in this.files) {
1523            file = this.files[filename];
1524            relativePath = filename.slice(this.root.length, filename.length);
1525            if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
1526                cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
1527            }
1528        }
1529    },
1530
1531    /**
1532     * Filter nested files/folders with the specified function.
1533     * @param {Function} search the predicate to use :
1534     * function (relativePath, file) {...}
1535     * It takes 2 arguments : the relative path and the file.
1536     * @return {Array} An array of matching elements.
1537     */
1538    filter: function(search) {
1539        var result = [];
1540        this.forEach(function (relativePath, entry) {
1541            if (search(relativePath, entry)) { // the file matches the function
1542                result.push(entry);
1543            }
1544
1545        });
1546        return result;
1547    },
1548
1549    /**
1550     * Add a file to the zip file, or search a file.
1551     * @param   {string|RegExp} name The name of the file to add (if data is defined),
1552     * the name of the file to find (if no data) or a regex to match files.
1553     * @param   {String|ArrayBuffer|Uint8Array|Buffer} data  The file data, either raw or base64 encoded
1554     * @param   {Object} o     File options
1555     * @return  {JSZip|Object|Array} this JSZip object (when adding a file),
1556     * a file (when searching by string) or an array of files (when searching by regex).
1557     */
1558    file: function(name, data, o) {
1559        if (arguments.length === 1) {
1560            if (isRegExp(name)) {
1561                var regexp = name;
1562                return this.filter(function(relativePath, file) {
1563                    return !file.dir && regexp.test(relativePath);
1564                });
1565            }
1566            else { // text
1567                var obj = this.files[this.root + name];
1568                if (obj && !obj.dir) {
1569                    return obj;
1570                } else {
1571                    return null;
1572                }
1573            }
1574        }
1575        else { // more than one argument : we have data !
1576            name = this.root + name;
1577            fileAdd.call(this, name, data, o);
1578        }
1579        return this;
1580    },
1581
1582    /**
1583     * Add a directory to the zip file, or search.
1584     * @param   {String|RegExp} arg The name of the directory to add, or a regex to search folders.
1585     * @return  {JSZip} an object with the new directory as the root, or an array containing matching folders.
1586     */
1587    folder: function(arg) {
1588        if (!arg) {
1589            return this;
1590        }
1591
1592        if (isRegExp(arg)) {
1593            return this.filter(function(relativePath, file) {
1594                return file.dir && arg.test(relativePath);
1595            });
1596        }
1597
1598        // else, name is a new folder
1599        var name = this.root + arg;
1600        var newFolder = folderAdd.call(this, name);
1601
1602        // Allow chaining by returning a new object with this folder as the root
1603        var ret = this.clone();
1604        ret.root = newFolder.name;
1605        return ret;
1606    },
1607
1608    /**
1609     * Delete a file, or a directory and all sub-files, from the zip
1610     * @param {string} name the name of the file to delete
1611     * @return {JSZip} this JSZip object
1612     */
1613    remove: function(name) {
1614        name = this.root + name;
1615        var file = this.files[name];
1616        if (!file) {
1617            // Look for any folders
1618            if (name.slice(-1) !== "/") {
1619                name += "/";
1620            }
1621            file = this.files[name];
1622        }
1623
1624        if (file && !file.dir) {
1625            // file
1626            delete this.files[name];
1627        } else {
1628            // maybe a folder, delete recursively
1629            var kids = this.filter(function(relativePath, file) {
1630                return file.name.slice(0, name.length) === name;
1631            });
1632            for (var i = 0; i < kids.length; i++) {
1633                delete this.files[kids[i].name];
1634            }
1635        }
1636
1637        return this;
1638    },
1639
1640    /**
1641     * @deprecated This method has been removed in JSZip 3.0, please check the upgrade guide.
1642     */
1643    generate: function() {
1644        throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
1645    },
1646
1647    /**
1648     * Generate the complete zip file as an internal stream.
1649     * @param {Object} options the options to generate the zip file :
1650     * - compression, "STORE" by default.
1651     * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
1652     * @return {StreamHelper} the streamed zip file.
1653     */
1654    generateInternalStream: function(options) {
1655        var worker, opts = {};
1656        try {
1657            opts = utils.extend(options || {}, {
1658                streamFiles: false,
1659                compression: "STORE",
1660                compressionOptions : null,
1661                type: "",
1662                platform: "DOS",
1663                comment: null,
1664                mimeType: "application/zip",
1665                encodeFileName: utf8.utf8encode
1666            });
1667
1668            opts.type = opts.type.toLowerCase();
1669            opts.compression = opts.compression.toUpperCase();
1670
1671            // "binarystring" is preferred but the internals use "string".
1672            if(opts.type === "binarystring") {
1673                opts.type = "string";
1674            }
1675
1676            if (!opts.type) {
1677                throw new Error("No output type specified.");
1678            }
1679
1680            utils.checkSupport(opts.type);
1681
1682            // accept nodejs `process.platform`
1683            if(
1684                opts.platform === "darwin" ||
1685                opts.platform === "freebsd" ||
1686                opts.platform === "linux" ||
1687                opts.platform === "sunos"
1688            ) {
1689                opts.platform = "UNIX";
1690            }
1691            if (opts.platform === "win32") {
1692                opts.platform = "DOS";
1693            }
1694
1695            var comment = opts.comment || this.comment || "";
1696            worker = generate.generateWorker(this, opts, comment);
1697        } catch (e) {
1698            worker = new GenericWorker("error");
1699            worker.error(e);
1700        }
1701        return new StreamHelper(worker, opts.type || "string", opts.mimeType);
1702    },
1703    /**
1704     * Generate the complete zip file asynchronously.
1705     * @see generateInternalStream
1706     */
1707    generateAsync: function(options, onUpdate) {
1708        return this.generateInternalStream(options).accumulate(onUpdate);
1709    },
1710    /**
1711     * Generate the complete zip file asynchronously.
1712     * @see generateInternalStream
1713     */
1714    generateNodeStream: function(options, onUpdate) {
1715        options = options || {};
1716        if (!options.type) {
1717            options.type = "nodebuffer";
1718        }
1719        return this.generateInternalStream(options).toNodejsStream(onUpdate);
1720    }
1721};
1722module.exports = out;
1723
1724},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(require,module,exports){
1725"use strict";
1726/*
1727 * This file is used by module bundlers (browserify/webpack/etc) when
1728 * including a stream implementation. We use "readable-stream" to get a
1729 * consistent behavior between nodejs versions but bundlers often have a shim
1730 * for "stream". Using this shim greatly improve the compatibility and greatly
1731 * reduce the final size of the bundle (only one stream implementation, not
1732 * two).
1733 */
1734module.exports = require("stream");
1735
1736},{"stream":undefined}],17:[function(require,module,exports){
1737"use strict";
1738var DataReader = require("./DataReader");
1739var utils = require("../utils");
1740
1741function ArrayReader(data) {
1742    DataReader.call(this, data);
1743    for(var i = 0; i < this.data.length; i++) {
1744        data[i] = data[i] & 0xFF;
1745    }
1746}
1747utils.inherits(ArrayReader, DataReader);
1748/**
1749 * @see DataReader.byteAt
1750 */
1751ArrayReader.prototype.byteAt = function(i) {
1752    return this.data[this.zero + i];
1753};
1754/**
1755 * @see DataReader.lastIndexOfSignature
1756 */
1757ArrayReader.prototype.lastIndexOfSignature = function(sig) {
1758    var sig0 = sig.charCodeAt(0),
1759        sig1 = sig.charCodeAt(1),
1760        sig2 = sig.charCodeAt(2),
1761        sig3 = sig.charCodeAt(3);
1762    for (var i = this.length - 4; i >= 0; --i) {
1763        if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
1764            return i - this.zero;
1765        }
1766    }
1767
1768    return -1;
1769};
1770/**
1771 * @see DataReader.readAndCheckSignature
1772 */
1773ArrayReader.prototype.readAndCheckSignature = function (sig) {
1774    var sig0 = sig.charCodeAt(0),
1775        sig1 = sig.charCodeAt(1),
1776        sig2 = sig.charCodeAt(2),
1777        sig3 = sig.charCodeAt(3),
1778        data = this.readData(4);
1779    return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
1780};
1781/**
1782 * @see DataReader.readData
1783 */
1784ArrayReader.prototype.readData = function(size) {
1785    this.checkOffset(size);
1786    if(size === 0) {
1787        return [];
1788    }
1789    var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
1790    this.index += size;
1791    return result;
1792};
1793module.exports = ArrayReader;
1794
1795},{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
1796"use strict";
1797var utils = require("../utils");
1798
1799function DataReader(data) {
1800    this.data = data; // type : see implementation
1801    this.length = data.length;
1802    this.index = 0;
1803    this.zero = 0;
1804}
1805DataReader.prototype = {
1806    /**
1807     * Check that the offset will not go too far.
1808     * @param {string} offset the additional offset to check.
1809     * @throws {Error} an Error if the offset is out of bounds.
1810     */
1811    checkOffset: function(offset) {
1812        this.checkIndex(this.index + offset);
1813    },
1814    /**
1815     * Check that the specified index will not be too far.
1816     * @param {string} newIndex the index to check.
1817     * @throws {Error} an Error if the index is out of bounds.
1818     */
1819    checkIndex: function(newIndex) {
1820        if (this.length < this.zero + newIndex || newIndex < 0) {
1821            throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
1822        }
1823    },
1824    /**
1825     * Change the index.
1826     * @param {number} newIndex The new index.
1827     * @throws {Error} if the new index is out of the data.
1828     */
1829    setIndex: function(newIndex) {
1830        this.checkIndex(newIndex);
1831        this.index = newIndex;
1832    },
1833    /**
1834     * Skip the next n bytes.
1835     * @param {number} n the number of bytes to skip.
1836     * @throws {Error} if the new index is out of the data.
1837     */
1838    skip: function(n) {
1839        this.setIndex(this.index + n);
1840    },
1841    /**
1842     * Get the byte at the specified index.
1843     * @param {number} i the index to use.
1844     * @return {number} a byte.
1845     */
1846    byteAt: function() {
1847        // see implementations
1848    },
1849    /**
1850     * Get the next number with a given byte size.
1851     * @param {number} size the number of bytes to read.
1852     * @return {number} the corresponding number.
1853     */
1854    readInt: function(size) {
1855        var result = 0,
1856            i;
1857        this.checkOffset(size);
1858        for (i = this.index + size - 1; i >= this.index; i--) {
1859            result = (result << 8) + this.byteAt(i);
1860        }
1861        this.index += size;
1862        return result;
1863    },
1864    /**
1865     * Get the next string with a given byte size.
1866     * @param {number} size the number of bytes to read.
1867     * @return {string} the corresponding string.
1868     */
1869    readString: function(size) {
1870        return utils.transformTo("string", this.readData(size));
1871    },
1872    /**
1873     * Get raw data without conversion, <size> bytes.
1874     * @param {number} size the number of bytes to read.
1875     * @return {Object} the raw data, implementation specific.
1876     */
1877    readData: function() {
1878        // see implementations
1879    },
1880    /**
1881     * Find the last occurrence of a zip signature (4 bytes).
1882     * @param {string} sig the signature to find.
1883     * @return {number} the index of the last occurrence, -1 if not found.
1884     */
1885    lastIndexOfSignature: function() {
1886        // see implementations
1887    },
1888    /**
1889     * Read the signature (4 bytes) at the current position and compare it with sig.
1890     * @param {string} sig the expected signature
1891     * @return {boolean} true if the signature matches, false otherwise.
1892     */
1893    readAndCheckSignature: function() {
1894        // see implementations
1895    },
1896    /**
1897     * Get the next date.
1898     * @return {Date} the date.
1899     */
1900    readDate: function() {
1901        var dostime = this.readInt(4);
1902        return new Date(Date.UTC(
1903            ((dostime >> 25) & 0x7f) + 1980, // year
1904            ((dostime >> 21) & 0x0f) - 1, // month
1905            (dostime >> 16) & 0x1f, // day
1906            (dostime >> 11) & 0x1f, // hour
1907            (dostime >> 5) & 0x3f, // minute
1908            (dostime & 0x1f) << 1)); // second
1909    }
1910};
1911module.exports = DataReader;
1912
1913},{"../utils":32}],19:[function(require,module,exports){
1914"use strict";
1915var Uint8ArrayReader = require("./Uint8ArrayReader");
1916var utils = require("../utils");
1917
1918function NodeBufferReader(data) {
1919    Uint8ArrayReader.call(this, data);
1920}
1921utils.inherits(NodeBufferReader, Uint8ArrayReader);
1922
1923/**
1924 * @see DataReader.readData
1925 */
1926NodeBufferReader.prototype.readData = function(size) {
1927    this.checkOffset(size);
1928    var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
1929    this.index += size;
1930    return result;
1931};
1932module.exports = NodeBufferReader;
1933
1934},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
1935"use strict";
1936var DataReader = require("./DataReader");
1937var utils = require("../utils");
1938
1939function StringReader(data) {
1940    DataReader.call(this, data);
1941}
1942utils.inherits(StringReader, DataReader);
1943/**
1944 * @see DataReader.byteAt
1945 */
1946StringReader.prototype.byteAt = function(i) {
1947    return this.data.charCodeAt(this.zero + i);
1948};
1949/**
1950 * @see DataReader.lastIndexOfSignature
1951 */
1952StringReader.prototype.lastIndexOfSignature = function(sig) {
1953    return this.data.lastIndexOf(sig) - this.zero;
1954};
1955/**
1956 * @see DataReader.readAndCheckSignature
1957 */
1958StringReader.prototype.readAndCheckSignature = function (sig) {
1959    var data = this.readData(4);
1960    return sig === data;
1961};
1962/**
1963 * @see DataReader.readData
1964 */
1965StringReader.prototype.readData = function(size) {
1966    this.checkOffset(size);
1967    // this will work because the constructor applied the "& 0xff" mask.
1968    var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
1969    this.index += size;
1970    return result;
1971};
1972module.exports = StringReader;
1973
1974},{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
1975"use strict";
1976var ArrayReader = require("./ArrayReader");
1977var utils = require("../utils");
1978
1979function Uint8ArrayReader(data) {
1980    ArrayReader.call(this, data);
1981}
1982utils.inherits(Uint8ArrayReader, ArrayReader);
1983/**
1984 * @see DataReader.readData
1985 */
1986Uint8ArrayReader.prototype.readData = function(size) {
1987    this.checkOffset(size);
1988    if(size === 0) {
1989        // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
1990        return new Uint8Array(0);
1991    }
1992    var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
1993    this.index += size;
1994    return result;
1995};
1996module.exports = Uint8ArrayReader;
1997
1998},{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
1999"use strict";
2000
2001var utils = require("../utils");
2002var support = require("../support");
2003var ArrayReader = require("./ArrayReader");
2004var StringReader = require("./StringReader");
2005var NodeBufferReader = require("./NodeBufferReader");
2006var Uint8ArrayReader = require("./Uint8ArrayReader");
2007
2008/**
2009 * Create a reader adapted to the data.
2010 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
2011 * @return {DataReader} the data reader.
2012 */
2013module.exports = function (data) {
2014    var type = utils.getTypeOf(data);
2015    utils.checkSupport(type);
2016    if (type === "string" && !support.uint8array) {
2017        return new StringReader(data);
2018    }
2019    if (type === "nodebuffer") {
2020        return new NodeBufferReader(data);
2021    }
2022    if (support.uint8array) {
2023        return new Uint8ArrayReader(utils.transformTo("uint8array", data));
2024    }
2025    return new ArrayReader(utils.transformTo("array", data));
2026};
2027
2028},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
2029"use strict";
2030exports.LOCAL_FILE_HEADER = "PK\x03\x04";
2031exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
2032exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
2033exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
2034exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
2035exports.DATA_DESCRIPTOR = "PK\x07\x08";
2036
2037},{}],24:[function(require,module,exports){
2038"use strict";
2039
2040var GenericWorker = require("./GenericWorker");
2041var utils = require("../utils");
2042
2043/**
2044 * A worker which convert chunks to a specified type.
2045 * @constructor
2046 * @param {String} destType the destination type.
2047 */
2048function ConvertWorker(destType) {
2049    GenericWorker.call(this, "ConvertWorker to " + destType);
2050    this.destType = destType;
2051}
2052utils.inherits(ConvertWorker, GenericWorker);
2053
2054/**
2055 * @see GenericWorker.processChunk
2056 */
2057ConvertWorker.prototype.processChunk = function (chunk) {
2058    this.push({
2059        data : utils.transformTo(this.destType, chunk.data),
2060        meta : chunk.meta
2061    });
2062};
2063module.exports = ConvertWorker;
2064
2065},{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
2066"use strict";
2067
2068var GenericWorker = require("./GenericWorker");
2069var crc32 = require("../crc32");
2070var utils = require("../utils");
2071
2072/**
2073 * A worker which calculate the crc32 of the data flowing through.
2074 * @constructor
2075 */
2076function Crc32Probe() {
2077    GenericWorker.call(this, "Crc32Probe");
2078    this.withStreamInfo("crc32", 0);
2079}
2080utils.inherits(Crc32Probe, GenericWorker);
2081
2082/**
2083 * @see GenericWorker.processChunk
2084 */
2085Crc32Probe.prototype.processChunk = function (chunk) {
2086    this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
2087    this.push(chunk);
2088};
2089module.exports = Crc32Probe;
2090
2091},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
2092"use strict";
2093
2094var utils = require("../utils");
2095var GenericWorker = require("./GenericWorker");
2096
2097/**
2098 * A worker which calculate the total length of the data flowing through.
2099 * @constructor
2100 * @param {String} propName the name used to expose the length
2101 */
2102function DataLengthProbe(propName) {
2103    GenericWorker.call(this, "DataLengthProbe for " + propName);
2104    this.propName = propName;
2105    this.withStreamInfo(propName, 0);
2106}
2107utils.inherits(DataLengthProbe, GenericWorker);
2108
2109/**
2110 * @see GenericWorker.processChunk
2111 */
2112DataLengthProbe.prototype.processChunk = function (chunk) {
2113    if(chunk) {
2114        var length = this.streamInfo[this.propName] || 0;
2115        this.streamInfo[this.propName] = length + chunk.data.length;
2116    }
2117    GenericWorker.prototype.processChunk.call(this, chunk);
2118};
2119module.exports = DataLengthProbe;
2120
2121
2122},{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
2123"use strict";
2124
2125var utils = require("../utils");
2126var GenericWorker = require("./GenericWorker");
2127
2128// the size of the generated chunks
2129// TODO expose this as a public variable
2130var DEFAULT_BLOCK_SIZE = 16 * 1024;
2131
2132/**
2133 * A worker that reads a content and emits chunks.
2134 * @constructor
2135 * @param {Promise} dataP the promise of the data to split
2136 */
2137function DataWorker(dataP) {
2138    GenericWorker.call(this, "DataWorker");
2139    var self = this;
2140    this.dataIsReady = false;
2141    this.index = 0;
2142    this.max = 0;
2143    this.data = null;
2144    this.type = "";
2145
2146    this._tickScheduled = false;
2147
2148    dataP.then(function (data) {
2149        self.dataIsReady = true;
2150        self.data = data;
2151        self.max = data && data.length || 0;
2152        self.type = utils.getTypeOf(data);
2153        if(!self.isPaused) {
2154            self._tickAndRepeat();
2155        }
2156    }, function (e) {
2157        self.error(e);
2158    });
2159}
2160
2161utils.inherits(DataWorker, GenericWorker);
2162
2163/**
2164 * @see GenericWorker.cleanUp
2165 */
2166DataWorker.prototype.cleanUp = function () {
2167    GenericWorker.prototype.cleanUp.call(this);
2168    this.data = null;
2169};
2170
2171/**
2172 * @see GenericWorker.resume
2173 */
2174DataWorker.prototype.resume = function () {
2175    if(!GenericWorker.prototype.resume.call(this)) {
2176        return false;
2177    }
2178
2179    if (!this._tickScheduled && this.dataIsReady) {
2180        this._tickScheduled = true;
2181        utils.delay(this._tickAndRepeat, [], this);
2182    }
2183    return true;
2184};
2185
2186/**
2187 * Trigger a tick a schedule an other call to this function.
2188 */
2189DataWorker.prototype._tickAndRepeat = function() {
2190    this._tickScheduled = false;
2191    if(this.isPaused || this.isFinished) {
2192        return;
2193    }
2194    this._tick();
2195    if(!this.isFinished) {
2196        utils.delay(this._tickAndRepeat, [], this);
2197        this._tickScheduled = true;
2198    }
2199};
2200
2201/**
2202 * Read and push a chunk.
2203 */
2204DataWorker.prototype._tick = function() {
2205
2206    if(this.isPaused || this.isFinished) {
2207        return false;
2208    }
2209
2210    var size = DEFAULT_BLOCK_SIZE;
2211    var data = null, nextIndex = Math.min(this.max, this.index + size);
2212    if (this.index >= this.max) {
2213        // EOF
2214        return this.end();
2215    } else {
2216        switch(this.type) {
2217        case "string":
2218            data = this.data.substring(this.index, nextIndex);
2219            break;
2220        case "uint8array":
2221            data = this.data.subarray(this.index, nextIndex);
2222            break;
2223        case "array":
2224        case "nodebuffer":
2225            data = this.data.slice(this.index, nextIndex);
2226            break;
2227        }
2228        this.index = nextIndex;
2229        return this.push({
2230            data : data,
2231            meta : {
2232                percent : this.max ? this.index / this.max * 100 : 0
2233            }
2234        });
2235    }
2236};
2237
2238module.exports = DataWorker;
2239
2240},{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
2241"use strict";
2242
2243/**
2244 * A worker that does nothing but passing chunks to the next one. This is like
2245 * a nodejs stream but with some differences. On the good side :
2246 * - it works on IE 6-9 without any issue / polyfill
2247 * - it weights less than the full dependencies bundled with browserify
2248 * - it forwards errors (no need to declare an error handler EVERYWHERE)
2249 *
2250 * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
2251 * object containing anything (`percent` for example), see each worker for more
2252 * details. The latter is the real data (String, Uint8Array, etc).
2253 *
2254 * @constructor
2255 * @param {String} name the name of the stream (mainly used for debugging purposes)
2256 */
2257function GenericWorker(name) {
2258    // the name of the worker
2259    this.name = name || "default";
2260    // an object containing metadata about the workers chain
2261    this.streamInfo = {};
2262    // an error which happened when the worker was paused
2263    this.generatedError = null;
2264    // an object containing metadata to be merged by this worker into the general metadata
2265    this.extraStreamInfo = {};
2266    // true if the stream is paused (and should not do anything), false otherwise
2267    this.isPaused = true;
2268    // true if the stream is finished (and should not do anything), false otherwise
2269    this.isFinished = false;
2270    // true if the stream is locked to prevent further structure updates (pipe), false otherwise
2271    this.isLocked = false;
2272    // the event listeners
2273    this._listeners = {
2274        "data":[],
2275        "end":[],
2276        "error":[]
2277    };
2278    // the previous worker, if any
2279    this.previous = null;
2280}
2281
2282GenericWorker.prototype = {
2283    /**
2284     * Push a chunk to the next workers.
2285     * @param {Object} chunk the chunk to push
2286     */
2287    push : function (chunk) {
2288        this.emit("data", chunk);
2289    },
2290    /**
2291     * End the stream.
2292     * @return {Boolean} true if this call ended the worker, false otherwise.
2293     */
2294    end : function () {
2295        if (this.isFinished) {
2296            return false;
2297        }
2298
2299        this.flush();
2300        try {
2301            this.emit("end");
2302            this.cleanUp();
2303            this.isFinished = true;
2304        } catch (e) {
2305            this.emit("error", e);
2306        }
2307        return true;
2308    },
2309    /**
2310     * End the stream with an error.
2311     * @param {Error} e the error which caused the premature end.
2312     * @return {Boolean} true if this call ended the worker with an error, false otherwise.
2313     */
2314    error : function (e) {
2315        if (this.isFinished) {
2316            return false;
2317        }
2318
2319        if(this.isPaused) {
2320            this.generatedError = e;
2321        } else {
2322            this.isFinished = true;
2323
2324            this.emit("error", e);
2325
2326            // in the workers chain exploded in the middle of the chain,
2327            // the error event will go downward but we also need to notify
2328            // workers upward that there has been an error.
2329            if(this.previous) {
2330                this.previous.error(e);
2331            }
2332
2333            this.cleanUp();
2334        }
2335        return true;
2336    },
2337    /**
2338     * Add a callback on an event.
2339     * @param {String} name the name of the event (data, end, error)
2340     * @param {Function} listener the function to call when the event is triggered
2341     * @return {GenericWorker} the current object for chainability
2342     */
2343    on : function (name, listener) {
2344        this._listeners[name].push(listener);
2345        return this;
2346    },
2347    /**
2348     * Clean any references when a worker is ending.
2349     */
2350    cleanUp : function () {
2351        this.streamInfo = this.generatedError = this.extraStreamInfo = null;
2352        this._listeners = [];
2353    },
2354    /**
2355     * Trigger an event. This will call registered callback with the provided arg.
2356     * @param {String} name the name of the event (data, end, error)
2357     * @param {Object} arg the argument to call the callback with.
2358     */
2359    emit : function (name, arg) {
2360        if (this._listeners[name]) {
2361            for(var i = 0; i < this._listeners[name].length; i++) {
2362                this._listeners[name][i].call(this, arg);
2363            }
2364        }
2365    },
2366    /**
2367     * Chain a worker with an other.
2368     * @param {Worker} next the worker receiving events from the current one.
2369     * @return {worker} the next worker for chainability
2370     */
2371    pipe : function (next) {
2372        return next.registerPrevious(this);
2373    },
2374    /**
2375     * Same as `pipe` in the other direction.
2376     * Using an API with `pipe(next)` is very easy.
2377     * Implementing the API with the point of view of the next one registering
2378     * a source is easier, see the ZipFileWorker.
2379     * @param {Worker} previous the previous worker, sending events to this one
2380     * @return {Worker} the current worker for chainability
2381     */
2382    registerPrevious : function (previous) {
2383        if (this.isLocked) {
2384            throw new Error("The stream '" + this + "' has already been used.");
2385        }
2386
2387        // sharing the streamInfo...
2388        this.streamInfo = previous.streamInfo;
2389        // ... and adding our own bits
2390        this.mergeStreamInfo();
2391        this.previous =  previous;
2392        var self = this;
2393        previous.on("data", function (chunk) {
2394            self.processChunk(chunk);
2395        });
2396        previous.on("end", function () {
2397            self.end();
2398        });
2399        previous.on("error", function (e) {
2400            self.error(e);
2401        });
2402        return this;
2403    },
2404    /**
2405     * Pause the stream so it doesn't send events anymore.
2406     * @return {Boolean} true if this call paused the worker, false otherwise.
2407     */
2408    pause : function () {
2409        if(this.isPaused || this.isFinished) {
2410            return false;
2411        }
2412        this.isPaused = true;
2413
2414        if(this.previous) {
2415            this.previous.pause();
2416        }
2417        return true;
2418    },
2419    /**
2420     * Resume a paused stream.
2421     * @return {Boolean} true if this call resumed the worker, false otherwise.
2422     */
2423    resume : function () {
2424        if(!this.isPaused || this.isFinished) {
2425            return false;
2426        }
2427        this.isPaused = false;
2428
2429        // if true, the worker tried to resume but failed
2430        var withError = false;
2431        if(this.generatedError) {
2432            this.error(this.generatedError);
2433            withError = true;
2434        }
2435        if(this.previous) {
2436            this.previous.resume();
2437        }
2438
2439        return !withError;
2440    },
2441    /**
2442     * Flush any remaining bytes as the stream is ending.
2443     */
2444    flush : function () {},
2445    /**
2446     * Process a chunk. This is usually the method overridden.
2447     * @param {Object} chunk the chunk to process.
2448     */
2449    processChunk : function(chunk) {
2450        this.push(chunk);
2451    },
2452    /**
2453     * Add a key/value to be added in the workers chain streamInfo once activated.
2454     * @param {String} key the key to use
2455     * @param {Object} value the associated value
2456     * @return {Worker} the current worker for chainability
2457     */
2458    withStreamInfo : function (key, value) {
2459        this.extraStreamInfo[key] = value;
2460        this.mergeStreamInfo();
2461        return this;
2462    },
2463    /**
2464     * Merge this worker's streamInfo into the chain's streamInfo.
2465     */
2466    mergeStreamInfo : function () {
2467        for(var key in this.extraStreamInfo) {
2468            if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key)) {
2469                continue;
2470            }
2471            this.streamInfo[key] = this.extraStreamInfo[key];
2472        }
2473    },
2474
2475    /**
2476     * Lock the stream to prevent further updates on the workers chain.
2477     * After calling this method, all calls to pipe will fail.
2478     */
2479    lock: function () {
2480        if (this.isLocked) {
2481            throw new Error("The stream '" + this + "' has already been used.");
2482        }
2483        this.isLocked = true;
2484        if (this.previous) {
2485            this.previous.lock();
2486        }
2487    },
2488
2489    /**
2490     *
2491     * Pretty print the workers chain.
2492     */
2493    toString : function () {
2494        var me = "Worker " + this.name;
2495        if (this.previous) {
2496            return this.previous + " -> " + me;
2497        } else {
2498            return me;
2499        }
2500    }
2501};
2502
2503module.exports = GenericWorker;
2504
2505},{}],29:[function(require,module,exports){
2506"use strict";
2507
2508var utils = require("../utils");
2509var ConvertWorker = require("./ConvertWorker");
2510var GenericWorker = require("./GenericWorker");
2511var base64 = require("../base64");
2512var support = require("../support");
2513var external = require("../external");
2514
2515var NodejsStreamOutputAdapter = null;
2516if (support.nodestream) {
2517    try {
2518        NodejsStreamOutputAdapter = require("../nodejs/NodejsStreamOutputAdapter");
2519    } catch(e) {
2520        // ignore
2521    }
2522}
2523
2524/**
2525 * Apply the final transformation of the data. If the user wants a Blob for
2526 * example, it's easier to work with an U8intArray and finally do the
2527 * ArrayBuffer/Blob conversion.
2528 * @param {String} type the name of the final type
2529 * @param {String|Uint8Array|Buffer} content the content to transform
2530 * @param {String} mimeType the mime type of the content, if applicable.
2531 * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
2532 */
2533function transformZipOutput(type, content, mimeType) {
2534    switch(type) {
2535    case "blob" :
2536        return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
2537    case "base64" :
2538        return base64.encode(content);
2539    default :
2540        return utils.transformTo(type, content);
2541    }
2542}
2543
2544/**
2545 * Concatenate an array of data of the given type.
2546 * @param {String} type the type of the data in the given array.
2547 * @param {Array} dataArray the array containing the data chunks to concatenate
2548 * @return {String|Uint8Array|Buffer} the concatenated data
2549 * @throws Error if the asked type is unsupported
2550 */
2551function concat (type, dataArray) {
2552    var i, index = 0, res = null, totalLength = 0;
2553    for(i = 0; i < dataArray.length; i++) {
2554        totalLength += dataArray[i].length;
2555    }
2556    switch(type) {
2557    case "string":
2558        return dataArray.join("");
2559    case "array":
2560        return Array.prototype.concat.apply([], dataArray);
2561    case "uint8array":
2562        res = new Uint8Array(totalLength);
2563        for(i = 0; i < dataArray.length; i++) {
2564            res.set(dataArray[i], index);
2565            index += dataArray[i].length;
2566        }
2567        return res;
2568    case "nodebuffer":
2569        return Buffer.concat(dataArray);
2570    default:
2571        throw new Error("concat : unsupported type '"  + type + "'");
2572    }
2573}
2574
2575/**
2576 * Listen a StreamHelper, accumulate its content and concatenate it into a
2577 * complete block.
2578 * @param {StreamHelper} helper the helper to use.
2579 * @param {Function} updateCallback a callback called on each update. Called
2580 * with one arg :
2581 * - the metadata linked to the update received.
2582 * @return Promise the promise for the accumulation.
2583 */
2584function accumulate(helper, updateCallback) {
2585    return new external.Promise(function (resolve, reject){
2586        var dataArray = [];
2587        var chunkType = helper._internalType,
2588            resultType = helper._outputType,
2589            mimeType = helper._mimeType;
2590        helper
2591            .on("data", function (data, meta) {
2592                dataArray.push(data);
2593                if(updateCallback) {
2594                    updateCallback(meta);
2595                }
2596            })
2597            .on("error", function(err) {
2598                dataArray = [];
2599                reject(err);
2600            })
2601            .on("end", function (){
2602                try {
2603                    var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
2604                    resolve(result);
2605                } catch (e) {
2606                    reject(e);
2607                }
2608                dataArray = [];
2609            })
2610            .resume();
2611    });
2612}
2613
2614/**
2615 * An helper to easily use workers outside of JSZip.
2616 * @constructor
2617 * @param {Worker} worker the worker to wrap
2618 * @param {String} outputType the type of data expected by the use
2619 * @param {String} mimeType the mime type of the content, if applicable.
2620 */
2621function StreamHelper(worker, outputType, mimeType) {
2622    var internalType = outputType;
2623    switch(outputType) {
2624    case "blob":
2625    case "arraybuffer":
2626        internalType = "uint8array";
2627        break;
2628    case "base64":
2629        internalType = "string";
2630        break;
2631    }
2632
2633    try {
2634        // the type used internally
2635        this._internalType = internalType;
2636        // the type used to output results
2637        this._outputType = outputType;
2638        // the mime type
2639        this._mimeType = mimeType;
2640        utils.checkSupport(internalType);
2641        this._worker = worker.pipe(new ConvertWorker(internalType));
2642        // the last workers can be rewired without issues but we need to
2643        // prevent any updates on previous workers.
2644        worker.lock();
2645    } catch(e) {
2646        this._worker = new GenericWorker("error");
2647        this._worker.error(e);
2648    }
2649}
2650
2651StreamHelper.prototype = {
2652    /**
2653     * Listen a StreamHelper, accumulate its content and concatenate it into a
2654     * complete block.
2655     * @param {Function} updateCb the update callback.
2656     * @return Promise the promise for the accumulation.
2657     */
2658    accumulate : function (updateCb) {
2659        return accumulate(this, updateCb);
2660    },
2661    /**
2662     * Add a listener on an event triggered on a stream.
2663     * @param {String} evt the name of the event
2664     * @param {Function} fn the listener
2665     * @return {StreamHelper} the current helper.
2666     */
2667    on : function (evt, fn) {
2668        var self = this;
2669
2670        if(evt === "data") {
2671            this._worker.on(evt, function (chunk) {
2672                fn.call(self, chunk.data, chunk.meta);
2673            });
2674        } else {
2675            this._worker.on(evt, function () {
2676                utils.delay(fn, arguments, self);
2677            });
2678        }
2679        return this;
2680    },
2681    /**
2682     * Resume the flow of chunks.
2683     * @return {StreamHelper} the current helper.
2684     */
2685    resume : function () {
2686        utils.delay(this._worker.resume, [], this._worker);
2687        return this;
2688    },
2689    /**
2690     * Pause the flow of chunks.
2691     * @return {StreamHelper} the current helper.
2692     */
2693    pause : function () {
2694        this._worker.pause();
2695        return this;
2696    },
2697    /**
2698     * Return a nodejs stream for this helper.
2699     * @param {Function} updateCb the update callback.
2700     * @return {NodejsStreamOutputAdapter} the nodejs stream.
2701     */
2702    toNodejsStream : function (updateCb) {
2703        utils.checkSupport("nodestream");
2704        if (this._outputType !== "nodebuffer") {
2705            // an object stream containing blob/arraybuffer/uint8array/string
2706            // is strange and I don't know if it would be useful.
2707            // I you find this comment and have a good usecase, please open a
2708            // bug report !
2709            throw new Error(this._outputType + " is not supported by this method");
2710        }
2711
2712        return new NodejsStreamOutputAdapter(this, {
2713            objectMode : this._outputType !== "nodebuffer"
2714        }, updateCb);
2715    }
2716};
2717
2718
2719module.exports = StreamHelper;
2720
2721},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
2722"use strict";
2723
2724exports.base64 = true;
2725exports.array = true;
2726exports.string = true;
2727exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
2728exports.nodebuffer = typeof Buffer !== "undefined";
2729// contains true if JSZip can read/generate Uint8Array, false otherwise.
2730exports.uint8array = typeof Uint8Array !== "undefined";
2731
2732if (typeof ArrayBuffer === "undefined") {
2733    exports.blob = false;
2734}
2735else {
2736    var buffer = new ArrayBuffer(0);
2737    try {
2738        exports.blob = new Blob([buffer], {
2739            type: "application/zip"
2740        }).size === 0;
2741    }
2742    catch (e) {
2743        try {
2744            var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
2745            var builder = new Builder();
2746            builder.append(buffer);
2747            exports.blob = builder.getBlob("application/zip").size === 0;
2748        }
2749        catch (e) {
2750            exports.blob = false;
2751        }
2752    }
2753}
2754
2755try {
2756    exports.nodestream = !!require("readable-stream").Readable;
2757} catch(e) {
2758    exports.nodestream = false;
2759}
2760
2761},{"readable-stream":16}],31:[function(require,module,exports){
2762"use strict";
2763
2764var utils = require("./utils");
2765var support = require("./support");
2766var nodejsUtils = require("./nodejsUtils");
2767var GenericWorker = require("./stream/GenericWorker");
2768
2769/**
2770 * The following functions come from pako, from pako/lib/utils/strings
2771 * released under the MIT license, see pako https://github.com/nodeca/pako/
2772 */
2773
2774// Table with utf8 lengths (calculated by first byte of sequence)
2775// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
2776// because max possible codepoint is 0x10ffff
2777var _utf8len = new Array(256);
2778for (var i=0; i<256; i++) {
2779    _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
2780}
2781_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
2782
2783// convert string to array (typed, when possible)
2784var string2buf = function (str) {
2785    var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
2786
2787    // count binary size
2788    for (m_pos = 0; m_pos < str_len; m_pos++) {
2789        c = str.charCodeAt(m_pos);
2790        if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
2791            c2 = str.charCodeAt(m_pos+1);
2792            if ((c2 & 0xfc00) === 0xdc00) {
2793                c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
2794                m_pos++;
2795            }
2796        }
2797        buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
2798    }
2799
2800    // allocate buffer
2801    if (support.uint8array) {
2802        buf = new Uint8Array(buf_len);
2803    } else {
2804        buf = new Array(buf_len);
2805    }
2806
2807    // convert
2808    for (i=0, m_pos = 0; i < buf_len; m_pos++) {
2809        c = str.charCodeAt(m_pos);
2810        if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
2811            c2 = str.charCodeAt(m_pos+1);
2812            if ((c2 & 0xfc00) === 0xdc00) {
2813                c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
2814                m_pos++;
2815            }
2816        }
2817        if (c < 0x80) {
2818            /* one byte */
2819            buf[i++] = c;
2820        } else if (c < 0x800) {
2821            /* two bytes */
2822            buf[i++] = 0xC0 | (c >>> 6);
2823            buf[i++] = 0x80 | (c & 0x3f);
2824        } else if (c < 0x10000) {
2825            /* three bytes */
2826            buf[i++] = 0xE0 | (c >>> 12);
2827            buf[i++] = 0x80 | (c >>> 6 & 0x3f);
2828            buf[i++] = 0x80 | (c & 0x3f);
2829        } else {
2830            /* four bytes */
2831            buf[i++] = 0xf0 | (c >>> 18);
2832            buf[i++] = 0x80 | (c >>> 12 & 0x3f);
2833            buf[i++] = 0x80 | (c >>> 6 & 0x3f);
2834            buf[i++] = 0x80 | (c & 0x3f);
2835        }
2836    }
2837
2838    return buf;
2839};
2840
2841// Calculate max possible position in utf8 buffer,
2842// that will not break sequence. If that's not possible
2843// - (very small limits) return max size as is.
2844//
2845// buf[] - utf8 bytes array
2846// max   - length limit (mandatory);
2847var utf8border = function(buf, max) {
2848    var pos;
2849
2850    max = max || buf.length;
2851    if (max > buf.length) { max = buf.length; }
2852
2853    // go back from last position, until start of sequence found
2854    pos = max-1;
2855    while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
2856
2857    // Fuckup - very small and broken sequence,
2858    // return max, because we should return something anyway.
2859    if (pos < 0) { return max; }
2860
2861    // If we came to start of buffer - that means vuffer is too small,
2862    // return max too.
2863    if (pos === 0) { return max; }
2864
2865    return (pos + _utf8len[buf[pos]] > max) ? pos : max;
2866};
2867
2868// convert array to string
2869var buf2string = function (buf) {
2870    var i, out, c, c_len;
2871    var len = buf.length;
2872
2873    // Reserve max possible length (2 words per char)
2874    // NB: by unknown reasons, Array is significantly faster for
2875    //     String.fromCharCode.apply than Uint16Array.
2876    var utf16buf = new Array(len*2);
2877
2878    for (out=0, i=0; i<len;) {
2879        c = buf[i++];
2880        // quick process ascii
2881        if (c < 0x80) { utf16buf[out++] = c; continue; }
2882
2883        c_len = _utf8len[c];
2884        // skip 5 & 6 byte codes
2885        if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
2886
2887        // apply mask on first byte
2888        c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
2889        // join the rest
2890        while (c_len > 1 && i < len) {
2891            c = (c << 6) | (buf[i++] & 0x3f);
2892            c_len--;
2893        }
2894
2895        // terminated by end of string?
2896        if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
2897
2898        if (c < 0x10000) {
2899            utf16buf[out++] = c;
2900        } else {
2901            c -= 0x10000;
2902            utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
2903            utf16buf[out++] = 0xdc00 | (c & 0x3ff);
2904        }
2905    }
2906
2907    // shrinkBuf(utf16buf, out)
2908    if (utf16buf.length !== out) {
2909        if(utf16buf.subarray) {
2910            utf16buf = utf16buf.subarray(0, out);
2911        } else {
2912            utf16buf.length = out;
2913        }
2914    }
2915
2916    // return String.fromCharCode.apply(null, utf16buf);
2917    return utils.applyFromCharCode(utf16buf);
2918};
2919
2920
2921// That's all for the pako functions.
2922
2923
2924/**
2925 * Transform a javascript string into an array (typed if possible) of bytes,
2926 * UTF-8 encoded.
2927 * @param {String} str the string to encode
2928 * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
2929 */
2930exports.utf8encode = function utf8encode(str) {
2931    if (support.nodebuffer) {
2932        return nodejsUtils.newBufferFrom(str, "utf-8");
2933    }
2934
2935    return string2buf(str);
2936};
2937
2938
2939/**
2940 * Transform a bytes array (or a representation) representing an UTF-8 encoded
2941 * string into a javascript string.
2942 * @param {Array|Uint8Array|Buffer} buf the data de decode
2943 * @return {String} the decoded string.
2944 */
2945exports.utf8decode = function utf8decode(buf) {
2946    if (support.nodebuffer) {
2947        return utils.transformTo("nodebuffer", buf).toString("utf-8");
2948    }
2949
2950    buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
2951
2952    return buf2string(buf);
2953};
2954
2955/**
2956 * A worker to decode utf8 encoded binary chunks into string chunks.
2957 * @constructor
2958 */
2959function Utf8DecodeWorker() {
2960    GenericWorker.call(this, "utf-8 decode");
2961    // the last bytes if a chunk didn't end with a complete codepoint.
2962    this.leftOver = null;
2963}
2964utils.inherits(Utf8DecodeWorker, GenericWorker);
2965
2966/**
2967 * @see GenericWorker.processChunk
2968 */
2969Utf8DecodeWorker.prototype.processChunk = function (chunk) {
2970
2971    var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
2972
2973    // 1st step, re-use what's left of the previous chunk
2974    if (this.leftOver && this.leftOver.length) {
2975        if(support.uint8array) {
2976            var previousData = data;
2977            data = new Uint8Array(previousData.length + this.leftOver.length);
2978            data.set(this.leftOver, 0);
2979            data.set(previousData, this.leftOver.length);
2980        } else {
2981            data = this.leftOver.concat(data);
2982        }
2983        this.leftOver = null;
2984    }
2985
2986    var nextBoundary = utf8border(data);
2987    var usableData = data;
2988    if (nextBoundary !== data.length) {
2989        if (support.uint8array) {
2990            usableData = data.subarray(0, nextBoundary);
2991            this.leftOver = data.subarray(nextBoundary, data.length);
2992        } else {
2993            usableData = data.slice(0, nextBoundary);
2994            this.leftOver = data.slice(nextBoundary, data.length);
2995        }
2996    }
2997
2998    this.push({
2999        data : exports.utf8decode(usableData),
3000        meta : chunk.meta
3001    });
3002};
3003
3004/**
3005 * @see GenericWorker.flush
3006 */
3007Utf8DecodeWorker.prototype.flush = function () {
3008    if(this.leftOver && this.leftOver.length) {
3009        this.push({
3010            data : exports.utf8decode(this.leftOver),
3011            meta : {}
3012        });
3013        this.leftOver = null;
3014    }
3015};
3016exports.Utf8DecodeWorker = Utf8DecodeWorker;
3017
3018/**
3019 * A worker to endcode string chunks into utf8 encoded binary chunks.
3020 * @constructor
3021 */
3022function Utf8EncodeWorker() {
3023    GenericWorker.call(this, "utf-8 encode");
3024}
3025utils.inherits(Utf8EncodeWorker, GenericWorker);
3026
3027/**
3028 * @see GenericWorker.processChunk
3029 */
3030Utf8EncodeWorker.prototype.processChunk = function (chunk) {
3031    this.push({
3032        data : exports.utf8encode(chunk.data),
3033        meta : chunk.meta
3034    });
3035};
3036exports.Utf8EncodeWorker = Utf8EncodeWorker;
3037
3038},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
3039"use strict";
3040
3041var support = require("./support");
3042var base64 = require("./base64");
3043var nodejsUtils = require("./nodejsUtils");
3044var external = require("./external");
3045require("setimmediate");
3046
3047
3048/**
3049 * Convert a string that pass as a "binary string": it should represent a byte
3050 * array but may have > 255 char codes. Be sure to take only the first byte
3051 * and returns the byte array.
3052 * @param {String} str the string to transform.
3053 * @return {Array|Uint8Array} the string in a binary format.
3054 */
3055function string2binary(str) {
3056    var result = null;
3057    if (support.uint8array) {
3058        result = new Uint8Array(str.length);
3059    } else {
3060        result = new Array(str.length);
3061    }
3062    return stringToArrayLike(str, result);
3063}
3064
3065/**
3066 * Create a new blob with the given content and the given type.
3067 * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
3068 * an Uint8Array because the stock browser of android 4 won't accept it (it
3069 * will be silently converted to a string, "[object Uint8Array]").
3070 *
3071 * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
3072 * when a large amount of Array is used to create the Blob, the amount of
3073 * memory consumed is nearly 100 times the original data amount.
3074 *
3075 * @param {String} type the mime type of the blob.
3076 * @return {Blob} the created blob.
3077 */
3078exports.newBlob = function(part, type) {
3079    exports.checkSupport("blob");
3080
3081    try {
3082        // Blob constructor
3083        return new Blob([part], {
3084            type: type
3085        });
3086    }
3087    catch (e) {
3088
3089        try {
3090            // deprecated, browser only, old way
3091            var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
3092            var builder = new Builder();
3093            builder.append(part);
3094            return builder.getBlob(type);
3095        }
3096        catch (e) {
3097
3098            // well, fuck ?!
3099            throw new Error("Bug : can't construct the Blob.");
3100        }
3101    }
3102
3103
3104};
3105/**
3106 * The identity function.
3107 * @param {Object} input the input.
3108 * @return {Object} the same input.
3109 */
3110function identity(input) {
3111    return input;
3112}
3113
3114/**
3115 * Fill in an array with a string.
3116 * @param {String} str the string to use.
3117 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
3118 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
3119 */
3120function stringToArrayLike(str, array) {
3121    for (var i = 0; i < str.length; ++i) {
3122        array[i] = str.charCodeAt(i) & 0xFF;
3123    }
3124    return array;
3125}
3126
3127/**
3128 * An helper for the function arrayLikeToString.
3129 * This contains static information and functions that
3130 * can be optimized by the browser JIT compiler.
3131 */
3132var arrayToStringHelper = {
3133    /**
3134     * Transform an array of int into a string, chunk by chunk.
3135     * See the performances notes on arrayLikeToString.
3136     * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
3137     * @param {String} type the type of the array.
3138     * @param {Integer} chunk the chunk size.
3139     * @return {String} the resulting string.
3140     * @throws Error if the chunk is too big for the stack.
3141     */
3142    stringifyByChunk: function(array, type, chunk) {
3143        var result = [], k = 0, len = array.length;
3144        // shortcut
3145        if (len <= chunk) {
3146            return String.fromCharCode.apply(null, array);
3147        }
3148        while (k < len) {
3149            if (type === "array" || type === "nodebuffer") {
3150                result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
3151            }
3152            else {
3153                result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
3154            }
3155            k += chunk;
3156        }
3157        return result.join("");
3158    },
3159    /**
3160     * Call String.fromCharCode on every item in the array.
3161     * This is the naive implementation, which generate A LOT of intermediate string.
3162     * This should be used when everything else fail.
3163     * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
3164     * @return {String} the result.
3165     */
3166    stringifyByChar: function(array){
3167        var resultStr = "";
3168        for(var i = 0; i < array.length; i++) {
3169            resultStr += String.fromCharCode(array[i]);
3170        }
3171        return resultStr;
3172    },
3173    applyCanBeUsed : {
3174        /**
3175         * true if the browser accepts to use String.fromCharCode on Uint8Array
3176         */
3177        uint8array : (function () {
3178            try {
3179                return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
3180            } catch (e) {
3181                return false;
3182            }
3183        })(),
3184        /**
3185         * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
3186         */
3187        nodebuffer : (function () {
3188            try {
3189                return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
3190            } catch (e) {
3191                return false;
3192            }
3193        })()
3194    }
3195};
3196
3197/**
3198 * Transform an array-like object to a string.
3199 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
3200 * @return {String} the result.
3201 */
3202function arrayLikeToString(array) {
3203    // Performances notes :
3204    // --------------------
3205    // String.fromCharCode.apply(null, array) is the fastest, see
3206    // see http://jsperf.com/converting-a-uint8array-to-a-string/2
3207    // but the stack is limited (and we can get huge arrays !).
3208    //
3209    // result += String.fromCharCode(array[i]); generate too many strings !
3210    //
3211    // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
3212    // TODO : we now have workers that split the work. Do we still need that ?
3213    var chunk = 65536,
3214        type = exports.getTypeOf(array),
3215        canUseApply = true;
3216    if (type === "uint8array") {
3217        canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
3218    } else if (type === "nodebuffer") {
3219        canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
3220    }
3221
3222    if (canUseApply) {
3223        while (chunk > 1) {
3224            try {
3225                return arrayToStringHelper.stringifyByChunk(array, type, chunk);
3226            } catch (e) {
3227                chunk = Math.floor(chunk / 2);
3228            }
3229        }
3230    }
3231
3232    // no apply or chunk error : slow and painful algorithm
3233    // default browser on android 4.*
3234    return arrayToStringHelper.stringifyByChar(array);
3235}
3236
3237exports.applyFromCharCode = arrayLikeToString;
3238
3239
3240/**
3241 * Copy the data from an array-like to an other array-like.
3242 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
3243 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
3244 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
3245 */
3246function arrayLikeToArrayLike(arrayFrom, arrayTo) {
3247    for (var i = 0; i < arrayFrom.length; i++) {
3248        arrayTo[i] = arrayFrom[i];
3249    }
3250    return arrayTo;
3251}
3252
3253// a matrix containing functions to transform everything into everything.
3254var transform = {};
3255
3256// string to ?
3257transform["string"] = {
3258    "string": identity,
3259    "array": function(input) {
3260        return stringToArrayLike(input, new Array(input.length));
3261    },
3262    "arraybuffer": function(input) {
3263        return transform["string"]["uint8array"](input).buffer;
3264    },
3265    "uint8array": function(input) {
3266        return stringToArrayLike(input, new Uint8Array(input.length));
3267    },
3268    "nodebuffer": function(input) {
3269        return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
3270    }
3271};
3272
3273// array to ?
3274transform["array"] = {
3275    "string": arrayLikeToString,
3276    "array": identity,
3277    "arraybuffer": function(input) {
3278        return (new Uint8Array(input)).buffer;
3279    },
3280    "uint8array": function(input) {
3281        return new Uint8Array(input);
3282    },
3283    "nodebuffer": function(input) {
3284        return nodejsUtils.newBufferFrom(input);
3285    }
3286};
3287
3288// arraybuffer to ?
3289transform["arraybuffer"] = {
3290    "string": function(input) {
3291        return arrayLikeToString(new Uint8Array(input));
3292    },
3293    "array": function(input) {
3294        return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
3295    },
3296    "arraybuffer": identity,
3297    "uint8array": function(input) {
3298        return new Uint8Array(input);
3299    },
3300    "nodebuffer": function(input) {
3301        return nodejsUtils.newBufferFrom(new Uint8Array(input));
3302    }
3303};
3304
3305// uint8array to ?
3306transform["uint8array"] = {
3307    "string": arrayLikeToString,
3308    "array": function(input) {
3309        return arrayLikeToArrayLike(input, new Array(input.length));
3310    },
3311    "arraybuffer": function(input) {
3312        return input.buffer;
3313    },
3314    "uint8array": identity,
3315    "nodebuffer": function(input) {
3316        return nodejsUtils.newBufferFrom(input);
3317    }
3318};
3319
3320// nodebuffer to ?
3321transform["nodebuffer"] = {
3322    "string": arrayLikeToString,
3323    "array": function(input) {
3324        return arrayLikeToArrayLike(input, new Array(input.length));
3325    },
3326    "arraybuffer": function(input) {
3327        return transform["nodebuffer"]["uint8array"](input).buffer;
3328    },
3329    "uint8array": function(input) {
3330        return arrayLikeToArrayLike(input, new Uint8Array(input.length));
3331    },
3332    "nodebuffer": identity
3333};
3334
3335/**
3336 * Transform an input into any type.
3337 * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
3338 * If no output type is specified, the unmodified input will be returned.
3339 * @param {String} outputType the output type.
3340 * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
3341 * @throws {Error} an Error if the browser doesn't support the requested output type.
3342 */
3343exports.transformTo = function(outputType, input) {
3344    if (!input) {
3345        // undefined, null, etc
3346        // an empty string won't harm.
3347        input = "";
3348    }
3349    if (!outputType) {
3350        return input;
3351    }
3352    exports.checkSupport(outputType);
3353    var inputType = exports.getTypeOf(input);
3354    var result = transform[inputType][outputType](input);
3355    return result;
3356};
3357
3358/**
3359 * Resolve all relative path components, "." and "..", in a path. If these relative components
3360 * traverse above the root then the resulting path will only contain the final path component.
3361 *
3362 * All empty components, e.g. "//", are removed.
3363 * @param {string} path A path with / or \ separators
3364 * @returns {string} The path with all relative path components resolved.
3365 */
3366exports.resolve = function(path) {
3367    var parts = path.split("/");
3368    var result = [];
3369    for (var index = 0; index < parts.length; index++) {
3370        var part = parts[index];
3371        // Allow the first and last component to be empty for trailing slashes.
3372        if (part === "." || (part === "" && index !== 0 && index !== parts.length - 1)) {
3373            continue;
3374        } else if (part === "..") {
3375            result.pop();
3376        } else {
3377            result.push(part);
3378        }
3379    }
3380    return result.join("/");
3381};
3382
3383/**
3384 * Return the type of the input.
3385 * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
3386 * @param {Object} input the input to identify.
3387 * @return {String} the (lowercase) type of the input.
3388 */
3389exports.getTypeOf = function(input) {
3390    if (typeof input === "string") {
3391        return "string";
3392    }
3393    if (Object.prototype.toString.call(input) === "[object Array]") {
3394        return "array";
3395    }
3396    if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
3397        return "nodebuffer";
3398    }
3399    if (support.uint8array && input instanceof Uint8Array) {
3400        return "uint8array";
3401    }
3402    if (support.arraybuffer && input instanceof ArrayBuffer) {
3403        return "arraybuffer";
3404    }
3405};
3406
3407/**
3408 * Throw an exception if the type is not supported.
3409 * @param {String} type the type to check.
3410 * @throws {Error} an Error if the browser doesn't support the requested type.
3411 */
3412exports.checkSupport = function(type) {
3413    var supported = support[type.toLowerCase()];
3414    if (!supported) {
3415        throw new Error(type + " is not supported by this platform");
3416    }
3417};
3418
3419exports.MAX_VALUE_16BITS = 65535;
3420exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
3421
3422/**
3423 * Prettify a string read as binary.
3424 * @param {string} str the string to prettify.
3425 * @return {string} a pretty string.
3426 */
3427exports.pretty = function(str) {
3428    var res = "",
3429        code, i;
3430    for (i = 0; i < (str || "").length; i++) {
3431        code = str.charCodeAt(i);
3432        res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
3433    }
3434    return res;
3435};
3436
3437/**
3438 * Defer the call of a function.
3439 * @param {Function} callback the function to call asynchronously.
3440 * @param {Array} args the arguments to give to the callback.
3441 */
3442exports.delay = function(callback, args, self) {
3443    setImmediate(function () {
3444        callback.apply(self || null, args || []);
3445    });
3446};
3447
3448/**
3449 * Extends a prototype with an other, without calling a constructor with
3450 * side effects. Inspired by nodejs' `utils.inherits`
3451 * @param {Function} ctor the constructor to augment
3452 * @param {Function} superCtor the parent constructor to use
3453 */
3454exports.inherits = function (ctor, superCtor) {
3455    var Obj = function() {};
3456    Obj.prototype = superCtor.prototype;
3457    ctor.prototype = new Obj();
3458};
3459
3460/**
3461 * Merge the objects passed as parameters into a new one.
3462 * @private
3463 * @param {...Object} var_args All objects to merge.
3464 * @return {Object} a new object with the data of the others.
3465 */
3466exports.extend = function() {
3467    var result = {}, i, attr;
3468    for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
3469        for (attr in arguments[i]) {
3470            if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") {
3471                result[attr] = arguments[i][attr];
3472            }
3473        }
3474    }
3475    return result;
3476};
3477
3478/**
3479 * Transform arbitrary content into a Promise.
3480 * @param {String} name a name for the content being processed.
3481 * @param {Object} inputData the content to process.
3482 * @param {Boolean} isBinary true if the content is not an unicode string
3483 * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
3484 * @param {Boolean} isBase64 true if the string content is encoded with base64.
3485 * @return {Promise} a promise in a format usable by JSZip.
3486 */
3487exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
3488
3489    // if inputData is already a promise, this flatten it.
3490    var promise = external.Promise.resolve(inputData).then(function(data) {
3491
3492
3493        var isBlob = support.blob && (data instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data)) !== -1);
3494
3495        if (isBlob && typeof FileReader !== "undefined") {
3496            return new external.Promise(function (resolve, reject) {
3497                var reader = new FileReader();
3498
3499                reader.onload = function(e) {
3500                    resolve(e.target.result);
3501                };
3502                reader.onerror = function(e) {
3503                    reject(e.target.error);
3504                };
3505                reader.readAsArrayBuffer(data);
3506            });
3507        } else {
3508            return data;
3509        }
3510    });
3511
3512    return promise.then(function(data) {
3513        var dataType = exports.getTypeOf(data);
3514
3515        if (!dataType) {
3516            return external.Promise.reject(
3517                new Error("Can't read the data of '" + name + "'. Is it " +
3518                          "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
3519            );
3520        }
3521        // special case : it's way easier to work with Uint8Array than with ArrayBuffer
3522        if (dataType === "arraybuffer") {
3523            data = exports.transformTo("uint8array", data);
3524        } else if (dataType === "string") {
3525            if (isBase64) {
3526                data = base64.decode(data);
3527            }
3528            else if (isBinary) {
3529                // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
3530                if (isOptimizedBinaryString !== true) {
3531                    // this is a string, not in a base64 format.
3532                    // Be sure that this is a correct "binary string"
3533                    data = string2binary(data);
3534                }
3535            }
3536        }
3537        return data;
3538    });
3539};
3540
3541},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"setimmediate":54}],33:[function(require,module,exports){
3542"use strict";
3543var readerFor = require("./reader/readerFor");
3544var utils = require("./utils");
3545var sig = require("./signature");
3546var ZipEntry = require("./zipEntry");
3547var support = require("./support");
3548//  class ZipEntries {{{
3549/**
3550 * All the entries in the zip file.
3551 * @constructor
3552 * @param {Object} loadOptions Options for loading the stream.
3553 */
3554function ZipEntries(loadOptions) {
3555    this.files = [];
3556    this.loadOptions = loadOptions;
3557}
3558ZipEntries.prototype = {
3559    /**
3560     * Check that the reader is on the specified signature.
3561     * @param {string} expectedSignature the expected signature.
3562     * @throws {Error} if it is an other signature.
3563     */
3564    checkSignature: function(expectedSignature) {
3565        if (!this.reader.readAndCheckSignature(expectedSignature)) {
3566            this.reader.index -= 4;
3567            var signature = this.reader.readString(4);
3568            throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
3569        }
3570    },
3571    /**
3572     * Check if the given signature is at the given index.
3573     * @param {number} askedIndex the index to check.
3574     * @param {string} expectedSignature the signature to expect.
3575     * @return {boolean} true if the signature is here, false otherwise.
3576     */
3577    isSignature: function(askedIndex, expectedSignature) {
3578        var currentIndex = this.reader.index;
3579        this.reader.setIndex(askedIndex);
3580        var signature = this.reader.readString(4);
3581        var result = signature === expectedSignature;
3582        this.reader.setIndex(currentIndex);
3583        return result;
3584    },
3585    /**
3586     * Read the end of the central directory.
3587     */
3588    readBlockEndOfCentral: function() {
3589        this.diskNumber = this.reader.readInt(2);
3590        this.diskWithCentralDirStart = this.reader.readInt(2);
3591        this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
3592        this.centralDirRecords = this.reader.readInt(2);
3593        this.centralDirSize = this.reader.readInt(4);
3594        this.centralDirOffset = this.reader.readInt(4);
3595
3596        this.zipCommentLength = this.reader.readInt(2);
3597        // warning : the encoding depends of the system locale
3598        // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
3599        // On a windows machine, this field is encoded with the localized windows code page.
3600        var zipComment = this.reader.readData(this.zipCommentLength);
3601        var decodeParamType = support.uint8array ? "uint8array" : "array";
3602        // To get consistent behavior with the generation part, we will assume that
3603        // this is utf8 encoded unless specified otherwise.
3604        var decodeContent = utils.transformTo(decodeParamType, zipComment);
3605        this.zipComment = this.loadOptions.decodeFileName(decodeContent);
3606    },
3607    /**
3608     * Read the end of the Zip 64 central directory.
3609     * Not merged with the method readEndOfCentral :
3610     * The end of central can coexist with its Zip64 brother,
3611     * I don't want to read the wrong number of bytes !
3612     */
3613    readBlockZip64EndOfCentral: function() {
3614        this.zip64EndOfCentralSize = this.reader.readInt(8);
3615        this.reader.skip(4);
3616        // this.versionMadeBy = this.reader.readString(2);
3617        // this.versionNeeded = this.reader.readInt(2);
3618        this.diskNumber = this.reader.readInt(4);
3619        this.diskWithCentralDirStart = this.reader.readInt(4);
3620        this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
3621        this.centralDirRecords = this.reader.readInt(8);
3622        this.centralDirSize = this.reader.readInt(8);
3623        this.centralDirOffset = this.reader.readInt(8);
3624
3625        this.zip64ExtensibleData = {};
3626        var extraDataSize = this.zip64EndOfCentralSize - 44,
3627            index = 0,
3628            extraFieldId,
3629            extraFieldLength,
3630            extraFieldValue;
3631        while (index < extraDataSize) {
3632            extraFieldId = this.reader.readInt(2);
3633            extraFieldLength = this.reader.readInt(4);
3634            extraFieldValue = this.reader.readData(extraFieldLength);
3635            this.zip64ExtensibleData[extraFieldId] = {
3636                id: extraFieldId,
3637                length: extraFieldLength,
3638                value: extraFieldValue
3639            };
3640        }
3641    },
3642    /**
3643     * Read the end of the Zip 64 central directory locator.
3644     */
3645    readBlockZip64EndOfCentralLocator: function() {
3646        this.diskWithZip64CentralDirStart = this.reader.readInt(4);
3647        this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
3648        this.disksCount = this.reader.readInt(4);
3649        if (this.disksCount > 1) {
3650            throw new Error("Multi-volumes zip are not supported");
3651        }
3652    },
3653    /**
3654     * Read the local files, based on the offset read in the central part.
3655     */
3656    readLocalFiles: function() {
3657        var i, file;
3658        for (i = 0; i < this.files.length; i++) {
3659            file = this.files[i];
3660            this.reader.setIndex(file.localHeaderOffset);
3661            this.checkSignature(sig.LOCAL_FILE_HEADER);
3662            file.readLocalPart(this.reader);
3663            file.handleUTF8();
3664            file.processAttributes();
3665        }
3666    },
3667    /**
3668     * Read the central directory.
3669     */
3670    readCentralDir: function() {
3671        var file;
3672
3673        this.reader.setIndex(this.centralDirOffset);
3674        while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
3675            file = new ZipEntry({
3676                zip64: this.zip64
3677            }, this.loadOptions);
3678            file.readCentralPart(this.reader);
3679            this.files.push(file);
3680        }
3681
3682        if (this.centralDirRecords !== this.files.length) {
3683            if (this.centralDirRecords !== 0 && this.files.length === 0) {
3684                // We expected some records but couldn't find ANY.
3685                // This is really suspicious, as if something went wrong.
3686                throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
3687            } else {
3688                // We found some records but not all.
3689                // Something is wrong but we got something for the user: no error here.
3690                // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
3691            }
3692        }
3693    },
3694    /**
3695     * Read the end of central directory.
3696     */
3697    readEndOfCentral: function() {
3698        var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
3699        if (offset < 0) {
3700            // Check if the content is a truncated zip or complete garbage.
3701            // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
3702            // extractible zip for example) but it can give a good hint.
3703            // If an ajax request was used without responseType, we will also
3704            // get unreadable data.
3705            var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
3706
3707            if (isGarbage) {
3708                throw new Error("Can't find end of central directory : is this a zip file ? " +
3709                                "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
3710            } else {
3711                throw new Error("Corrupted zip: can't find end of central directory");
3712            }
3713
3714        }
3715        this.reader.setIndex(offset);
3716        var endOfCentralDirOffset = offset;
3717        this.checkSignature(sig.CENTRAL_DIRECTORY_END);
3718        this.readBlockEndOfCentral();
3719
3720
3721        /* extract from the zip spec :
3722            4)  If one of the fields in the end of central directory
3723                record is too small to hold required data, the field
3724                should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
3725                ZIP64 format record should be created.
3726            5)  The end of central directory record and the
3727                Zip64 end of central directory locator record must
3728                reside on the same disk when splitting or spanning
3729                an archive.
3730         */
3731        if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
3732            this.zip64 = true;
3733
3734            /*
3735            Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
3736            the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents
3737            all numbers as 64-bit double precision IEEE 754 floating point numbers.
3738            So, we have 53bits for integers and bitwise operations treat everything as 32bits.
3739            see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
3740            and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
3741            */
3742
3743            // should look for a zip64 EOCD locator
3744            offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
3745            if (offset < 0) {
3746                throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
3747            }
3748            this.reader.setIndex(offset);
3749            this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
3750            this.readBlockZip64EndOfCentralLocator();
3751
3752            // now the zip64 EOCD record
3753            if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
3754                // console.warn("ZIP64 end of central directory not where expected.");
3755                this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
3756                if (this.relativeOffsetEndOfZip64CentralDir < 0) {
3757                    throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
3758                }
3759            }
3760            this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
3761            this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
3762            this.readBlockZip64EndOfCentral();
3763        }
3764
3765        var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
3766        if (this.zip64) {
3767            expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
3768            expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
3769        }
3770
3771        var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
3772
3773        if (extraBytes > 0) {
3774            // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
3775            if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
3776                // The offsets seem wrong, but we have something at the specified offset.
3777                // So… we keep it.
3778            } else {
3779                // the offset is wrong, update the "zero" of the reader
3780                // this happens if data has been prepended (crx files for example)
3781                this.reader.zero = extraBytes;
3782            }
3783        } else if (extraBytes < 0) {
3784            throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
3785        }
3786    },
3787    prepareReader: function(data) {
3788        this.reader = readerFor(data);
3789    },
3790    /**
3791     * Read a zip file and create ZipEntries.
3792     * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
3793     */
3794    load: function(data) {
3795        this.prepareReader(data);
3796        this.readEndOfCentral();
3797        this.readCentralDir();
3798        this.readLocalFiles();
3799    }
3800};
3801// }}} end of ZipEntries
3802module.exports = ZipEntries;
3803
3804},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
3805"use strict";
3806var readerFor = require("./reader/readerFor");
3807var utils = require("./utils");
3808var CompressedObject = require("./compressedObject");
3809var crc32fn = require("./crc32");
3810var utf8 = require("./utf8");
3811var compressions = require("./compressions");
3812var support = require("./support");
3813
3814var MADE_BY_DOS = 0x00;
3815var MADE_BY_UNIX = 0x03;
3816
3817/**
3818 * Find a compression registered in JSZip.
3819 * @param {string} compressionMethod the method magic to find.
3820 * @return {Object|null} the JSZip compression object, null if none found.
3821 */
3822var findCompression = function(compressionMethod) {
3823    for (var method in compressions) {
3824        if (!Object.prototype.hasOwnProperty.call(compressions, method)) {
3825            continue;
3826        }
3827        if (compressions[method].magic === compressionMethod) {
3828            return compressions[method];
3829        }
3830    }
3831    return null;
3832};
3833
3834// class ZipEntry {{{
3835/**
3836 * An entry in the zip file.
3837 * @constructor
3838 * @param {Object} options Options of the current file.
3839 * @param {Object} loadOptions Options for loading the stream.
3840 */
3841function ZipEntry(options, loadOptions) {
3842    this.options = options;
3843    this.loadOptions = loadOptions;
3844}
3845ZipEntry.prototype = {
3846    /**
3847     * say if the file is encrypted.
3848     * @return {boolean} true if the file is encrypted, false otherwise.
3849     */
3850    isEncrypted: function() {
3851        // bit 1 is set
3852        return (this.bitFlag & 0x0001) === 0x0001;
3853    },
3854    /**
3855     * say if the file has utf-8 filename/comment.
3856     * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
3857     */
3858    useUTF8: function() {
3859        // bit 11 is set
3860        return (this.bitFlag & 0x0800) === 0x0800;
3861    },
3862    /**
3863     * Read the local part of a zip file and add the info in this object.
3864     * @param {DataReader} reader the reader to use.
3865     */
3866    readLocalPart: function(reader) {
3867        var compression, localExtraFieldsLength;
3868
3869        // we already know everything from the central dir !
3870        // If the central dir data are false, we are doomed.
3871        // On the bright side, the local part is scary  : zip64, data descriptors, both, etc.
3872        // The less data we get here, the more reliable this should be.
3873        // Let's skip the whole header and dash to the data !
3874        reader.skip(22);
3875        // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
3876        // Strangely, the filename here is OK.
3877        // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
3878        // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
3879        // Search "unzip mismatching "local" filename continuing with "central" filename version" on
3880        // the internet.
3881        //
3882        // I think I see the logic here : the central directory is used to display
3883        // content and the local directory is used to extract the files. Mixing / and \
3884        // may be used to display \ to windows users and use / when extracting the files.
3885        // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
3886        this.fileNameLength = reader.readInt(2);
3887        localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
3888        // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
3889        this.fileName = reader.readData(this.fileNameLength);
3890        reader.skip(localExtraFieldsLength);
3891
3892        if (this.compressedSize === -1 || this.uncompressedSize === -1) {
3893            throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
3894        }
3895
3896        compression = findCompression(this.compressionMethod);
3897        if (compression === null) { // no compression found
3898            throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
3899        }
3900        this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
3901    },
3902
3903    /**
3904     * Read the central part of a zip file and add the info in this object.
3905     * @param {DataReader} reader the reader to use.
3906     */
3907    readCentralPart: function(reader) {
3908        this.versionMadeBy = reader.readInt(2);
3909        reader.skip(2);
3910        // this.versionNeeded = reader.readInt(2);
3911        this.bitFlag = reader.readInt(2);
3912        this.compressionMethod = reader.readString(2);
3913        this.date = reader.readDate();
3914        this.crc32 = reader.readInt(4);
3915        this.compressedSize = reader.readInt(4);
3916        this.uncompressedSize = reader.readInt(4);
3917        var fileNameLength = reader.readInt(2);
3918        this.extraFieldsLength = reader.readInt(2);
3919        this.fileCommentLength = reader.readInt(2);
3920        this.diskNumberStart = reader.readInt(2);
3921        this.internalFileAttributes = reader.readInt(2);
3922        this.externalFileAttributes = reader.readInt(4);
3923        this.localHeaderOffset = reader.readInt(4);
3924
3925        if (this.isEncrypted()) {
3926            throw new Error("Encrypted zip are not supported");
3927        }
3928
3929        // will be read in the local part, see the comments there
3930        reader.skip(fileNameLength);
3931        this.readExtraFields(reader);
3932        this.parseZIP64ExtraField(reader);
3933        this.fileComment = reader.readData(this.fileCommentLength);
3934    },
3935
3936    /**
3937     * Parse the external file attributes and get the unix/dos permissions.
3938     */
3939    processAttributes: function () {
3940        this.unixPermissions = null;
3941        this.dosPermissions = null;
3942        var madeBy = this.versionMadeBy >> 8;
3943
3944        // Check if we have the DOS directory flag set.
3945        // We look for it in the DOS and UNIX permissions
3946        // but some unknown platform could set it as a compatibility flag.
3947        this.dir = this.externalFileAttributes & 0x0010 ? true : false;
3948
3949        if(madeBy === MADE_BY_DOS) {
3950            // first 6 bits (0 to 5)
3951            this.dosPermissions = this.externalFileAttributes & 0x3F;
3952        }
3953
3954        if(madeBy === MADE_BY_UNIX) {
3955            this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
3956            // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
3957        }
3958
3959        // fail safe : if the name ends with a / it probably means a folder
3960        if (!this.dir && this.fileNameStr.slice(-1) === "/") {
3961            this.dir = true;
3962        }
3963    },
3964
3965    /**
3966     * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
3967     * @param {DataReader} reader the reader to use.
3968     */
3969    parseZIP64ExtraField: function() {
3970        if (!this.extraFields[0x0001]) {
3971            return;
3972        }
3973
3974        // should be something, preparing the extra reader
3975        var extraReader = readerFor(this.extraFields[0x0001].value);
3976
3977        // I really hope that these 64bits integer can fit in 32 bits integer, because js
3978        // won't let us have more.
3979        if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
3980            this.uncompressedSize = extraReader.readInt(8);
3981        }
3982        if (this.compressedSize === utils.MAX_VALUE_32BITS) {
3983            this.compressedSize = extraReader.readInt(8);
3984        }
3985        if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
3986            this.localHeaderOffset = extraReader.readInt(8);
3987        }
3988        if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
3989            this.diskNumberStart = extraReader.readInt(4);
3990        }
3991    },
3992    /**
3993     * Read the central part of a zip file and add the info in this object.
3994     * @param {DataReader} reader the reader to use.
3995     */
3996    readExtraFields: function(reader) {
3997        var end = reader.index + this.extraFieldsLength,
3998            extraFieldId,
3999            extraFieldLength,
4000            extraFieldValue;
4001
4002        if (!this.extraFields) {
4003            this.extraFields = {};
4004        }
4005
4006        while (reader.index + 4 < end) {
4007            extraFieldId = reader.readInt(2);
4008            extraFieldLength = reader.readInt(2);
4009            extraFieldValue = reader.readData(extraFieldLength);
4010
4011            this.extraFields[extraFieldId] = {
4012                id: extraFieldId,
4013                length: extraFieldLength,
4014                value: extraFieldValue
4015            };
4016        }
4017
4018        reader.setIndex(end);
4019    },
4020    /**
4021     * Apply an UTF8 transformation if needed.
4022     */
4023    handleUTF8: function() {
4024        var decodeParamType = support.uint8array ? "uint8array" : "array";
4025        if (this.useUTF8()) {
4026            this.fileNameStr = utf8.utf8decode(this.fileName);
4027            this.fileCommentStr = utf8.utf8decode(this.fileComment);
4028        } else {
4029            var upath = this.findExtraFieldUnicodePath();
4030            if (upath !== null) {
4031                this.fileNameStr = upath;
4032            } else {
4033                // ASCII text or unsupported code page
4034                var fileNameByteArray =  utils.transformTo(decodeParamType, this.fileName);
4035                this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
4036            }
4037
4038            var ucomment = this.findExtraFieldUnicodeComment();
4039            if (ucomment !== null) {
4040                this.fileCommentStr = ucomment;
4041            } else {
4042                // ASCII text or unsupported code page
4043                var commentByteArray =  utils.transformTo(decodeParamType, this.fileComment);
4044                this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
4045            }
4046        }
4047    },
4048
4049    /**
4050     * Find the unicode path declared in the extra field, if any.
4051     * @return {String} the unicode path, null otherwise.
4052     */
4053    findExtraFieldUnicodePath: function() {
4054        var upathField = this.extraFields[0x7075];
4055        if (upathField) {
4056            var extraReader = readerFor(upathField.value);
4057
4058            // wrong version
4059            if (extraReader.readInt(1) !== 1) {
4060                return null;
4061            }
4062
4063            // the crc of the filename changed, this field is out of date.
4064            if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
4065                return null;
4066            }
4067
4068            return utf8.utf8decode(extraReader.readData(upathField.length - 5));
4069        }
4070        return null;
4071    },
4072
4073    /**
4074     * Find the unicode comment declared in the extra field, if any.
4075     * @return {String} the unicode comment, null otherwise.
4076     */
4077    findExtraFieldUnicodeComment: function() {
4078        var ucommentField = this.extraFields[0x6375];
4079        if (ucommentField) {
4080            var extraReader = readerFor(ucommentField.value);
4081
4082            // wrong version
4083            if (extraReader.readInt(1) !== 1) {
4084                return null;
4085            }
4086
4087            // the crc of the comment changed, this field is out of date.
4088            if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
4089                return null;
4090            }
4091
4092            return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
4093        }
4094        return null;
4095    }
4096};
4097module.exports = ZipEntry;
4098
4099},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
4100"use strict";
4101
4102var StreamHelper = require("./stream/StreamHelper");
4103var DataWorker = require("./stream/DataWorker");
4104var utf8 = require("./utf8");
4105var CompressedObject = require("./compressedObject");
4106var GenericWorker = require("./stream/GenericWorker");
4107
4108/**
4109 * A simple object representing a file in the zip file.
4110 * @constructor
4111 * @param {string} name the name of the file
4112 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
4113 * @param {Object} options the options of the file
4114 */
4115var ZipObject = function(name, data, options) {
4116    this.name = name;
4117    this.dir = options.dir;
4118    this.date = options.date;
4119    this.comment = options.comment;
4120    this.unixPermissions = options.unixPermissions;
4121    this.dosPermissions = options.dosPermissions;
4122
4123    this._data = data;
4124    this._dataBinary = options.binary;
4125    // keep only the compression
4126    this.options = {
4127        compression : options.compression,
4128        compressionOptions : options.compressionOptions
4129    };
4130};
4131
4132ZipObject.prototype = {
4133    /**
4134     * Create an internal stream for the content of this object.
4135     * @param {String} type the type of each chunk.
4136     * @return StreamHelper the stream.
4137     */
4138    internalStream: function (type) {
4139        var result = null, outputType = "string";
4140        try {
4141            if (!type) {
4142                throw new Error("No output type specified.");
4143            }
4144            outputType = type.toLowerCase();
4145            var askUnicodeString = outputType === "string" || outputType === "text";
4146            if (outputType === "binarystring" || outputType === "text") {
4147                outputType = "string";
4148            }
4149            result = this._decompressWorker();
4150
4151            var isUnicodeString = !this._dataBinary;
4152
4153            if (isUnicodeString && !askUnicodeString) {
4154                result = result.pipe(new utf8.Utf8EncodeWorker());
4155            }
4156            if (!isUnicodeString && askUnicodeString) {
4157                result = result.pipe(new utf8.Utf8DecodeWorker());
4158            }
4159        } catch (e) {
4160            result = new GenericWorker("error");
4161            result.error(e);
4162        }
4163
4164        return new StreamHelper(result, outputType, "");
4165    },
4166
4167    /**
4168     * Prepare the content in the asked type.
4169     * @param {String} type the type of the result.
4170     * @param {Function} onUpdate a function to call on each internal update.
4171     * @return Promise the promise of the result.
4172     */
4173    async: function (type, onUpdate) {
4174        return this.internalStream(type).accumulate(onUpdate);
4175    },
4176
4177    /**
4178     * Prepare the content as a nodejs stream.
4179     * @param {String} type the type of each chunk.
4180     * @param {Function} onUpdate a function to call on each internal update.
4181     * @return Stream the stream.
4182     */
4183    nodeStream: function (type, onUpdate) {
4184        return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
4185    },
4186
4187    /**
4188     * Return a worker for the compressed content.
4189     * @private
4190     * @param {Object} compression the compression object to use.
4191     * @param {Object} compressionOptions the options to use when compressing.
4192     * @return Worker the worker.
4193     */
4194    _compressWorker: function (compression, compressionOptions) {
4195        if (
4196            this._data instanceof CompressedObject &&
4197            this._data.compression.magic === compression.magic
4198        ) {
4199            return this._data.getCompressedWorker();
4200        } else {
4201            var result = this._decompressWorker();
4202            if(!this._dataBinary) {
4203                result = result.pipe(new utf8.Utf8EncodeWorker());
4204            }
4205            return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
4206        }
4207    },
4208    /**
4209     * Return a worker for the decompressed content.
4210     * @private
4211     * @return Worker the worker.
4212     */
4213    _decompressWorker : function () {
4214        if (this._data instanceof CompressedObject) {
4215            return this._data.getContentWorker();
4216        } else if (this._data instanceof GenericWorker) {
4217            return this._data;
4218        } else {
4219            return new DataWorker(this._data);
4220        }
4221    }
4222};
4223
4224var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
4225var removedFn = function () {
4226    throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
4227};
4228
4229for(var i = 0; i < removedMethods.length; i++) {
4230    ZipObject.prototype[removedMethods[i]] = removedFn;
4231}
4232module.exports = ZipObject;
4233
4234},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
4235(function (global){
4236'use strict';
4237var Mutation = global.MutationObserver || global.WebKitMutationObserver;
4238
4239var scheduleDrain;
4240
4241{
4242  if (Mutation) {
4243    var called = 0;
4244    var observer = new Mutation(nextTick);
4245    var element = global.document.createTextNode('');
4246    observer.observe(element, {
4247      characterData: true
4248    });
4249    scheduleDrain = function () {
4250      element.data = (called = ++called % 2);
4251    };
4252  } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
4253    var channel = new global.MessageChannel();
4254    channel.port1.onmessage = nextTick;
4255    scheduleDrain = function () {
4256      channel.port2.postMessage(0);
4257    };
4258  } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
4259    scheduleDrain = function () {
4260
4261      // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
4262      // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
4263      var scriptEl = global.document.createElement('script');
4264      scriptEl.onreadystatechange = function () {
4265        nextTick();
4266
4267        scriptEl.onreadystatechange = null;
4268        scriptEl.parentNode.removeChild(scriptEl);
4269        scriptEl = null;
4270      };
4271      global.document.documentElement.appendChild(scriptEl);
4272    };
4273  } else {
4274    scheduleDrain = function () {
4275      setTimeout(nextTick, 0);
4276    };
4277  }
4278}
4279
4280var draining;
4281var queue = [];
4282//named nextTick for less confusing stack traces
4283function nextTick() {
4284  draining = true;
4285  var i, oldQueue;
4286  var len = queue.length;
4287  while (len) {
4288    oldQueue = queue;
4289    queue = [];
4290    i = -1;
4291    while (++i < len) {
4292      oldQueue[i]();
4293    }
4294    len = queue.length;
4295  }
4296  draining = false;
4297}
4298
4299module.exports = immediate;
4300function immediate(task) {
4301  if (queue.push(task) === 1 && !draining) {
4302    scheduleDrain();
4303  }
4304}
4305
4306}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4307},{}],37:[function(require,module,exports){
4308'use strict';
4309var immediate = require('immediate');
4310
4311/* istanbul ignore next */
4312function INTERNAL() {}
4313
4314var handlers = {};
4315
4316var REJECTED = ['REJECTED'];
4317var FULFILLED = ['FULFILLED'];
4318var PENDING = ['PENDING'];
4319
4320module.exports = Promise;
4321
4322function Promise(resolver) {
4323  if (typeof resolver !== 'function') {
4324    throw new TypeError('resolver must be a function');
4325  }
4326  this.state = PENDING;
4327  this.queue = [];
4328  this.outcome = void 0;
4329  if (resolver !== INTERNAL) {
4330    safelyResolveThenable(this, resolver);
4331  }
4332}
4333
4334Promise.prototype["finally"] = function (callback) {
4335  if (typeof callback !== 'function') {
4336    return this;
4337  }
4338  var p = this.constructor;
4339  return this.then(resolve, reject);
4340
4341  function resolve(value) {
4342    function yes () {
4343      return value;
4344    }
4345    return p.resolve(callback()).then(yes);
4346  }
4347  function reject(reason) {
4348    function no () {
4349      throw reason;
4350    }
4351    return p.resolve(callback()).then(no);
4352  }
4353};
4354Promise.prototype["catch"] = function (onRejected) {
4355  return this.then(null, onRejected);
4356};
4357Promise.prototype.then = function (onFulfilled, onRejected) {
4358  if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
4359    typeof onRejected !== 'function' && this.state === REJECTED) {
4360    return this;
4361  }
4362  var promise = new this.constructor(INTERNAL);
4363  if (this.state !== PENDING) {
4364    var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
4365    unwrap(promise, resolver, this.outcome);
4366  } else {
4367    this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
4368  }
4369
4370  return promise;
4371};
4372function QueueItem(promise, onFulfilled, onRejected) {
4373  this.promise = promise;
4374  if (typeof onFulfilled === 'function') {
4375    this.onFulfilled = onFulfilled;
4376    this.callFulfilled = this.otherCallFulfilled;
4377  }
4378  if (typeof onRejected === 'function') {
4379    this.onRejected = onRejected;
4380    this.callRejected = this.otherCallRejected;
4381  }
4382}
4383QueueItem.prototype.callFulfilled = function (value) {
4384  handlers.resolve(this.promise, value);
4385};
4386QueueItem.prototype.otherCallFulfilled = function (value) {
4387  unwrap(this.promise, this.onFulfilled, value);
4388};
4389QueueItem.prototype.callRejected = function (value) {
4390  handlers.reject(this.promise, value);
4391};
4392QueueItem.prototype.otherCallRejected = function (value) {
4393  unwrap(this.promise, this.onRejected, value);
4394};
4395
4396function unwrap(promise, func, value) {
4397  immediate(function () {
4398    var returnValue;
4399    try {
4400      returnValue = func(value);
4401    } catch (e) {
4402      return handlers.reject(promise, e);
4403    }
4404    if (returnValue === promise) {
4405      handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
4406    } else {
4407      handlers.resolve(promise, returnValue);
4408    }
4409  });
4410}
4411
4412handlers.resolve = function (self, value) {
4413  var result = tryCatch(getThen, value);
4414  if (result.status === 'error') {
4415    return handlers.reject(self, result.value);
4416  }
4417  var thenable = result.value;
4418
4419  if (thenable) {
4420    safelyResolveThenable(self, thenable);
4421  } else {
4422    self.state = FULFILLED;
4423    self.outcome = value;
4424    var i = -1;
4425    var len = self.queue.length;
4426    while (++i < len) {
4427      self.queue[i].callFulfilled(value);
4428    }
4429  }
4430  return self;
4431};
4432handlers.reject = function (self, error) {
4433  self.state = REJECTED;
4434  self.outcome = error;
4435  var i = -1;
4436  var len = self.queue.length;
4437  while (++i < len) {
4438    self.queue[i].callRejected(error);
4439  }
4440  return self;
4441};
4442
4443function getThen(obj) {
4444  // Make sure we only access the accessor once as required by the spec
4445  var then = obj && obj.then;
4446  if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
4447    return function appyThen() {
4448      then.apply(obj, arguments);
4449    };
4450  }
4451}
4452
4453function safelyResolveThenable(self, thenable) {
4454  // Either fulfill, reject or reject with error
4455  var called = false;
4456  function onError(value) {
4457    if (called) {
4458      return;
4459    }
4460    called = true;
4461    handlers.reject(self, value);
4462  }
4463
4464  function onSuccess(value) {
4465    if (called) {
4466      return;
4467    }
4468    called = true;
4469    handlers.resolve(self, value);
4470  }
4471
4472  function tryToUnwrap() {
4473    thenable(onSuccess, onError);
4474  }
4475
4476  var result = tryCatch(tryToUnwrap);
4477  if (result.status === 'error') {
4478    onError(result.value);
4479  }
4480}
4481
4482function tryCatch(func, value) {
4483  var out = {};
4484  try {
4485    out.value = func(value);
4486    out.status = 'success';
4487  } catch (e) {
4488    out.status = 'error';
4489    out.value = e;
4490  }
4491  return out;
4492}
4493
4494Promise.resolve = resolve;
4495function resolve(value) {
4496  if (value instanceof this) {
4497    return value;
4498  }
4499  return handlers.resolve(new this(INTERNAL), value);
4500}
4501
4502Promise.reject = reject;
4503function reject(reason) {
4504  var promise = new this(INTERNAL);
4505  return handlers.reject(promise, reason);
4506}
4507
4508Promise.all = all;
4509function all(iterable) {
4510  var self = this;
4511  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
4512    return this.reject(new TypeError('must be an array'));
4513  }
4514
4515  var len = iterable.length;
4516  var called = false;
4517  if (!len) {
4518    return this.resolve([]);
4519  }
4520
4521  var values = new Array(len);
4522  var resolved = 0;
4523  var i = -1;
4524  var promise = new this(INTERNAL);
4525
4526  while (++i < len) {
4527    allResolver(iterable[i], i);
4528  }
4529  return promise;
4530  function allResolver(value, i) {
4531    self.resolve(value).then(resolveFromAll, function (error) {
4532      if (!called) {
4533        called = true;
4534        handlers.reject(promise, error);
4535      }
4536    });
4537    function resolveFromAll(outValue) {
4538      values[i] = outValue;
4539      if (++resolved === len && !called) {
4540        called = true;
4541        handlers.resolve(promise, values);
4542      }
4543    }
4544  }
4545}
4546
4547Promise.race = race;
4548function race(iterable) {
4549  var self = this;
4550  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
4551    return this.reject(new TypeError('must be an array'));
4552  }
4553
4554  var len = iterable.length;
4555  var called = false;
4556  if (!len) {
4557    return this.resolve([]);
4558  }
4559
4560  var i = -1;
4561  var promise = new this(INTERNAL);
4562
4563  while (++i < len) {
4564    resolver(iterable[i]);
4565  }
4566  return promise;
4567  function resolver(value) {
4568    self.resolve(value).then(function (response) {
4569      if (!called) {
4570        called = true;
4571        handlers.resolve(promise, response);
4572      }
4573    }, function (error) {
4574      if (!called) {
4575        called = true;
4576        handlers.reject(promise, error);
4577      }
4578    });
4579  }
4580}
4581
4582},{"immediate":36}],38:[function(require,module,exports){
4583// Top level file is just a mixin of submodules & constants
4584'use strict';
4585
4586var assign    = require('./lib/utils/common').assign;
4587
4588var deflate   = require('./lib/deflate');
4589var inflate   = require('./lib/inflate');
4590var constants = require('./lib/zlib/constants');
4591
4592var pako = {};
4593
4594assign(pako, deflate, inflate, constants);
4595
4596module.exports = pako;
4597
4598},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(require,module,exports){
4599'use strict';
4600
4601
4602var zlib_deflate = require('./zlib/deflate');
4603var utils        = require('./utils/common');
4604var strings      = require('./utils/strings');
4605var msg          = require('./zlib/messages');
4606var ZStream      = require('./zlib/zstream');
4607
4608var toString = Object.prototype.toString;
4609
4610/* Public constants ==========================================================*/
4611/* ===========================================================================*/
4612
4613var Z_NO_FLUSH      = 0;
4614var Z_FINISH        = 4;
4615
4616var Z_OK            = 0;
4617var Z_STREAM_END    = 1;
4618var Z_SYNC_FLUSH    = 2;
4619
4620var Z_DEFAULT_COMPRESSION = -1;
4621
4622var Z_DEFAULT_STRATEGY    = 0;
4623
4624var Z_DEFLATED  = 8;
4625
4626/* ===========================================================================*/
4627
4628
4629/**
4630 * class Deflate
4631 *
4632 * Generic JS-style wrapper for zlib calls. If you don't need
4633 * streaming behaviour - use more simple functions: [[deflate]],
4634 * [[deflateRaw]] and [[gzip]].
4635 **/
4636
4637/* internal
4638 * Deflate.chunks -> Array
4639 *
4640 * Chunks of output data, if [[Deflate#onData]] not overriden.
4641 **/
4642
4643/**
4644 * Deflate.result -> Uint8Array|Array
4645 *
4646 * Compressed result, generated by default [[Deflate#onData]]
4647 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
4648 * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
4649 * push a chunk with explicit flush (call [[Deflate#push]] with
4650 * `Z_SYNC_FLUSH` param).
4651 **/
4652
4653/**
4654 * Deflate.err -> Number
4655 *
4656 * Error code after deflate finished. 0 (Z_OK) on success.
4657 * You will not need it in real life, because deflate errors
4658 * are possible only on wrong options or bad `onData` / `onEnd`
4659 * custom handlers.
4660 **/
4661
4662/**
4663 * Deflate.msg -> String
4664 *
4665 * Error message, if [[Deflate.err]] != 0
4666 **/
4667
4668
4669/**
4670 * new Deflate(options)
4671 * - options (Object): zlib deflate options.
4672 *
4673 * Creates new deflator instance with specified params. Throws exception
4674 * on bad params. Supported options:
4675 *
4676 * - `level`
4677 * - `windowBits`
4678 * - `memLevel`
4679 * - `strategy`
4680 * - `dictionary`
4681 *
4682 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
4683 * for more information on these.
4684 *
4685 * Additional options, for internal needs:
4686 *
4687 * - `chunkSize` - size of generated data chunks (16K by default)
4688 * - `raw` (Boolean) - do raw deflate
4689 * - `gzip` (Boolean) - create gzip wrapper
4690 * - `to` (String) - if equal to 'string', then result will be "binary string"
4691 *    (each char code [0..255])
4692 * - `header` (Object) - custom header for gzip
4693 *   - `text` (Boolean) - true if compressed data believed to be text
4694 *   - `time` (Number) - modification time, unix timestamp
4695 *   - `os` (Number) - operation system code
4696 *   - `extra` (Array) - array of bytes with extra data (max 65536)
4697 *   - `name` (String) - file name (binary string)
4698 *   - `comment` (String) - comment (binary string)
4699 *   - `hcrc` (Boolean) - true if header crc should be added
4700 *
4701 * ##### Example:
4702 *
4703 * ```javascript
4704 * var pako = require('pako')
4705 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
4706 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
4707 *
4708 * var deflate = new pako.Deflate({ level: 3});
4709 *
4710 * deflate.push(chunk1, false);
4711 * deflate.push(chunk2, true);  // true -> last chunk
4712 *
4713 * if (deflate.err) { throw new Error(deflate.err); }
4714 *
4715 * console.log(deflate.result);
4716 * ```
4717 **/
4718function Deflate(options) {
4719  if (!(this instanceof Deflate)) return new Deflate(options);
4720
4721  this.options = utils.assign({
4722    level: Z_DEFAULT_COMPRESSION,
4723    method: Z_DEFLATED,
4724    chunkSize: 16384,
4725    windowBits: 15,
4726    memLevel: 8,
4727    strategy: Z_DEFAULT_STRATEGY,
4728    to: ''
4729  }, options || {});
4730
4731  var opt = this.options;
4732
4733  if (opt.raw && (opt.windowBits > 0)) {
4734    opt.windowBits = -opt.windowBits;
4735  }
4736
4737  else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
4738    opt.windowBits += 16;
4739  }
4740
4741  this.err    = 0;      // error code, if happens (0 = Z_OK)
4742  this.msg    = '';     // error message
4743  this.ended  = false;  // used to avoid multiple onEnd() calls
4744  this.chunks = [];     // chunks of compressed data
4745
4746  this.strm = new ZStream();
4747  this.strm.avail_out = 0;
4748
4749  var status = zlib_deflate.deflateInit2(
4750    this.strm,
4751    opt.level,
4752    opt.method,
4753    opt.windowBits,
4754    opt.memLevel,
4755    opt.strategy
4756  );
4757
4758  if (status !== Z_OK) {
4759    throw new Error(msg[status]);
4760  }
4761
4762  if (opt.header) {
4763    zlib_deflate.deflateSetHeader(this.strm, opt.header);
4764  }
4765
4766  if (opt.dictionary) {
4767    var dict;
4768    // Convert data if needed
4769    if (typeof opt.dictionary === 'string') {
4770      // If we need to compress text, change encoding to utf8.
4771      dict = strings.string2buf(opt.dictionary);
4772    } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
4773      dict = new Uint8Array(opt.dictionary);
4774    } else {
4775      dict = opt.dictionary;
4776    }
4777
4778    status = zlib_deflate.deflateSetDictionary(this.strm, dict);
4779
4780    if (status !== Z_OK) {
4781      throw new Error(msg[status]);
4782    }
4783
4784    this._dict_set = true;
4785  }
4786}
4787
4788/**
4789 * Deflate#push(data[, mode]) -> Boolean
4790 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
4791 *   converted to utf8 byte sequence.
4792 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
4793 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
4794 *
4795 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
4796 * new compressed chunks. Returns `true` on success. The last data block must have
4797 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
4798 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
4799 * can use mode Z_SYNC_FLUSH, keeping the compression context.
4800 *
4801 * On fail call [[Deflate#onEnd]] with error code and return false.
4802 *
4803 * We strongly recommend to use `Uint8Array` on input for best speed (output
4804 * array format is detected automatically). Also, don't skip last param and always
4805 * use the same type in your code (boolean or number). That will improve JS speed.
4806 *
4807 * For regular `Array`-s make sure all elements are [0..255].
4808 *
4809 * ##### Example
4810 *
4811 * ```javascript
4812 * push(chunk, false); // push one of data chunks
4813 * ...
4814 * push(chunk, true);  // push last chunk
4815 * ```
4816 **/
4817Deflate.prototype.push = function (data, mode) {
4818  var strm = this.strm;
4819  var chunkSize = this.options.chunkSize;
4820  var status, _mode;
4821
4822  if (this.ended) { return false; }
4823
4824  _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
4825
4826  // Convert data if needed
4827  if (typeof data === 'string') {
4828    // If we need to compress text, change encoding to utf8.
4829    strm.input = strings.string2buf(data);
4830  } else if (toString.call(data) === '[object ArrayBuffer]') {
4831    strm.input = new Uint8Array(data);
4832  } else {
4833    strm.input = data;
4834  }
4835
4836  strm.next_in = 0;
4837  strm.avail_in = strm.input.length;
4838
4839  do {
4840    if (strm.avail_out === 0) {
4841      strm.output = new utils.Buf8(chunkSize);
4842      strm.next_out = 0;
4843      strm.avail_out = chunkSize;
4844    }
4845    status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */
4846
4847    if (status !== Z_STREAM_END && status !== Z_OK) {
4848      this.onEnd(status);
4849      this.ended = true;
4850      return false;
4851    }
4852    if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
4853      if (this.options.to === 'string') {
4854        this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
4855      } else {
4856        this.onData(utils.shrinkBuf(strm.output, strm.next_out));
4857      }
4858    }
4859  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
4860
4861  // Finalize on the last chunk.
4862  if (_mode === Z_FINISH) {
4863    status = zlib_deflate.deflateEnd(this.strm);
4864    this.onEnd(status);
4865    this.ended = true;
4866    return status === Z_OK;
4867  }
4868
4869  // callback interim results if Z_SYNC_FLUSH.
4870  if (_mode === Z_SYNC_FLUSH) {
4871    this.onEnd(Z_OK);
4872    strm.avail_out = 0;
4873    return true;
4874  }
4875
4876  return true;
4877};
4878
4879
4880/**
4881 * Deflate#onData(chunk) -> Void
4882 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
4883 *   on js engine support. When string output requested, each chunk
4884 *   will be string.
4885 *
4886 * By default, stores data blocks in `chunks[]` property and glue
4887 * those in `onEnd`. Override this handler, if you need another behaviour.
4888 **/
4889Deflate.prototype.onData = function (chunk) {
4890  this.chunks.push(chunk);
4891};
4892
4893
4894/**
4895 * Deflate#onEnd(status) -> Void
4896 * - status (Number): deflate status. 0 (Z_OK) on success,
4897 *   other if not.
4898 *
4899 * Called once after you tell deflate that the input stream is
4900 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
4901 * or if an error happened. By default - join collected chunks,
4902 * free memory and fill `results` / `err` properties.
4903 **/
4904Deflate.prototype.onEnd = function (status) {
4905  // On success - join
4906  if (status === Z_OK) {
4907    if (this.options.to === 'string') {
4908      this.result = this.chunks.join('');
4909    } else {
4910      this.result = utils.flattenChunks(this.chunks);
4911    }
4912  }
4913  this.chunks = [];
4914  this.err = status;
4915  this.msg = this.strm.msg;
4916};
4917
4918
4919/**
4920 * deflate(data[, options]) -> Uint8Array|Array|String
4921 * - data (Uint8Array|Array|String): input data to compress.
4922 * - options (Object): zlib deflate options.
4923 *
4924 * Compress `data` with deflate algorithm and `options`.
4925 *
4926 * Supported options are:
4927 *
4928 * - level
4929 * - windowBits
4930 * - memLevel
4931 * - strategy
4932 * - dictionary
4933 *
4934 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
4935 * for more information on these.
4936 *
4937 * Sugar (options):
4938 *
4939 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
4940 *   negative windowBits implicitly.
4941 * - `to` (String) - if equal to 'string', then result will be "binary string"
4942 *    (each char code [0..255])
4943 *
4944 * ##### Example:
4945 *
4946 * ```javascript
4947 * var pako = require('pako')
4948 *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
4949 *
4950 * console.log(pako.deflate(data));
4951 * ```
4952 **/
4953function deflate(input, options) {
4954  var deflator = new Deflate(options);
4955
4956  deflator.push(input, true);
4957
4958  // That will never happens, if you don't cheat with options :)
4959  if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
4960
4961  return deflator.result;
4962}
4963
4964
4965/**
4966 * deflateRaw(data[, options]) -> Uint8Array|Array|String
4967 * - data (Uint8Array|Array|String): input data to compress.
4968 * - options (Object): zlib deflate options.
4969 *
4970 * The same as [[deflate]], but creates raw data, without wrapper
4971 * (header and adler32 crc).
4972 **/
4973function deflateRaw(input, options) {
4974  options = options || {};
4975  options.raw = true;
4976  return deflate(input, options);
4977}
4978
4979
4980/**
4981 * gzip(data[, options]) -> Uint8Array|Array|String
4982 * - data (Uint8Array|Array|String): input data to compress.
4983 * - options (Object): zlib deflate options.
4984 *
4985 * The same as [[deflate]], but create gzip wrapper instead of
4986 * deflate one.
4987 **/
4988function gzip(input, options) {
4989  options = options || {};
4990  options.gzip = true;
4991  return deflate(input, options);
4992}
4993
4994
4995exports.Deflate = Deflate;
4996exports.deflate = deflate;
4997exports.deflateRaw = deflateRaw;
4998exports.gzip = gzip;
4999
5000},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(require,module,exports){
5001'use strict';
5002
5003
5004var zlib_inflate = require('./zlib/inflate');
5005var utils        = require('./utils/common');
5006var strings      = require('./utils/strings');
5007var c            = require('./zlib/constants');
5008var msg          = require('./zlib/messages');
5009var ZStream      = require('./zlib/zstream');
5010var GZheader     = require('./zlib/gzheader');
5011
5012var toString = Object.prototype.toString;
5013
5014/**
5015 * class Inflate
5016 *
5017 * Generic JS-style wrapper for zlib calls. If you don't need
5018 * streaming behaviour - use more simple functions: [[inflate]]
5019 * and [[inflateRaw]].
5020 **/
5021
5022/* internal
5023 * inflate.chunks -> Array
5024 *
5025 * Chunks of output data, if [[Inflate#onData]] not overriden.
5026 **/
5027
5028/**
5029 * Inflate.result -> Uint8Array|Array|String
5030 *
5031 * Uncompressed result, generated by default [[Inflate#onData]]
5032 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
5033 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
5034 * push a chunk with explicit flush (call [[Inflate#push]] with
5035 * `Z_SYNC_FLUSH` param).
5036 **/
5037
5038/**
5039 * Inflate.err -> Number
5040 *
5041 * Error code after inflate finished. 0 (Z_OK) on success.
5042 * Should be checked if broken data possible.
5043 **/
5044
5045/**
5046 * Inflate.msg -> String
5047 *
5048 * Error message, if [[Inflate.err]] != 0
5049 **/
5050
5051
5052/**
5053 * new Inflate(options)
5054 * - options (Object): zlib inflate options.
5055 *
5056 * Creates new inflator instance with specified params. Throws exception
5057 * on bad params. Supported options:
5058 *
5059 * - `windowBits`
5060 * - `dictionary`
5061 *
5062 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
5063 * for more information on these.
5064 *
5065 * Additional options, for internal needs:
5066 *
5067 * - `chunkSize` - size of generated data chunks (16K by default)
5068 * - `raw` (Boolean) - do raw inflate
5069 * - `to` (String) - if equal to 'string', then result will be converted
5070 *   from utf8 to utf16 (javascript) string. When string output requested,
5071 *   chunk length can differ from `chunkSize`, depending on content.
5072 *
5073 * By default, when no options set, autodetect deflate/gzip data format via
5074 * wrapper header.
5075 *
5076 * ##### Example:
5077 *
5078 * ```javascript
5079 * var pako = require('pako')
5080 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
5081 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
5082 *
5083 * var inflate = new pako.Inflate({ level: 3});
5084 *
5085 * inflate.push(chunk1, false);
5086 * inflate.push(chunk2, true);  // true -> last chunk
5087 *
5088 * if (inflate.err) { throw new Error(inflate.err); }
5089 *
5090 * console.log(inflate.result);
5091 * ```
5092 **/
5093function Inflate(options) {
5094  if (!(this instanceof Inflate)) return new Inflate(options);
5095
5096  this.options = utils.assign({
5097    chunkSize: 16384,
5098    windowBits: 0,
5099    to: ''
5100  }, options || {});
5101
5102  var opt = this.options;
5103
5104  // Force window size for `raw` data, if not set directly,
5105  // because we have no header for autodetect.
5106  if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
5107    opt.windowBits = -opt.windowBits;
5108    if (opt.windowBits === 0) { opt.windowBits = -15; }
5109  }
5110
5111  // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
5112  if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
5113      !(options && options.windowBits)) {
5114    opt.windowBits += 32;
5115  }
5116
5117  // Gzip header has no info about windows size, we can do autodetect only
5118  // for deflate. So, if window size not set, force it to max when gzip possible
5119  if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
5120    // bit 3 (16) -> gzipped data
5121    // bit 4 (32) -> autodetect gzip/deflate
5122    if ((opt.windowBits & 15) === 0) {
5123      opt.windowBits |= 15;
5124    }
5125  }
5126
5127  this.err    = 0;      // error code, if happens (0 = Z_OK)
5128  this.msg    = '';     // error message
5129  this.ended  = false;  // used to avoid multiple onEnd() calls
5130  this.chunks = [];     // chunks of compressed data
5131
5132  this.strm   = new ZStream();
5133  this.strm.avail_out = 0;
5134
5135  var status  = zlib_inflate.inflateInit2(
5136    this.strm,
5137    opt.windowBits
5138  );
5139
5140  if (status !== c.Z_OK) {
5141    throw new Error(msg[status]);
5142  }
5143
5144  this.header = new GZheader();
5145
5146  zlib_inflate.inflateGetHeader(this.strm, this.header);
5147}
5148
5149/**
5150 * Inflate#push(data[, mode]) -> Boolean
5151 * - data (Uint8Array|Array|ArrayBuffer|String): input data
5152 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
5153 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
5154 *
5155 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
5156 * new output chunks. Returns `true` on success. The last data block must have
5157 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
5158 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
5159 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
5160 *
5161 * On fail call [[Inflate#onEnd]] with error code and return false.
5162 *
5163 * We strongly recommend to use `Uint8Array` on input for best speed (output
5164 * format is detected automatically). Also, don't skip last param and always
5165 * use the same type in your code (boolean or number). That will improve JS speed.
5166 *
5167 * For regular `Array`-s make sure all elements are [0..255].
5168 *
5169 * ##### Example
5170 *
5171 * ```javascript
5172 * push(chunk, false); // push one of data chunks
5173 * ...
5174 * push(chunk, true);  // push last chunk
5175 * ```
5176 **/
5177Inflate.prototype.push = function (data, mode) {
5178  var strm = this.strm;
5179  var chunkSize = this.options.chunkSize;
5180  var dictionary = this.options.dictionary;
5181  var status, _mode;
5182  var next_out_utf8, tail, utf8str;
5183  var dict;
5184
5185  // Flag to properly process Z_BUF_ERROR on testing inflate call
5186  // when we check that all output data was flushed.
5187  var allowBufError = false;
5188
5189  if (this.ended) { return false; }
5190  _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
5191
5192  // Convert data if needed
5193  if (typeof data === 'string') {
5194    // Only binary strings can be decompressed on practice
5195    strm.input = strings.binstring2buf(data);
5196  } else if (toString.call(data) === '[object ArrayBuffer]') {
5197    strm.input = new Uint8Array(data);
5198  } else {
5199    strm.input = data;
5200  }
5201
5202  strm.next_in = 0;
5203  strm.avail_in = strm.input.length;
5204
5205  do {
5206    if (strm.avail_out === 0) {
5207      strm.output = new utils.Buf8(chunkSize);
5208      strm.next_out = 0;
5209      strm.avail_out = chunkSize;
5210    }
5211
5212    status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */
5213
5214    if (status === c.Z_NEED_DICT && dictionary) {
5215      // Convert data if needed
5216      if (typeof dictionary === 'string') {
5217        dict = strings.string2buf(dictionary);
5218      } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
5219        dict = new Uint8Array(dictionary);
5220      } else {
5221        dict = dictionary;
5222      }
5223
5224      status = zlib_inflate.inflateSetDictionary(this.strm, dict);
5225
5226    }
5227
5228    if (status === c.Z_BUF_ERROR && allowBufError === true) {
5229      status = c.Z_OK;
5230      allowBufError = false;
5231    }
5232
5233    if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
5234      this.onEnd(status);
5235      this.ended = true;
5236      return false;
5237    }
5238
5239    if (strm.next_out) {
5240      if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
5241
5242        if (this.options.to === 'string') {
5243
5244          next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
5245
5246          tail = strm.next_out - next_out_utf8;
5247          utf8str = strings.buf2string(strm.output, next_out_utf8);
5248
5249          // move tail
5250          strm.next_out = tail;
5251          strm.avail_out = chunkSize - tail;
5252          if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
5253
5254          this.onData(utf8str);
5255
5256        } else {
5257          this.onData(utils.shrinkBuf(strm.output, strm.next_out));
5258        }
5259      }
5260    }
5261
5262    // When no more input data, we should check that internal inflate buffers
5263    // are flushed. The only way to do it when avail_out = 0 - run one more
5264    // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
5265    // Here we set flag to process this error properly.
5266    //
5267    // NOTE. Deflate does not return error in this case and does not needs such
5268    // logic.
5269    if (strm.avail_in === 0 && strm.avail_out === 0) {
5270      allowBufError = true;
5271    }
5272
5273  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
5274
5275  if (status === c.Z_STREAM_END) {
5276    _mode = c.Z_FINISH;
5277  }
5278
5279  // Finalize on the last chunk.
5280  if (_mode === c.Z_FINISH) {
5281    status = zlib_inflate.inflateEnd(this.strm);
5282    this.onEnd(status);
5283    this.ended = true;
5284    return status === c.Z_OK;
5285  }
5286
5287  // callback interim results if Z_SYNC_FLUSH.
5288  if (_mode === c.Z_SYNC_FLUSH) {
5289    this.onEnd(c.Z_OK);
5290    strm.avail_out = 0;
5291    return true;
5292  }
5293
5294  return true;
5295};
5296
5297
5298/**
5299 * Inflate#onData(chunk) -> Void
5300 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
5301 *   on js engine support. When string output requested, each chunk
5302 *   will be string.
5303 *
5304 * By default, stores data blocks in `chunks[]` property and glue
5305 * those in `onEnd`. Override this handler, if you need another behaviour.
5306 **/
5307Inflate.prototype.onData = function (chunk) {
5308  this.chunks.push(chunk);
5309};
5310
5311
5312/**
5313 * Inflate#onEnd(status) -> Void
5314 * - status (Number): inflate status. 0 (Z_OK) on success,
5315 *   other if not.
5316 *
5317 * Called either after you tell inflate that the input stream is
5318 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
5319 * or if an error happened. By default - join collected chunks,
5320 * free memory and fill `results` / `err` properties.
5321 **/
5322Inflate.prototype.onEnd = function (status) {
5323  // On success - join
5324  if (status === c.Z_OK) {
5325    if (this.options.to === 'string') {
5326      // Glue & convert here, until we teach pako to send
5327      // utf8 alligned strings to onData
5328      this.result = this.chunks.join('');
5329    } else {
5330      this.result = utils.flattenChunks(this.chunks);
5331    }
5332  }
5333  this.chunks = [];
5334  this.err = status;
5335  this.msg = this.strm.msg;
5336};
5337
5338
5339/**
5340 * inflate(data[, options]) -> Uint8Array|Array|String
5341 * - data (Uint8Array|Array|String): input data to decompress.
5342 * - options (Object): zlib inflate options.
5343 *
5344 * Decompress `data` with inflate/ungzip and `options`. Autodetect
5345 * format via wrapper header by default. That's why we don't provide
5346 * separate `ungzip` method.
5347 *
5348 * Supported options are:
5349 *
5350 * - windowBits
5351 *
5352 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
5353 * for more information.
5354 *
5355 * Sugar (options):
5356 *
5357 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
5358 *   negative windowBits implicitly.
5359 * - `to` (String) - if equal to 'string', then result will be converted
5360 *   from utf8 to utf16 (javascript) string. When string output requested,
5361 *   chunk length can differ from `chunkSize`, depending on content.
5362 *
5363 *
5364 * ##### Example:
5365 *
5366 * ```javascript
5367 * var pako = require('pako')
5368 *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
5369 *   , output;
5370 *
5371 * try {
5372 *   output = pako.inflate(input);
5373 * } catch (err)
5374 *   console.log(err);
5375 * }
5376 * ```
5377 **/
5378function inflate(input, options) {
5379  var inflator = new Inflate(options);
5380
5381  inflator.push(input, true);
5382
5383  // That will never happens, if you don't cheat with options :)
5384  if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
5385
5386  return inflator.result;
5387}
5388
5389
5390/**
5391 * inflateRaw(data[, options]) -> Uint8Array|Array|String
5392 * - data (Uint8Array|Array|String): input data to decompress.
5393 * - options (Object): zlib inflate options.
5394 *
5395 * The same as [[inflate]], but creates raw data, without wrapper
5396 * (header and adler32 crc).
5397 **/
5398function inflateRaw(input, options) {
5399  options = options || {};
5400  options.raw = true;
5401  return inflate(input, options);
5402}
5403
5404
5405/**
5406 * ungzip(data[, options]) -> Uint8Array|Array|String
5407 * - data (Uint8Array|Array|String): input data to decompress.
5408 * - options (Object): zlib inflate options.
5409 *
5410 * Just shortcut to [[inflate]], because it autodetects format
5411 * by header.content. Done for convenience.
5412 **/
5413
5414
5415exports.Inflate = Inflate;
5416exports.inflate = inflate;
5417exports.inflateRaw = inflateRaw;
5418exports.ungzip  = inflate;
5419
5420},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(require,module,exports){
5421'use strict';
5422
5423
5424var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
5425                (typeof Uint16Array !== 'undefined') &&
5426                (typeof Int32Array !== 'undefined');
5427
5428
5429exports.assign = function (obj /*from1, from2, from3, ...*/) {
5430  var sources = Array.prototype.slice.call(arguments, 1);
5431  while (sources.length) {
5432    var source = sources.shift();
5433    if (!source) { continue; }
5434
5435    if (typeof source !== 'object') {
5436      throw new TypeError(source + 'must be non-object');
5437    }
5438
5439    for (var p in source) {
5440      if (source.hasOwnProperty(p)) {
5441        obj[p] = source[p];
5442      }
5443    }
5444  }
5445
5446  return obj;
5447};
5448
5449
5450// reduce buffer size, avoiding mem copy
5451exports.shrinkBuf = function (buf, size) {
5452  if (buf.length === size) { return buf; }
5453  if (buf.subarray) { return buf.subarray(0, size); }
5454  buf.length = size;
5455  return buf;
5456};
5457
5458
5459var fnTyped = {
5460  arraySet: function (dest, src, src_offs, len, dest_offs) {
5461    if (src.subarray && dest.subarray) {
5462      dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
5463      return;
5464    }
5465    // Fallback to ordinary array
5466    for (var i = 0; i < len; i++) {
5467      dest[dest_offs + i] = src[src_offs + i];
5468    }
5469  },
5470  // Join array of chunks to single array.
5471  flattenChunks: function (chunks) {
5472    var i, l, len, pos, chunk, result;
5473
5474    // calculate data length
5475    len = 0;
5476    for (i = 0, l = chunks.length; i < l; i++) {
5477      len += chunks[i].length;
5478    }
5479
5480    // join chunks
5481    result = new Uint8Array(len);
5482    pos = 0;
5483    for (i = 0, l = chunks.length; i < l; i++) {
5484      chunk = chunks[i];
5485      result.set(chunk, pos);
5486      pos += chunk.length;
5487    }
5488
5489    return result;
5490  }
5491};
5492
5493var fnUntyped = {
5494  arraySet: function (dest, src, src_offs, len, dest_offs) {
5495    for (var i = 0; i < len; i++) {
5496      dest[dest_offs + i] = src[src_offs + i];
5497    }
5498  },
5499  // Join array of chunks to single array.
5500  flattenChunks: function (chunks) {
5501    return [].concat.apply([], chunks);
5502  }
5503};
5504
5505
5506// Enable/Disable typed arrays use, for testing
5507//
5508exports.setTyped = function (on) {
5509  if (on) {
5510    exports.Buf8  = Uint8Array;
5511    exports.Buf16 = Uint16Array;
5512    exports.Buf32 = Int32Array;
5513    exports.assign(exports, fnTyped);
5514  } else {
5515    exports.Buf8  = Array;
5516    exports.Buf16 = Array;
5517    exports.Buf32 = Array;
5518    exports.assign(exports, fnUntyped);
5519  }
5520};
5521
5522exports.setTyped(TYPED_OK);
5523
5524},{}],42:[function(require,module,exports){
5525// String encode/decode helpers
5526'use strict';
5527
5528
5529var utils = require('./common');
5530
5531
5532// Quick check if we can use fast array to bin string conversion
5533//
5534// - apply(Array) can fail on Android 2.2
5535// - apply(Uint8Array) can fail on iOS 5.1 Safary
5536//
5537var STR_APPLY_OK = true;
5538var STR_APPLY_UIA_OK = true;
5539
5540try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
5541try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
5542
5543
5544// Table with utf8 lengths (calculated by first byte of sequence)
5545// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
5546// because max possible codepoint is 0x10ffff
5547var _utf8len = new utils.Buf8(256);
5548for (var q = 0; q < 256; q++) {
5549  _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
5550}
5551_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
5552
5553
5554// convert string to array (typed, when possible)
5555exports.string2buf = function (str) {
5556  var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
5557
5558  // count binary size
5559  for (m_pos = 0; m_pos < str_len; m_pos++) {
5560    c = str.charCodeAt(m_pos);
5561    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
5562      c2 = str.charCodeAt(m_pos + 1);
5563      if ((c2 & 0xfc00) === 0xdc00) {
5564        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
5565        m_pos++;
5566      }
5567    }
5568    buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
5569  }
5570
5571  // allocate buffer
5572  buf = new utils.Buf8(buf_len);
5573
5574  // convert
5575  for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
5576    c = str.charCodeAt(m_pos);
5577    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
5578      c2 = str.charCodeAt(m_pos + 1);
5579      if ((c2 & 0xfc00) === 0xdc00) {
5580        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
5581        m_pos++;
5582      }
5583    }
5584    if (c < 0x80) {
5585      /* one byte */
5586      buf[i++] = c;
5587    } else if (c < 0x800) {
5588      /* two bytes */
5589      buf[i++] = 0xC0 | (c >>> 6);
5590      buf[i++] = 0x80 | (c & 0x3f);
5591    } else if (c < 0x10000) {
5592      /* three bytes */
5593      buf[i++] = 0xE0 | (c >>> 12);
5594      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
5595      buf[i++] = 0x80 | (c & 0x3f);
5596    } else {
5597      /* four bytes */
5598      buf[i++] = 0xf0 | (c >>> 18);
5599      buf[i++] = 0x80 | (c >>> 12 & 0x3f);
5600      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
5601      buf[i++] = 0x80 | (c & 0x3f);
5602    }
5603  }
5604
5605  return buf;
5606};
5607
5608// Helper (used in 2 places)
5609function buf2binstring(buf, len) {
5610  // use fallback for big arrays to avoid stack overflow
5611  if (len < 65537) {
5612    if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
5613      return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
5614    }
5615  }
5616
5617  var result = '';
5618  for (var i = 0; i < len; i++) {
5619    result += String.fromCharCode(buf[i]);
5620  }
5621  return result;
5622}
5623
5624
5625// Convert byte array to binary string
5626exports.buf2binstring = function (buf) {
5627  return buf2binstring(buf, buf.length);
5628};
5629
5630
5631// Convert binary string (typed, when possible)
5632exports.binstring2buf = function (str) {
5633  var buf = new utils.Buf8(str.length);
5634  for (var i = 0, len = buf.length; i < len; i++) {
5635    buf[i] = str.charCodeAt(i);
5636  }
5637  return buf;
5638};
5639
5640
5641// convert array to string
5642exports.buf2string = function (buf, max) {
5643  var i, out, c, c_len;
5644  var len = max || buf.length;
5645
5646  // Reserve max possible length (2 words per char)
5647  // NB: by unknown reasons, Array is significantly faster for
5648  //     String.fromCharCode.apply than Uint16Array.
5649  var utf16buf = new Array(len * 2);
5650
5651  for (out = 0, i = 0; i < len;) {
5652    c = buf[i++];
5653    // quick process ascii
5654    if (c < 0x80) { utf16buf[out++] = c; continue; }
5655
5656    c_len = _utf8len[c];
5657    // skip 5 & 6 byte codes
5658    if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
5659
5660    // apply mask on first byte
5661    c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
5662    // join the rest
5663    while (c_len > 1 && i < len) {
5664      c = (c << 6) | (buf[i++] & 0x3f);
5665      c_len--;
5666    }
5667
5668    // terminated by end of string?
5669    if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
5670
5671    if (c < 0x10000) {
5672      utf16buf[out++] = c;
5673    } else {
5674      c -= 0x10000;
5675      utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
5676      utf16buf[out++] = 0xdc00 | (c & 0x3ff);
5677    }
5678  }
5679
5680  return buf2binstring(utf16buf, out);
5681};
5682
5683
5684// Calculate max possible position in utf8 buffer,
5685// that will not break sequence. If that's not possible
5686// - (very small limits) return max size as is.
5687//
5688// buf[] - utf8 bytes array
5689// max   - length limit (mandatory);
5690exports.utf8border = function (buf, max) {
5691  var pos;
5692
5693  max = max || buf.length;
5694  if (max > buf.length) { max = buf.length; }
5695
5696  // go back from last position, until start of sequence found
5697  pos = max - 1;
5698  while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
5699
5700  // Fuckup - very small and broken sequence,
5701  // return max, because we should return something anyway.
5702  if (pos < 0) { return max; }
5703
5704  // If we came to start of buffer - that means vuffer is too small,
5705  // return max too.
5706  if (pos === 0) { return max; }
5707
5708  return (pos + _utf8len[buf[pos]] > max) ? pos : max;
5709};
5710
5711},{"./common":41}],43:[function(require,module,exports){
5712'use strict';
5713
5714// Note: adler32 takes 12% for level 0 and 2% for level 6.
5715// It doesn't worth to make additional optimizationa as in original.
5716// Small size is preferable.
5717
5718// (C) 1995-2013 Jean-loup Gailly and Mark Adler
5719// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5720//
5721// This software is provided 'as-is', without any express or implied
5722// warranty. In no event will the authors be held liable for any damages
5723// arising from the use of this software.
5724//
5725// Permission is granted to anyone to use this software for any purpose,
5726// including commercial applications, and to alter it and redistribute it
5727// freely, subject to the following restrictions:
5728//
5729// 1. The origin of this software must not be misrepresented; you must not
5730//   claim that you wrote the original software. If you use this software
5731//   in a product, an acknowledgment in the product documentation would be
5732//   appreciated but is not required.
5733// 2. Altered source versions must be plainly marked as such, and must not be
5734//   misrepresented as being the original software.
5735// 3. This notice may not be removed or altered from any source distribution.
5736
5737function adler32(adler, buf, len, pos) {
5738  var s1 = (adler & 0xffff) |0,
5739      s2 = ((adler >>> 16) & 0xffff) |0,
5740      n = 0;
5741
5742  while (len !== 0) {
5743    // Set limit ~ twice less than 5552, to keep
5744    // s2 in 31-bits, because we force signed ints.
5745    // in other case %= will fail.
5746    n = len > 2000 ? 2000 : len;
5747    len -= n;
5748
5749    do {
5750      s1 = (s1 + buf[pos++]) |0;
5751      s2 = (s2 + s1) |0;
5752    } while (--n);
5753
5754    s1 %= 65521;
5755    s2 %= 65521;
5756  }
5757
5758  return (s1 | (s2 << 16)) |0;
5759}
5760
5761
5762module.exports = adler32;
5763
5764},{}],44:[function(require,module,exports){
5765'use strict';
5766
5767// (C) 1995-2013 Jean-loup Gailly and Mark Adler
5768// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5769//
5770// This software is provided 'as-is', without any express or implied
5771// warranty. In no event will the authors be held liable for any damages
5772// arising from the use of this software.
5773//
5774// Permission is granted to anyone to use this software for any purpose,
5775// including commercial applications, and to alter it and redistribute it
5776// freely, subject to the following restrictions:
5777//
5778// 1. The origin of this software must not be misrepresented; you must not
5779//   claim that you wrote the original software. If you use this software
5780//   in a product, an acknowledgment in the product documentation would be
5781//   appreciated but is not required.
5782// 2. Altered source versions must be plainly marked as such, and must not be
5783//   misrepresented as being the original software.
5784// 3. This notice may not be removed or altered from any source distribution.
5785
5786module.exports = {
5787
5788  /* Allowed flush values; see deflate() and inflate() below for details */
5789  Z_NO_FLUSH:         0,
5790  Z_PARTIAL_FLUSH:    1,
5791  Z_SYNC_FLUSH:       2,
5792  Z_FULL_FLUSH:       3,
5793  Z_FINISH:           4,
5794  Z_BLOCK:            5,
5795  Z_TREES:            6,
5796
5797  /* Return codes for the compression/decompression functions. Negative values
5798  * are errors, positive values are used for special but normal events.
5799  */
5800  Z_OK:               0,
5801  Z_STREAM_END:       1,
5802  Z_NEED_DICT:        2,
5803  Z_ERRNO:           -1,
5804  Z_STREAM_ERROR:    -2,
5805  Z_DATA_ERROR:      -3,
5806  //Z_MEM_ERROR:     -4,
5807  Z_BUF_ERROR:       -5,
5808  //Z_VERSION_ERROR: -6,
5809
5810  /* compression levels */
5811  Z_NO_COMPRESSION:         0,
5812  Z_BEST_SPEED:             1,
5813  Z_BEST_COMPRESSION:       9,
5814  Z_DEFAULT_COMPRESSION:   -1,
5815
5816
5817  Z_FILTERED:               1,
5818  Z_HUFFMAN_ONLY:           2,
5819  Z_RLE:                    3,
5820  Z_FIXED:                  4,
5821  Z_DEFAULT_STRATEGY:       0,
5822
5823  /* Possible values of the data_type field (though see inflate()) */
5824  Z_BINARY:                 0,
5825  Z_TEXT:                   1,
5826  //Z_ASCII:                1, // = Z_TEXT (deprecated)
5827  Z_UNKNOWN:                2,
5828
5829  /* The deflate compression method */
5830  Z_DEFLATED:               8
5831  //Z_NULL:                 null // Use -1 or null inline, depending on var type
5832};
5833
5834},{}],45:[function(require,module,exports){
5835'use strict';
5836
5837// Note: we can't get significant speed boost here.
5838// So write code to minimize size - no pregenerated tables
5839// and array tools dependencies.
5840
5841// (C) 1995-2013 Jean-loup Gailly and Mark Adler
5842// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5843//
5844// This software is provided 'as-is', without any express or implied
5845// warranty. In no event will the authors be held liable for any damages
5846// arising from the use of this software.
5847//
5848// Permission is granted to anyone to use this software for any purpose,
5849// including commercial applications, and to alter it and redistribute it
5850// freely, subject to the following restrictions:
5851//
5852// 1. The origin of this software must not be misrepresented; you must not
5853//   claim that you wrote the original software. If you use this software
5854//   in a product, an acknowledgment in the product documentation would be
5855//   appreciated but is not required.
5856// 2. Altered source versions must be plainly marked as such, and must not be
5857//   misrepresented as being the original software.
5858// 3. This notice may not be removed or altered from any source distribution.
5859
5860// Use ordinary array, since untyped makes no boost here
5861function makeTable() {
5862  var c, table = [];
5863
5864  for (var n = 0; n < 256; n++) {
5865    c = n;
5866    for (var k = 0; k < 8; k++) {
5867      c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
5868    }
5869    table[n] = c;
5870  }
5871
5872  return table;
5873}
5874
5875// Create table on load. Just 255 signed longs. Not a problem.
5876var crcTable = makeTable();
5877
5878
5879function crc32(crc, buf, len, pos) {
5880  var t = crcTable,
5881      end = pos + len;
5882
5883  crc ^= -1;
5884
5885  for (var i = pos; i < end; i++) {
5886    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
5887  }
5888
5889  return (crc ^ (-1)); // >>> 0;
5890}
5891
5892
5893module.exports = crc32;
5894
5895},{}],46:[function(require,module,exports){
5896'use strict';
5897
5898// (C) 1995-2013 Jean-loup Gailly and Mark Adler
5899// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5900//
5901// This software is provided 'as-is', without any express or implied
5902// warranty. In no event will the authors be held liable for any damages
5903// arising from the use of this software.
5904//
5905// Permission is granted to anyone to use this software for any purpose,
5906// including commercial applications, and to alter it and redistribute it
5907// freely, subject to the following restrictions:
5908//
5909// 1. The origin of this software must not be misrepresented; you must not
5910//   claim that you wrote the original software. If you use this software
5911//   in a product, an acknowledgment in the product documentation would be
5912//   appreciated but is not required.
5913// 2. Altered source versions must be plainly marked as such, and must not be
5914//   misrepresented as being the original software.
5915// 3. This notice may not be removed or altered from any source distribution.
5916
5917var utils   = require('../utils/common');
5918var trees   = require('./trees');
5919var adler32 = require('./adler32');
5920var crc32   = require('./crc32');
5921var msg     = require('./messages');
5922
5923/* Public constants ==========================================================*/
5924/* ===========================================================================*/
5925
5926
5927/* Allowed flush values; see deflate() and inflate() below for details */
5928var Z_NO_FLUSH      = 0;
5929var Z_PARTIAL_FLUSH = 1;
5930//var Z_SYNC_FLUSH    = 2;
5931var Z_FULL_FLUSH    = 3;
5932var Z_FINISH        = 4;
5933var Z_BLOCK         = 5;
5934//var Z_TREES         = 6;
5935
5936
5937/* Return codes for the compression/decompression functions. Negative values
5938 * are errors, positive values are used for special but normal events.
5939 */
5940var Z_OK            = 0;
5941var Z_STREAM_END    = 1;
5942//var Z_NEED_DICT     = 2;
5943//var Z_ERRNO         = -1;
5944var Z_STREAM_ERROR  = -2;
5945var Z_DATA_ERROR    = -3;
5946//var Z_MEM_ERROR     = -4;
5947var Z_BUF_ERROR     = -5;
5948//var Z_VERSION_ERROR = -6;
5949
5950
5951/* compression levels */
5952//var Z_NO_COMPRESSION      = 0;
5953//var Z_BEST_SPEED          = 1;
5954//var Z_BEST_COMPRESSION    = 9;
5955var Z_DEFAULT_COMPRESSION = -1;
5956
5957
5958var Z_FILTERED            = 1;
5959var Z_HUFFMAN_ONLY        = 2;
5960var Z_RLE                 = 3;
5961var Z_FIXED               = 4;
5962var Z_DEFAULT_STRATEGY    = 0;
5963
5964/* Possible values of the data_type field (though see inflate()) */
5965//var Z_BINARY              = 0;
5966//var Z_TEXT                = 1;
5967//var Z_ASCII               = 1; // = Z_TEXT
5968var Z_UNKNOWN             = 2;
5969
5970
5971/* The deflate compression method */
5972var Z_DEFLATED  = 8;
5973
5974/*============================================================================*/
5975
5976
5977var MAX_MEM_LEVEL = 9;
5978/* Maximum value for memLevel in deflateInit2 */
5979var MAX_WBITS = 15;
5980/* 32K LZ77 window */
5981var DEF_MEM_LEVEL = 8;
5982
5983
5984var LENGTH_CODES  = 29;
5985/* number of length codes, not counting the special END_BLOCK code */
5986var LITERALS      = 256;
5987/* number of literal bytes 0..255 */
5988var L_CODES       = LITERALS + 1 + LENGTH_CODES;
5989/* number of Literal or Length codes, including the END_BLOCK code */
5990var D_CODES       = 30;
5991/* number of distance codes */
5992var BL_CODES      = 19;
5993/* number of codes used to transfer the bit lengths */
5994var HEAP_SIZE     = 2 * L_CODES + 1;
5995/* maximum heap size */
5996var MAX_BITS  = 15;
5997/* All codes must not exceed MAX_BITS bits */
5998
5999var MIN_MATCH = 3;
6000var MAX_MATCH = 258;
6001var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
6002
6003var PRESET_DICT = 0x20;
6004
6005var INIT_STATE = 42;
6006var EXTRA_STATE = 69;
6007var NAME_STATE = 73;
6008var COMMENT_STATE = 91;
6009var HCRC_STATE = 103;
6010var BUSY_STATE = 113;
6011var FINISH_STATE = 666;
6012
6013var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
6014var BS_BLOCK_DONE     = 2; /* block flush performed */
6015var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
6016var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
6017
6018var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
6019
6020function err(strm, errorCode) {
6021  strm.msg = msg[errorCode];
6022  return errorCode;
6023}
6024
6025function rank(f) {
6026  return ((f) << 1) - ((f) > 4 ? 9 : 0);
6027}
6028
6029function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
6030
6031
6032/* =========================================================================
6033 * Flush as much pending output as possible. All deflate() output goes
6034 * through this function so some applications may wish to modify it
6035 * to avoid allocating a large strm->output buffer and copying into it.
6036 * (See also read_buf()).
6037 */
6038function flush_pending(strm) {
6039  var s = strm.state;
6040
6041  //_tr_flush_bits(s);
6042  var len = s.pending;
6043  if (len > strm.avail_out) {
6044    len = strm.avail_out;
6045  }
6046  if (len === 0) { return; }
6047
6048  utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
6049  strm.next_out += len;
6050  s.pending_out += len;
6051  strm.total_out += len;
6052  strm.avail_out -= len;
6053  s.pending -= len;
6054  if (s.pending === 0) {
6055    s.pending_out = 0;
6056  }
6057}
6058
6059
6060function flush_block_only(s, last) {
6061  trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
6062  s.block_start = s.strstart;
6063  flush_pending(s.strm);
6064}
6065
6066
6067function put_byte(s, b) {
6068  s.pending_buf[s.pending++] = b;
6069}
6070
6071
6072/* =========================================================================
6073 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
6074 * IN assertion: the stream state is correct and there is enough room in
6075 * pending_buf.
6076 */
6077function putShortMSB(s, b) {
6078//  put_byte(s, (Byte)(b >> 8));
6079//  put_byte(s, (Byte)(b & 0xff));
6080  s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
6081  s.pending_buf[s.pending++] = b & 0xff;
6082}
6083
6084
6085/* ===========================================================================
6086 * Read a new buffer from the current input stream, update the adler32
6087 * and total number of bytes read.  All deflate() input goes through
6088 * this function so some applications may wish to modify it to avoid
6089 * allocating a large strm->input buffer and copying from it.
6090 * (See also flush_pending()).
6091 */
6092function read_buf(strm, buf, start, size) {
6093  var len = strm.avail_in;
6094
6095  if (len > size) { len = size; }
6096  if (len === 0) { return 0; }
6097
6098  strm.avail_in -= len;
6099
6100  // zmemcpy(buf, strm->next_in, len);
6101  utils.arraySet(buf, strm.input, strm.next_in, len, start);
6102  if (strm.state.wrap === 1) {
6103    strm.adler = adler32(strm.adler, buf, len, start);
6104  }
6105
6106  else if (strm.state.wrap === 2) {
6107    strm.adler = crc32(strm.adler, buf, len, start);
6108  }
6109
6110  strm.next_in += len;
6111  strm.total_in += len;
6112
6113  return len;
6114}
6115
6116
6117/* ===========================================================================
6118 * Set match_start to the longest match starting at the given string and
6119 * return its length. Matches shorter or equal to prev_length are discarded,
6120 * in which case the result is equal to prev_length and match_start is
6121 * garbage.
6122 * IN assertions: cur_match is the head of the hash chain for the current
6123 *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
6124 * OUT assertion: the match length is not greater than s->lookahead.
6125 */
6126function longest_match(s, cur_match) {
6127  var chain_length = s.max_chain_length;      /* max hash chain length */
6128  var scan = s.strstart; /* current string */
6129  var match;                       /* matched string */
6130  var len;                           /* length of current match */
6131  var best_len = s.prev_length;              /* best match length so far */
6132  var nice_match = s.nice_match;             /* stop if match long enough */
6133  var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
6134      s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
6135
6136  var _win = s.window; // shortcut
6137
6138  var wmask = s.w_mask;
6139  var prev  = s.prev;
6140
6141  /* Stop when cur_match becomes <= limit. To simplify the code,
6142   * we prevent matches with the string of window index 0.
6143   */
6144
6145  var strend = s.strstart + MAX_MATCH;
6146  var scan_end1  = _win[scan + best_len - 1];
6147  var scan_end   = _win[scan + best_len];
6148
6149  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
6150   * It is easy to get rid of this optimization if necessary.
6151   */
6152  // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
6153
6154  /* Do not waste too much time if we already have a good match: */
6155  if (s.prev_length >= s.good_match) {
6156    chain_length >>= 2;
6157  }
6158  /* Do not look for matches beyond the end of the input. This is necessary
6159   * to make deflate deterministic.
6160   */
6161  if (nice_match > s.lookahead) { nice_match = s.lookahead; }
6162
6163  // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
6164
6165  do {
6166    // Assert(cur_match < s->strstart, "no future");
6167    match = cur_match;
6168
6169    /* Skip to next match if the match length cannot increase
6170     * or if the match length is less than 2.  Note that the checks below
6171     * for insufficient lookahead only occur occasionally for performance
6172     * reasons.  Therefore uninitialized memory will be accessed, and
6173     * conditional jumps will be made that depend on those values.
6174     * However the length of the match is limited to the lookahead, so
6175     * the output of deflate is not affected by the uninitialized values.
6176     */
6177
6178    if (_win[match + best_len]     !== scan_end  ||
6179        _win[match + best_len - 1] !== scan_end1 ||
6180        _win[match]                !== _win[scan] ||
6181        _win[++match]              !== _win[scan + 1]) {
6182      continue;
6183    }
6184
6185    /* The check at best_len-1 can be removed because it will be made
6186     * again later. (This heuristic is not always a win.)
6187     * It is not necessary to compare scan[2] and match[2] since they
6188     * are always equal when the other bytes match, given that
6189     * the hash keys are equal and that HASH_BITS >= 8.
6190     */
6191    scan += 2;
6192    match++;
6193    // Assert(*scan == *match, "match[2]?");
6194
6195    /* We check for insufficient lookahead only every 8th comparison;
6196     * the 256th check will be made at strstart+258.
6197     */
6198    do {
6199      /*jshint noempty:false*/
6200    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6201             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6202             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6203             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6204             scan < strend);
6205
6206    // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
6207
6208    len = MAX_MATCH - (strend - scan);
6209    scan = strend - MAX_MATCH;
6210
6211    if (len > best_len) {
6212      s.match_start = cur_match;
6213      best_len = len;
6214      if (len >= nice_match) {
6215        break;
6216      }
6217      scan_end1  = _win[scan + best_len - 1];
6218      scan_end   = _win[scan + best_len];
6219    }
6220  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
6221
6222  if (best_len <= s.lookahead) {
6223    return best_len;
6224  }
6225  return s.lookahead;
6226}
6227
6228
6229/* ===========================================================================
6230 * Fill the window when the lookahead becomes insufficient.
6231 * Updates strstart and lookahead.
6232 *
6233 * IN assertion: lookahead < MIN_LOOKAHEAD
6234 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
6235 *    At least one byte has been read, or avail_in == 0; reads are
6236 *    performed for at least two bytes (required for the zip translate_eol
6237 *    option -- not supported here).
6238 */
6239function fill_window(s) {
6240  var _w_size = s.w_size;
6241  var p, n, m, more, str;
6242
6243  //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
6244
6245  do {
6246    more = s.window_size - s.lookahead - s.strstart;
6247
6248    // JS ints have 32 bit, block below not needed
6249    /* Deal with !@#$% 64K limit: */
6250    //if (sizeof(int) <= 2) {
6251    //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
6252    //        more = wsize;
6253    //
6254    //  } else if (more == (unsigned)(-1)) {
6255    //        /* Very unlikely, but possible on 16 bit machine if
6256    //         * strstart == 0 && lookahead == 1 (input done a byte at time)
6257    //         */
6258    //        more--;
6259    //    }
6260    //}
6261
6262
6263    /* If the window is almost full and there is insufficient lookahead,
6264     * move the upper half to the lower one to make room in the upper half.
6265     */
6266    if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
6267
6268      utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
6269      s.match_start -= _w_size;
6270      s.strstart -= _w_size;
6271      /* we now have strstart >= MAX_DIST */
6272      s.block_start -= _w_size;
6273
6274      /* Slide the hash table (could be avoided with 32 bit values
6275       at the expense of memory usage). We slide even when level == 0
6276       to keep the hash table consistent if we switch back to level > 0
6277       later. (Using level 0 permanently is not an optimal usage of
6278       zlib, so we don't care about this pathological case.)
6279       */
6280
6281      n = s.hash_size;
6282      p = n;
6283      do {
6284        m = s.head[--p];
6285        s.head[p] = (m >= _w_size ? m - _w_size : 0);
6286      } while (--n);
6287
6288      n = _w_size;
6289      p = n;
6290      do {
6291        m = s.prev[--p];
6292        s.prev[p] = (m >= _w_size ? m - _w_size : 0);
6293        /* If n is not on any hash chain, prev[n] is garbage but
6294         * its value will never be used.
6295         */
6296      } while (--n);
6297
6298      more += _w_size;
6299    }
6300    if (s.strm.avail_in === 0) {
6301      break;
6302    }
6303
6304    /* If there was no sliding:
6305     *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
6306     *    more == window_size - lookahead - strstart
6307     * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
6308     * => more >= window_size - 2*WSIZE + 2
6309     * In the BIG_MEM or MMAP case (not yet supported),
6310     *   window_size == input_size + MIN_LOOKAHEAD  &&
6311     *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
6312     * Otherwise, window_size == 2*WSIZE so more >= 2.
6313     * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
6314     */
6315    //Assert(more >= 2, "more < 2");
6316    n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
6317    s.lookahead += n;
6318
6319    /* Initialize the hash value now that we have some input: */
6320    if (s.lookahead + s.insert >= MIN_MATCH) {
6321      str = s.strstart - s.insert;
6322      s.ins_h = s.window[str];
6323
6324      /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
6325      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
6326//#if MIN_MATCH != 3
6327//        Call update_hash() MIN_MATCH-3 more times
6328//#endif
6329      while (s.insert) {
6330        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
6331        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
6332
6333        s.prev[str & s.w_mask] = s.head[s.ins_h];
6334        s.head[s.ins_h] = str;
6335        str++;
6336        s.insert--;
6337        if (s.lookahead + s.insert < MIN_MATCH) {
6338          break;
6339        }
6340      }
6341    }
6342    /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
6343     * but this is not important since only literal bytes will be emitted.
6344     */
6345
6346  } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
6347
6348  /* If the WIN_INIT bytes after the end of the current data have never been
6349   * written, then zero those bytes in order to avoid memory check reports of
6350   * the use of uninitialized (or uninitialised as Julian writes) bytes by
6351   * the longest match routines.  Update the high water mark for the next
6352   * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
6353   * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
6354   */
6355//  if (s.high_water < s.window_size) {
6356//    var curr = s.strstart + s.lookahead;
6357//    var init = 0;
6358//
6359//    if (s.high_water < curr) {
6360//      /* Previous high water mark below current data -- zero WIN_INIT
6361//       * bytes or up to end of window, whichever is less.
6362//       */
6363//      init = s.window_size - curr;
6364//      if (init > WIN_INIT)
6365//        init = WIN_INIT;
6366//      zmemzero(s->window + curr, (unsigned)init);
6367//      s->high_water = curr + init;
6368//    }
6369//    else if (s->high_water < (ulg)curr + WIN_INIT) {
6370//      /* High water mark at or above current data, but below current data
6371//       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
6372//       * to end of window, whichever is less.
6373//       */
6374//      init = (ulg)curr + WIN_INIT - s->high_water;
6375//      if (init > s->window_size - s->high_water)
6376//        init = s->window_size - s->high_water;
6377//      zmemzero(s->window + s->high_water, (unsigned)init);
6378//      s->high_water += init;
6379//    }
6380//  }
6381//
6382//  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
6383//    "not enough room for search");
6384}
6385
6386/* ===========================================================================
6387 * Copy without compression as much as possible from the input stream, return
6388 * the current block state.
6389 * This function does not insert new strings in the dictionary since
6390 * uncompressible data is probably not useful. This function is used
6391 * only for the level=0 compression option.
6392 * NOTE: this function should be optimized to avoid extra copying from
6393 * window to pending_buf.
6394 */
6395function deflate_stored(s, flush) {
6396  /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
6397   * to pending_buf_size, and each stored block has a 5 byte header:
6398   */
6399  var max_block_size = 0xffff;
6400
6401  if (max_block_size > s.pending_buf_size - 5) {
6402    max_block_size = s.pending_buf_size - 5;
6403  }
6404
6405  /* Copy as much as possible from input to output: */
6406  for (;;) {
6407    /* Fill the window as much as possible: */
6408    if (s.lookahead <= 1) {
6409
6410      //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
6411      //  s->block_start >= (long)s->w_size, "slide too late");
6412//      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
6413//        s.block_start >= s.w_size)) {
6414//        throw  new Error("slide too late");
6415//      }
6416
6417      fill_window(s);
6418      if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
6419        return BS_NEED_MORE;
6420      }
6421
6422      if (s.lookahead === 0) {
6423        break;
6424      }
6425      /* flush the current block */
6426    }
6427    //Assert(s->block_start >= 0L, "block gone");
6428//    if (s.block_start < 0) throw new Error("block gone");
6429
6430    s.strstart += s.lookahead;
6431    s.lookahead = 0;
6432
6433    /* Emit a stored block if pending_buf will be full: */
6434    var max_start = s.block_start + max_block_size;
6435
6436    if (s.strstart === 0 || s.strstart >= max_start) {
6437      /* strstart == 0 is possible when wraparound on 16-bit machine */
6438      s.lookahead = s.strstart - max_start;
6439      s.strstart = max_start;
6440      /*** FLUSH_BLOCK(s, 0); ***/
6441      flush_block_only(s, false);
6442      if (s.strm.avail_out === 0) {
6443        return BS_NEED_MORE;
6444      }
6445      /***/
6446
6447
6448    }
6449    /* Flush if we may have to slide, otherwise block_start may become
6450     * negative and the data will be gone:
6451     */
6452    if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
6453      /*** FLUSH_BLOCK(s, 0); ***/
6454      flush_block_only(s, false);
6455      if (s.strm.avail_out === 0) {
6456        return BS_NEED_MORE;
6457      }
6458      /***/
6459    }
6460  }
6461
6462  s.insert = 0;
6463
6464  if (flush === Z_FINISH) {
6465    /*** FLUSH_BLOCK(s, 1); ***/
6466    flush_block_only(s, true);
6467    if (s.strm.avail_out === 0) {
6468      return BS_FINISH_STARTED;
6469    }
6470    /***/
6471    return BS_FINISH_DONE;
6472  }
6473
6474  if (s.strstart > s.block_start) {
6475    /*** FLUSH_BLOCK(s, 0); ***/
6476    flush_block_only(s, false);
6477    if (s.strm.avail_out === 0) {
6478      return BS_NEED_MORE;
6479    }
6480    /***/
6481  }
6482
6483  return BS_NEED_MORE;
6484}
6485
6486/* ===========================================================================
6487 * Compress as much as possible from the input stream, return the current
6488 * block state.
6489 * This function does not perform lazy evaluation of matches and inserts
6490 * new strings in the dictionary only for unmatched strings or for short
6491 * matches. It is used only for the fast compression options.
6492 */
6493function deflate_fast(s, flush) {
6494  var hash_head;        /* head of the hash chain */
6495  var bflush;           /* set if current block must be flushed */
6496
6497  for (;;) {
6498    /* Make sure that we always have enough lookahead, except
6499     * at the end of the input file. We need MAX_MATCH bytes
6500     * for the next match, plus MIN_MATCH bytes to insert the
6501     * string following the next match.
6502     */
6503    if (s.lookahead < MIN_LOOKAHEAD) {
6504      fill_window(s);
6505      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
6506        return BS_NEED_MORE;
6507      }
6508      if (s.lookahead === 0) {
6509        break; /* flush the current block */
6510      }
6511    }
6512
6513    /* Insert the string window[strstart .. strstart+2] in the
6514     * dictionary, and set hash_head to the head of the hash chain:
6515     */
6516    hash_head = 0/*NIL*/;
6517    if (s.lookahead >= MIN_MATCH) {
6518      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6519      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6520      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6521      s.head[s.ins_h] = s.strstart;
6522      /***/
6523    }
6524
6525    /* Find the longest match, discarding those <= prev_length.
6526     * At this point we have always match_length < MIN_MATCH
6527     */
6528    if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
6529      /* To simplify the code, we prevent matches with the string
6530       * of window index 0 (in particular we have to avoid a match
6531       * of the string with itself at the start of the input file).
6532       */
6533      s.match_length = longest_match(s, hash_head);
6534      /* longest_match() sets match_start */
6535    }
6536    if (s.match_length >= MIN_MATCH) {
6537      // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
6538
6539      /*** _tr_tally_dist(s, s.strstart - s.match_start,
6540                     s.match_length - MIN_MATCH, bflush); ***/
6541      bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
6542
6543      s.lookahead -= s.match_length;
6544
6545      /* Insert new strings in the hash table only if the match length
6546       * is not too large. This saves time but degrades compression.
6547       */
6548      if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
6549        s.match_length--; /* string at strstart already in table */
6550        do {
6551          s.strstart++;
6552          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6553          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6554          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6555          s.head[s.ins_h] = s.strstart;
6556          /***/
6557          /* strstart never exceeds WSIZE-MAX_MATCH, so there are
6558           * always MIN_MATCH bytes ahead.
6559           */
6560        } while (--s.match_length !== 0);
6561        s.strstart++;
6562      } else
6563      {
6564        s.strstart += s.match_length;
6565        s.match_length = 0;
6566        s.ins_h = s.window[s.strstart];
6567        /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
6568        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
6569
6570//#if MIN_MATCH != 3
6571//                Call UPDATE_HASH() MIN_MATCH-3 more times
6572//#endif
6573        /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
6574         * matter since it will be recomputed at next deflate call.
6575         */
6576      }
6577    } else {
6578      /* No match, output a literal byte */
6579      //Tracevv((stderr,"%c", s.window[s.strstart]));
6580      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6581      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6582
6583      s.lookahead--;
6584      s.strstart++;
6585    }
6586    if (bflush) {
6587      /*** FLUSH_BLOCK(s, 0); ***/
6588      flush_block_only(s, false);
6589      if (s.strm.avail_out === 0) {
6590        return BS_NEED_MORE;
6591      }
6592      /***/
6593    }
6594  }
6595  s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
6596  if (flush === Z_FINISH) {
6597    /*** FLUSH_BLOCK(s, 1); ***/
6598    flush_block_only(s, true);
6599    if (s.strm.avail_out === 0) {
6600      return BS_FINISH_STARTED;
6601    }
6602    /***/
6603    return BS_FINISH_DONE;
6604  }
6605  if (s.last_lit) {
6606    /*** FLUSH_BLOCK(s, 0); ***/
6607    flush_block_only(s, false);
6608    if (s.strm.avail_out === 0) {
6609      return BS_NEED_MORE;
6610    }
6611    /***/
6612  }
6613  return BS_BLOCK_DONE;
6614}
6615
6616/* ===========================================================================
6617 * Same as above, but achieves better compression. We use a lazy
6618 * evaluation for matches: a match is finally adopted only if there is
6619 * no better match at the next window position.
6620 */
6621function deflate_slow(s, flush) {
6622  var hash_head;          /* head of hash chain */
6623  var bflush;              /* set if current block must be flushed */
6624
6625  var max_insert;
6626
6627  /* Process the input block. */
6628  for (;;) {
6629    /* Make sure that we always have enough lookahead, except
6630     * at the end of the input file. We need MAX_MATCH bytes
6631     * for the next match, plus MIN_MATCH bytes to insert the
6632     * string following the next match.
6633     */
6634    if (s.lookahead < MIN_LOOKAHEAD) {
6635      fill_window(s);
6636      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
6637        return BS_NEED_MORE;
6638      }
6639      if (s.lookahead === 0) { break; } /* flush the current block */
6640    }
6641
6642    /* Insert the string window[strstart .. strstart+2] in the
6643     * dictionary, and set hash_head to the head of the hash chain:
6644     */
6645    hash_head = 0/*NIL*/;
6646    if (s.lookahead >= MIN_MATCH) {
6647      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6648      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6649      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6650      s.head[s.ins_h] = s.strstart;
6651      /***/
6652    }
6653
6654    /* Find the longest match, discarding those <= prev_length.
6655     */
6656    s.prev_length = s.match_length;
6657    s.prev_match = s.match_start;
6658    s.match_length = MIN_MATCH - 1;
6659
6660    if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
6661        s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
6662      /* To simplify the code, we prevent matches with the string
6663       * of window index 0 (in particular we have to avoid a match
6664       * of the string with itself at the start of the input file).
6665       */
6666      s.match_length = longest_match(s, hash_head);
6667      /* longest_match() sets match_start */
6668
6669      if (s.match_length <= 5 &&
6670         (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
6671
6672        /* If prev_match is also MIN_MATCH, match_start is garbage
6673         * but we will ignore the current match anyway.
6674         */
6675        s.match_length = MIN_MATCH - 1;
6676      }
6677    }
6678    /* If there was a match at the previous step and the current
6679     * match is not better, output the previous match:
6680     */
6681    if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
6682      max_insert = s.strstart + s.lookahead - MIN_MATCH;
6683      /* Do not insert strings in hash table beyond this. */
6684
6685      //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
6686
6687      /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
6688                     s.prev_length - MIN_MATCH, bflush);***/
6689      bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
6690      /* Insert in hash table all strings up to the end of the match.
6691       * strstart-1 and strstart are already inserted. If there is not
6692       * enough lookahead, the last two strings are not inserted in
6693       * the hash table.
6694       */
6695      s.lookahead -= s.prev_length - 1;
6696      s.prev_length -= 2;
6697      do {
6698        if (++s.strstart <= max_insert) {
6699          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6700          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6701          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6702          s.head[s.ins_h] = s.strstart;
6703          /***/
6704        }
6705      } while (--s.prev_length !== 0);
6706      s.match_available = 0;
6707      s.match_length = MIN_MATCH - 1;
6708      s.strstart++;
6709
6710      if (bflush) {
6711        /*** FLUSH_BLOCK(s, 0); ***/
6712        flush_block_only(s, false);
6713        if (s.strm.avail_out === 0) {
6714          return BS_NEED_MORE;
6715        }
6716        /***/
6717      }
6718
6719    } else if (s.match_available) {
6720      /* If there was no match at the previous position, output a
6721       * single literal. If there was a match but the current match
6722       * is longer, truncate the previous match to a single literal.
6723       */
6724      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
6725      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
6726      bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
6727
6728      if (bflush) {
6729        /*** FLUSH_BLOCK_ONLY(s, 0) ***/
6730        flush_block_only(s, false);
6731        /***/
6732      }
6733      s.strstart++;
6734      s.lookahead--;
6735      if (s.strm.avail_out === 0) {
6736        return BS_NEED_MORE;
6737      }
6738    } else {
6739      /* There is no previous match to compare with, wait for
6740       * the next step to decide.
6741       */
6742      s.match_available = 1;
6743      s.strstart++;
6744      s.lookahead--;
6745    }
6746  }
6747  //Assert (flush != Z_NO_FLUSH, "no flush?");
6748  if (s.match_available) {
6749    //Tracevv((stderr,"%c", s->window[s->strstart-1]));
6750    /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
6751    bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
6752
6753    s.match_available = 0;
6754  }
6755  s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
6756  if (flush === Z_FINISH) {
6757    /*** FLUSH_BLOCK(s, 1); ***/
6758    flush_block_only(s, true);
6759    if (s.strm.avail_out === 0) {
6760      return BS_FINISH_STARTED;
6761    }
6762    /***/
6763    return BS_FINISH_DONE;
6764  }
6765  if (s.last_lit) {
6766    /*** FLUSH_BLOCK(s, 0); ***/
6767    flush_block_only(s, false);
6768    if (s.strm.avail_out === 0) {
6769      return BS_NEED_MORE;
6770    }
6771    /***/
6772  }
6773
6774  return BS_BLOCK_DONE;
6775}
6776
6777
6778/* ===========================================================================
6779 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
6780 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
6781 * deflate switches away from Z_RLE.)
6782 */
6783function deflate_rle(s, flush) {
6784  var bflush;            /* set if current block must be flushed */
6785  var prev;              /* byte at distance one to match */
6786  var scan, strend;      /* scan goes up to strend for length of run */
6787
6788  var _win = s.window;
6789
6790  for (;;) {
6791    /* Make sure that we always have enough lookahead, except
6792     * at the end of the input file. We need MAX_MATCH bytes
6793     * for the longest run, plus one for the unrolled loop.
6794     */
6795    if (s.lookahead <= MAX_MATCH) {
6796      fill_window(s);
6797      if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
6798        return BS_NEED_MORE;
6799      }
6800      if (s.lookahead === 0) { break; } /* flush the current block */
6801    }
6802
6803    /* See how many times the previous byte repeats */
6804    s.match_length = 0;
6805    if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
6806      scan = s.strstart - 1;
6807      prev = _win[scan];
6808      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
6809        strend = s.strstart + MAX_MATCH;
6810        do {
6811          /*jshint noempty:false*/
6812        } while (prev === _win[++scan] && prev === _win[++scan] &&
6813                 prev === _win[++scan] && prev === _win[++scan] &&
6814                 prev === _win[++scan] && prev === _win[++scan] &&
6815                 prev === _win[++scan] && prev === _win[++scan] &&
6816                 scan < strend);
6817        s.match_length = MAX_MATCH - (strend - scan);
6818        if (s.match_length > s.lookahead) {
6819          s.match_length = s.lookahead;
6820        }
6821      }
6822      //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
6823    }
6824
6825    /* Emit match if have run of MIN_MATCH or longer, else emit literal */
6826    if (s.match_length >= MIN_MATCH) {
6827      //check_match(s, s.strstart, s.strstart - 1, s.match_length);
6828
6829      /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
6830      bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
6831
6832      s.lookahead -= s.match_length;
6833      s.strstart += s.match_length;
6834      s.match_length = 0;
6835    } else {
6836      /* No match, output a literal byte */
6837      //Tracevv((stderr,"%c", s->window[s->strstart]));
6838      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6839      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6840
6841      s.lookahead--;
6842      s.strstart++;
6843    }
6844    if (bflush) {
6845      /*** FLUSH_BLOCK(s, 0); ***/
6846      flush_block_only(s, false);
6847      if (s.strm.avail_out === 0) {
6848        return BS_NEED_MORE;
6849      }
6850      /***/
6851    }
6852  }
6853  s.insert = 0;
6854  if (flush === Z_FINISH) {
6855    /*** FLUSH_BLOCK(s, 1); ***/
6856    flush_block_only(s, true);
6857    if (s.strm.avail_out === 0) {
6858      return BS_FINISH_STARTED;
6859    }
6860    /***/
6861    return BS_FINISH_DONE;
6862  }
6863  if (s.last_lit) {
6864    /*** FLUSH_BLOCK(s, 0); ***/
6865    flush_block_only(s, false);
6866    if (s.strm.avail_out === 0) {
6867      return BS_NEED_MORE;
6868    }
6869    /***/
6870  }
6871  return BS_BLOCK_DONE;
6872}
6873
6874/* ===========================================================================
6875 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
6876 * (It will be regenerated if this run of deflate switches away from Huffman.)
6877 */
6878function deflate_huff(s, flush) {
6879  var bflush;             /* set if current block must be flushed */
6880
6881  for (;;) {
6882    /* Make sure that we have a literal to write. */
6883    if (s.lookahead === 0) {
6884      fill_window(s);
6885      if (s.lookahead === 0) {
6886        if (flush === Z_NO_FLUSH) {
6887          return BS_NEED_MORE;
6888        }
6889        break;      /* flush the current block */
6890      }
6891    }
6892
6893    /* Output a literal byte */
6894    s.match_length = 0;
6895    //Tracevv((stderr,"%c", s->window[s->strstart]));
6896    /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6897    bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6898    s.lookahead--;
6899    s.strstart++;
6900    if (bflush) {
6901      /*** FLUSH_BLOCK(s, 0); ***/
6902      flush_block_only(s, false);
6903      if (s.strm.avail_out === 0) {
6904        return BS_NEED_MORE;
6905      }
6906      /***/
6907    }
6908  }
6909  s.insert = 0;
6910  if (flush === Z_FINISH) {
6911    /*** FLUSH_BLOCK(s, 1); ***/
6912    flush_block_only(s, true);
6913    if (s.strm.avail_out === 0) {
6914      return BS_FINISH_STARTED;
6915    }
6916    /***/
6917    return BS_FINISH_DONE;
6918  }
6919  if (s.last_lit) {
6920    /*** FLUSH_BLOCK(s, 0); ***/
6921    flush_block_only(s, false);
6922    if (s.strm.avail_out === 0) {
6923      return BS_NEED_MORE;
6924    }
6925    /***/
6926  }
6927  return BS_BLOCK_DONE;
6928}
6929
6930/* Values for max_lazy_match, good_match and max_chain_length, depending on
6931 * the desired pack level (0..9). The values given below have been tuned to
6932 * exclude worst case performance for pathological files. Better values may be
6933 * found for specific files.
6934 */
6935function Config(good_length, max_lazy, nice_length, max_chain, func) {
6936  this.good_length = good_length;
6937  this.max_lazy = max_lazy;
6938  this.nice_length = nice_length;
6939  this.max_chain = max_chain;
6940  this.func = func;
6941}
6942
6943var configuration_table;
6944
6945configuration_table = [
6946  /*      good lazy nice chain */
6947  new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
6948  new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
6949  new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
6950  new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
6951
6952  new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
6953  new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
6954  new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
6955  new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
6956  new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
6957  new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
6958];
6959
6960
6961/* ===========================================================================
6962 * Initialize the "longest match" routines for a new zlib stream
6963 */
6964function lm_init(s) {
6965  s.window_size = 2 * s.w_size;
6966
6967  /*** CLEAR_HASH(s); ***/
6968  zero(s.head); // Fill with NIL (= 0);
6969
6970  /* Set the default configuration parameters:
6971   */
6972  s.max_lazy_match = configuration_table[s.level].max_lazy;
6973  s.good_match = configuration_table[s.level].good_length;
6974  s.nice_match = configuration_table[s.level].nice_length;
6975  s.max_chain_length = configuration_table[s.level].max_chain;
6976
6977  s.strstart = 0;
6978  s.block_start = 0;
6979  s.lookahead = 0;
6980  s.insert = 0;
6981  s.match_length = s.prev_length = MIN_MATCH - 1;
6982  s.match_available = 0;
6983  s.ins_h = 0;
6984}
6985
6986
6987function DeflateState() {
6988  this.strm = null;            /* pointer back to this zlib stream */
6989  this.status = 0;            /* as the name implies */
6990  this.pending_buf = null;      /* output still pending */
6991  this.pending_buf_size = 0;  /* size of pending_buf */
6992  this.pending_out = 0;       /* next pending byte to output to the stream */
6993  this.pending = 0;           /* nb of bytes in the pending buffer */
6994  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
6995  this.gzhead = null;         /* gzip header information to write */
6996  this.gzindex = 0;           /* where in extra, name, or comment */
6997  this.method = Z_DEFLATED; /* can only be DEFLATED */
6998  this.last_flush = -1;   /* value of flush param for previous deflate call */
6999
7000  this.w_size = 0;  /* LZ77 window size (32K by default) */
7001  this.w_bits = 0;  /* log2(w_size)  (8..16) */
7002  this.w_mask = 0;  /* w_size - 1 */
7003
7004  this.window = null;
7005  /* Sliding window. Input bytes are read into the second half of the window,
7006   * and move to the first half later to keep a dictionary of at least wSize
7007   * bytes. With this organization, matches are limited to a distance of
7008   * wSize-MAX_MATCH bytes, but this ensures that IO is always
7009   * performed with a length multiple of the block size.
7010   */
7011
7012  this.window_size = 0;
7013  /* Actual size of window: 2*wSize, except when the user input buffer
7014   * is directly used as sliding window.
7015   */
7016
7017  this.prev = null;
7018  /* Link to older string with same hash index. To limit the size of this
7019   * array to 64K, this link is maintained only for the last 32K strings.
7020   * An index in this array is thus a window index modulo 32K.
7021   */
7022
7023  this.head = null;   /* Heads of the hash chains or NIL. */
7024
7025  this.ins_h = 0;       /* hash index of string to be inserted */
7026  this.hash_size = 0;   /* number of elements in hash table */
7027  this.hash_bits = 0;   /* log2(hash_size) */
7028  this.hash_mask = 0;   /* hash_size-1 */
7029
7030  this.hash_shift = 0;
7031  /* Number of bits by which ins_h must be shifted at each input
7032   * step. It must be such that after MIN_MATCH steps, the oldest
7033   * byte no longer takes part in the hash key, that is:
7034   *   hash_shift * MIN_MATCH >= hash_bits
7035   */
7036
7037  this.block_start = 0;
7038  /* Window position at the beginning of the current output block. Gets
7039   * negative when the window is moved backwards.
7040   */
7041
7042  this.match_length = 0;      /* length of best match */
7043  this.prev_match = 0;        /* previous match */
7044  this.match_available = 0;   /* set if previous match exists */
7045  this.strstart = 0;          /* start of string to insert */
7046  this.match_start = 0;       /* start of matching string */
7047  this.lookahead = 0;         /* number of valid bytes ahead in window */
7048
7049  this.prev_length = 0;
7050  /* Length of the best match at previous step. Matches not greater than this
7051   * are discarded. This is used in the lazy match evaluation.
7052   */
7053
7054  this.max_chain_length = 0;
7055  /* To speed up deflation, hash chains are never searched beyond this
7056   * length.  A higher limit improves compression ratio but degrades the
7057   * speed.
7058   */
7059
7060  this.max_lazy_match = 0;
7061  /* Attempt to find a better match only when the current match is strictly
7062   * smaller than this value. This mechanism is used only for compression
7063   * levels >= 4.
7064   */
7065  // That's alias to max_lazy_match, don't use directly
7066  //this.max_insert_length = 0;
7067  /* Insert new strings in the hash table only if the match length is not
7068   * greater than this length. This saves time but degrades compression.
7069   * max_insert_length is used only for compression levels <= 3.
7070   */
7071
7072  this.level = 0;     /* compression level (1..9) */
7073  this.strategy = 0;  /* favor or force Huffman coding*/
7074
7075  this.good_match = 0;
7076  /* Use a faster search when the previous match is longer than this */
7077
7078  this.nice_match = 0; /* Stop searching when current match exceeds this */
7079
7080              /* used by trees.c: */
7081
7082  /* Didn't use ct_data typedef below to suppress compiler warning */
7083
7084  // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
7085  // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
7086  // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
7087
7088  // Use flat array of DOUBLE size, with interleaved fata,
7089  // because JS does not support effective
7090  this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
7091  this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
7092  this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
7093  zero(this.dyn_ltree);
7094  zero(this.dyn_dtree);
7095  zero(this.bl_tree);
7096
7097  this.l_desc   = null;         /* desc. for literal tree */
7098  this.d_desc   = null;         /* desc. for distance tree */
7099  this.bl_desc  = null;         /* desc. for bit length tree */
7100
7101  //ush bl_count[MAX_BITS+1];
7102  this.bl_count = new utils.Buf16(MAX_BITS + 1);
7103  /* number of codes at each bit length for an optimal tree */
7104
7105  //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
7106  this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
7107  zero(this.heap);
7108
7109  this.heap_len = 0;               /* number of elements in the heap */
7110  this.heap_max = 0;               /* element of largest frequency */
7111  /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
7112   * The same heap array is used to build all trees.
7113   */
7114
7115  this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
7116  zero(this.depth);
7117  /* Depth of each subtree used as tie breaker for trees of equal frequency
7118   */
7119
7120  this.l_buf = 0;          /* buffer index for literals or lengths */
7121
7122  this.lit_bufsize = 0;
7123  /* Size of match buffer for literals/lengths.  There are 4 reasons for
7124   * limiting lit_bufsize to 64K:
7125   *   - frequencies can be kept in 16 bit counters
7126   *   - if compression is not successful for the first block, all input
7127   *     data is still in the window so we can still emit a stored block even
7128   *     when input comes from standard input.  (This can also be done for
7129   *     all blocks if lit_bufsize is not greater than 32K.)
7130   *   - if compression is not successful for a file smaller than 64K, we can
7131   *     even emit a stored file instead of a stored block (saving 5 bytes).
7132   *     This is applicable only for zip (not gzip or zlib).
7133   *   - creating new Huffman trees less frequently may not provide fast
7134   *     adaptation to changes in the input data statistics. (Take for
7135   *     example a binary file with poorly compressible code followed by
7136   *     a highly compressible string table.) Smaller buffer sizes give
7137   *     fast adaptation but have of course the overhead of transmitting
7138   *     trees more frequently.
7139   *   - I can't count above 4
7140   */
7141
7142  this.last_lit = 0;      /* running index in l_buf */
7143
7144  this.d_buf = 0;
7145  /* Buffer index for distances. To simplify the code, d_buf and l_buf have
7146   * the same number of elements. To use different lengths, an extra flag
7147   * array would be necessary.
7148   */
7149
7150  this.opt_len = 0;       /* bit length of current block with optimal trees */
7151  this.static_len = 0;    /* bit length of current block with static trees */
7152  this.matches = 0;       /* number of string matches in current block */
7153  this.insert = 0;        /* bytes at end of window left to insert */
7154
7155
7156  this.bi_buf = 0;
7157  /* Output buffer. bits are inserted starting at the bottom (least
7158   * significant bits).
7159   */
7160  this.bi_valid = 0;
7161  /* Number of valid bits in bi_buf.  All bits above the last valid bit
7162   * are always zero.
7163   */
7164
7165  // Used for window memory init. We safely ignore it for JS. That makes
7166  // sense only for pointers and memory check tools.
7167  //this.high_water = 0;
7168  /* High water mark offset in window for initialized bytes -- bytes above
7169   * this are set to zero in order to avoid memory check warnings when
7170   * longest match routines access bytes past the input.  This is then
7171   * updated to the new high water mark.
7172   */
7173}
7174
7175
7176function deflateResetKeep(strm) {
7177  var s;
7178
7179  if (!strm || !strm.state) {
7180    return err(strm, Z_STREAM_ERROR);
7181  }
7182
7183  strm.total_in = strm.total_out = 0;
7184  strm.data_type = Z_UNKNOWN;
7185
7186  s = strm.state;
7187  s.pending = 0;
7188  s.pending_out = 0;
7189
7190  if (s.wrap < 0) {
7191    s.wrap = -s.wrap;
7192    /* was made negative by deflate(..., Z_FINISH); */
7193  }
7194  s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
7195  strm.adler = (s.wrap === 2) ?
7196    0  // crc32(0, Z_NULL, 0)
7197  :
7198    1; // adler32(0, Z_NULL, 0)
7199  s.last_flush = Z_NO_FLUSH;
7200  trees._tr_init(s);
7201  return Z_OK;
7202}
7203
7204
7205function deflateReset(strm) {
7206  var ret = deflateResetKeep(strm);
7207  if (ret === Z_OK) {
7208    lm_init(strm.state);
7209  }
7210  return ret;
7211}
7212
7213
7214function deflateSetHeader(strm, head) {
7215  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
7216  if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
7217  strm.state.gzhead = head;
7218  return Z_OK;
7219}
7220
7221
7222function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
7223  if (!strm) { // === Z_NULL
7224    return Z_STREAM_ERROR;
7225  }
7226  var wrap = 1;
7227
7228  if (level === Z_DEFAULT_COMPRESSION) {
7229    level = 6;
7230  }
7231
7232  if (windowBits < 0) { /* suppress zlib wrapper */
7233    wrap = 0;
7234    windowBits = -windowBits;
7235  }
7236
7237  else if (windowBits > 15) {
7238    wrap = 2;           /* write gzip wrapper instead */
7239    windowBits -= 16;
7240  }
7241
7242
7243  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
7244    windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
7245    strategy < 0 || strategy > Z_FIXED) {
7246    return err(strm, Z_STREAM_ERROR);
7247  }
7248
7249
7250  if (windowBits === 8) {
7251    windowBits = 9;
7252  }
7253  /* until 256-byte window bug fixed */
7254
7255  var s = new DeflateState();
7256
7257  strm.state = s;
7258  s.strm = strm;
7259
7260  s.wrap = wrap;
7261  s.gzhead = null;
7262  s.w_bits = windowBits;
7263  s.w_size = 1 << s.w_bits;
7264  s.w_mask = s.w_size - 1;
7265
7266  s.hash_bits = memLevel + 7;
7267  s.hash_size = 1 << s.hash_bits;
7268  s.hash_mask = s.hash_size - 1;
7269  s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
7270
7271  s.window = new utils.Buf8(s.w_size * 2);
7272  s.head = new utils.Buf16(s.hash_size);
7273  s.prev = new utils.Buf16(s.w_size);
7274
7275  // Don't need mem init magic for JS.
7276  //s.high_water = 0;  /* nothing written to s->window yet */
7277
7278  s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
7279
7280  s.pending_buf_size = s.lit_bufsize * 4;
7281
7282  //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
7283  //s->pending_buf = (uchf *) overlay;
7284  s.pending_buf = new utils.Buf8(s.pending_buf_size);
7285
7286  // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
7287  //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
7288  s.d_buf = 1 * s.lit_bufsize;
7289
7290  //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
7291  s.l_buf = (1 + 2) * s.lit_bufsize;
7292
7293  s.level = level;
7294  s.strategy = strategy;
7295  s.method = method;
7296
7297  return deflateReset(strm);
7298}
7299
7300function deflateInit(strm, level) {
7301  return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
7302}
7303
7304
7305function deflate(strm, flush) {
7306  var old_flush, s;
7307  var beg, val; // for gzip header write only
7308
7309  if (!strm || !strm.state ||
7310    flush > Z_BLOCK || flush < 0) {
7311    return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
7312  }
7313
7314  s = strm.state;
7315
7316  if (!strm.output ||
7317      (!strm.input && strm.avail_in !== 0) ||
7318      (s.status === FINISH_STATE && flush !== Z_FINISH)) {
7319    return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
7320  }
7321
7322  s.strm = strm; /* just in case */
7323  old_flush = s.last_flush;
7324  s.last_flush = flush;
7325
7326  /* Write the header */
7327  if (s.status === INIT_STATE) {
7328
7329    if (s.wrap === 2) { // GZIP header
7330      strm.adler = 0;  //crc32(0L, Z_NULL, 0);
7331      put_byte(s, 31);
7332      put_byte(s, 139);
7333      put_byte(s, 8);
7334      if (!s.gzhead) { // s->gzhead == Z_NULL
7335        put_byte(s, 0);
7336        put_byte(s, 0);
7337        put_byte(s, 0);
7338        put_byte(s, 0);
7339        put_byte(s, 0);
7340        put_byte(s, s.level === 9 ? 2 :
7341                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
7342                     4 : 0));
7343        put_byte(s, OS_CODE);
7344        s.status = BUSY_STATE;
7345      }
7346      else {
7347        put_byte(s, (s.gzhead.text ? 1 : 0) +
7348                    (s.gzhead.hcrc ? 2 : 0) +
7349                    (!s.gzhead.extra ? 0 : 4) +
7350                    (!s.gzhead.name ? 0 : 8) +
7351                    (!s.gzhead.comment ? 0 : 16)
7352                );
7353        put_byte(s, s.gzhead.time & 0xff);
7354        put_byte(s, (s.gzhead.time >> 8) & 0xff);
7355        put_byte(s, (s.gzhead.time >> 16) & 0xff);
7356        put_byte(s, (s.gzhead.time >> 24) & 0xff);
7357        put_byte(s, s.level === 9 ? 2 :
7358                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
7359                     4 : 0));
7360        put_byte(s, s.gzhead.os & 0xff);
7361        if (s.gzhead.extra && s.gzhead.extra.length) {
7362          put_byte(s, s.gzhead.extra.length & 0xff);
7363          put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
7364        }
7365        if (s.gzhead.hcrc) {
7366          strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
7367        }
7368        s.gzindex = 0;
7369        s.status = EXTRA_STATE;
7370      }
7371    }
7372    else // DEFLATE header
7373    {
7374      var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
7375      var level_flags = -1;
7376
7377      if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
7378        level_flags = 0;
7379      } else if (s.level < 6) {
7380        level_flags = 1;
7381      } else if (s.level === 6) {
7382        level_flags = 2;
7383      } else {
7384        level_flags = 3;
7385      }
7386      header |= (level_flags << 6);
7387      if (s.strstart !== 0) { header |= PRESET_DICT; }
7388      header += 31 - (header % 31);
7389
7390      s.status = BUSY_STATE;
7391      putShortMSB(s, header);
7392
7393      /* Save the adler32 of the preset dictionary: */
7394      if (s.strstart !== 0) {
7395        putShortMSB(s, strm.adler >>> 16);
7396        putShortMSB(s, strm.adler & 0xffff);
7397      }
7398      strm.adler = 1; // adler32(0L, Z_NULL, 0);
7399    }
7400  }
7401
7402//#ifdef GZIP
7403  if (s.status === EXTRA_STATE) {
7404    if (s.gzhead.extra/* != Z_NULL*/) {
7405      beg = s.pending;  /* start of bytes to update crc */
7406
7407      while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
7408        if (s.pending === s.pending_buf_size) {
7409          if (s.gzhead.hcrc && s.pending > beg) {
7410            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7411          }
7412          flush_pending(strm);
7413          beg = s.pending;
7414          if (s.pending === s.pending_buf_size) {
7415            break;
7416          }
7417        }
7418        put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
7419        s.gzindex++;
7420      }
7421      if (s.gzhead.hcrc && s.pending > beg) {
7422        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7423      }
7424      if (s.gzindex === s.gzhead.extra.length) {
7425        s.gzindex = 0;
7426        s.status = NAME_STATE;
7427      }
7428    }
7429    else {
7430      s.status = NAME_STATE;
7431    }
7432  }
7433  if (s.status === NAME_STATE) {
7434    if (s.gzhead.name/* != Z_NULL*/) {
7435      beg = s.pending;  /* start of bytes to update crc */
7436      //int val;
7437
7438      do {
7439        if (s.pending === s.pending_buf_size) {
7440          if (s.gzhead.hcrc && s.pending > beg) {
7441            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7442          }
7443          flush_pending(strm);
7444          beg = s.pending;
7445          if (s.pending === s.pending_buf_size) {
7446            val = 1;
7447            break;
7448          }
7449        }
7450        // JS specific: little magic to add zero terminator to end of string
7451        if (s.gzindex < s.gzhead.name.length) {
7452          val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
7453        } else {
7454          val = 0;
7455        }
7456        put_byte(s, val);
7457      } while (val !== 0);
7458
7459      if (s.gzhead.hcrc && s.pending > beg) {
7460        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7461      }
7462      if (val === 0) {
7463        s.gzindex = 0;
7464        s.status = COMMENT_STATE;
7465      }
7466    }
7467    else {
7468      s.status = COMMENT_STATE;
7469    }
7470  }
7471  if (s.status === COMMENT_STATE) {
7472    if (s.gzhead.comment/* != Z_NULL*/) {
7473      beg = s.pending;  /* start of bytes to update crc */
7474      //int val;
7475
7476      do {
7477        if (s.pending === s.pending_buf_size) {
7478          if (s.gzhead.hcrc && s.pending > beg) {
7479            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7480          }
7481          flush_pending(strm);
7482          beg = s.pending;
7483          if (s.pending === s.pending_buf_size) {
7484            val = 1;
7485            break;
7486          }
7487        }
7488        // JS specific: little magic to add zero terminator to end of string
7489        if (s.gzindex < s.gzhead.comment.length) {
7490          val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
7491        } else {
7492          val = 0;
7493        }
7494        put_byte(s, val);
7495      } while (val !== 0);
7496
7497      if (s.gzhead.hcrc && s.pending > beg) {
7498        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7499      }
7500      if (val === 0) {
7501        s.status = HCRC_STATE;
7502      }
7503    }
7504    else {
7505      s.status = HCRC_STATE;
7506    }
7507  }
7508  if (s.status === HCRC_STATE) {
7509    if (s.gzhead.hcrc) {
7510      if (s.pending + 2 > s.pending_buf_size) {
7511        flush_pending(strm);
7512      }
7513      if (s.pending + 2 <= s.pending_buf_size) {
7514        put_byte(s, strm.adler & 0xff);
7515        put_byte(s, (strm.adler >> 8) & 0xff);
7516        strm.adler = 0; //crc32(0L, Z_NULL, 0);
7517        s.status = BUSY_STATE;
7518      }
7519    }
7520    else {
7521      s.status = BUSY_STATE;
7522    }
7523  }
7524//#endif
7525
7526  /* Flush as much pending output as possible */
7527  if (s.pending !== 0) {
7528    flush_pending(strm);
7529    if (strm.avail_out === 0) {
7530      /* Since avail_out is 0, deflate will be called again with
7531       * more output space, but possibly with both pending and
7532       * avail_in equal to zero. There won't be anything to do,
7533       * but this is not an error situation so make sure we
7534       * return OK instead of BUF_ERROR at next call of deflate:
7535       */
7536      s.last_flush = -1;
7537      return Z_OK;
7538    }
7539
7540    /* Make sure there is something to do and avoid duplicate consecutive
7541     * flushes. For repeated and useless calls with Z_FINISH, we keep
7542     * returning Z_STREAM_END instead of Z_BUF_ERROR.
7543     */
7544  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
7545    flush !== Z_FINISH) {
7546    return err(strm, Z_BUF_ERROR);
7547  }
7548
7549  /* User must not provide more input after the first FINISH: */
7550  if (s.status === FINISH_STATE && strm.avail_in !== 0) {
7551    return err(strm, Z_BUF_ERROR);
7552  }
7553
7554  /* Start a new block or continue the current one.
7555   */
7556  if (strm.avail_in !== 0 || s.lookahead !== 0 ||
7557    (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
7558    var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
7559      (s.strategy === Z_RLE ? deflate_rle(s, flush) :
7560        configuration_table[s.level].func(s, flush));
7561
7562    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
7563      s.status = FINISH_STATE;
7564    }
7565    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
7566      if (strm.avail_out === 0) {
7567        s.last_flush = -1;
7568        /* avoid BUF_ERROR next call, see above */
7569      }
7570      return Z_OK;
7571      /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
7572       * of deflate should use the same flush parameter to make sure
7573       * that the flush is complete. So we don't have to output an
7574       * empty block here, this will be done at next call. This also
7575       * ensures that for a very small output buffer, we emit at most
7576       * one empty block.
7577       */
7578    }
7579    if (bstate === BS_BLOCK_DONE) {
7580      if (flush === Z_PARTIAL_FLUSH) {
7581        trees._tr_align(s);
7582      }
7583      else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
7584
7585        trees._tr_stored_block(s, 0, 0, false);
7586        /* For a full flush, this empty block will be recognized
7587         * as a special marker by inflate_sync().
7588         */
7589        if (flush === Z_FULL_FLUSH) {
7590          /*** CLEAR_HASH(s); ***/             /* forget history */
7591          zero(s.head); // Fill with NIL (= 0);
7592
7593          if (s.lookahead === 0) {
7594            s.strstart = 0;
7595            s.block_start = 0;
7596            s.insert = 0;
7597          }
7598        }
7599      }
7600      flush_pending(strm);
7601      if (strm.avail_out === 0) {
7602        s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
7603        return Z_OK;
7604      }
7605    }
7606  }
7607  //Assert(strm->avail_out > 0, "bug2");
7608  //if (strm.avail_out <= 0) { throw new Error("bug2");}
7609
7610  if (flush !== Z_FINISH) { return Z_OK; }
7611  if (s.wrap <= 0) { return Z_STREAM_END; }
7612
7613  /* Write the trailer */
7614  if (s.wrap === 2) {
7615    put_byte(s, strm.adler & 0xff);
7616    put_byte(s, (strm.adler >> 8) & 0xff);
7617    put_byte(s, (strm.adler >> 16) & 0xff);
7618    put_byte(s, (strm.adler >> 24) & 0xff);
7619    put_byte(s, strm.total_in & 0xff);
7620    put_byte(s, (strm.total_in >> 8) & 0xff);
7621    put_byte(s, (strm.total_in >> 16) & 0xff);
7622    put_byte(s, (strm.total_in >> 24) & 0xff);
7623  }
7624  else
7625  {
7626    putShortMSB(s, strm.adler >>> 16);
7627    putShortMSB(s, strm.adler & 0xffff);
7628  }
7629
7630  flush_pending(strm);
7631  /* If avail_out is zero, the application will call deflate again
7632   * to flush the rest.
7633   */
7634  if (s.wrap > 0) { s.wrap = -s.wrap; }
7635  /* write the trailer only once! */
7636  return s.pending !== 0 ? Z_OK : Z_STREAM_END;
7637}
7638
7639function deflateEnd(strm) {
7640  var status;
7641
7642  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
7643    return Z_STREAM_ERROR;
7644  }
7645
7646  status = strm.state.status;
7647  if (status !== INIT_STATE &&
7648    status !== EXTRA_STATE &&
7649    status !== NAME_STATE &&
7650    status !== COMMENT_STATE &&
7651    status !== HCRC_STATE &&
7652    status !== BUSY_STATE &&
7653    status !== FINISH_STATE
7654  ) {
7655    return err(strm, Z_STREAM_ERROR);
7656  }
7657
7658  strm.state = null;
7659
7660  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
7661}
7662
7663
7664/* =========================================================================
7665 * Initializes the compression dictionary from the given byte
7666 * sequence without producing any compressed output.
7667 */
7668function deflateSetDictionary(strm, dictionary) {
7669  var dictLength = dictionary.length;
7670
7671  var s;
7672  var str, n;
7673  var wrap;
7674  var avail;
7675  var next;
7676  var input;
7677  var tmpDict;
7678
7679  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
7680    return Z_STREAM_ERROR;
7681  }
7682
7683  s = strm.state;
7684  wrap = s.wrap;
7685
7686  if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
7687    return Z_STREAM_ERROR;
7688  }
7689
7690  /* when using zlib wrappers, compute Adler-32 for provided dictionary */
7691  if (wrap === 1) {
7692    /* adler32(strm->adler, dictionary, dictLength); */
7693    strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
7694  }
7695
7696  s.wrap = 0;   /* avoid computing Adler-32 in read_buf */
7697
7698  /* if dictionary would fill window, just replace the history */
7699  if (dictLength >= s.w_size) {
7700    if (wrap === 0) {            /* already empty otherwise */
7701      /*** CLEAR_HASH(s); ***/
7702      zero(s.head); // Fill with NIL (= 0);
7703      s.strstart = 0;
7704      s.block_start = 0;
7705      s.insert = 0;
7706    }
7707    /* use the tail */
7708    // dictionary = dictionary.slice(dictLength - s.w_size);
7709    tmpDict = new utils.Buf8(s.w_size);
7710    utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
7711    dictionary = tmpDict;
7712    dictLength = s.w_size;
7713  }
7714  /* insert dictionary into window and hash */
7715  avail = strm.avail_in;
7716  next = strm.next_in;
7717  input = strm.input;
7718  strm.avail_in = dictLength;
7719  strm.next_in = 0;
7720  strm.input = dictionary;
7721  fill_window(s);
7722  while (s.lookahead >= MIN_MATCH) {
7723    str = s.strstart;
7724    n = s.lookahead - (MIN_MATCH - 1);
7725    do {
7726      /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
7727      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
7728
7729      s.prev[str & s.w_mask] = s.head[s.ins_h];
7730
7731      s.head[s.ins_h] = str;
7732      str++;
7733    } while (--n);
7734    s.strstart = str;
7735    s.lookahead = MIN_MATCH - 1;
7736    fill_window(s);
7737  }
7738  s.strstart += s.lookahead;
7739  s.block_start = s.strstart;
7740  s.insert = s.lookahead;
7741  s.lookahead = 0;
7742  s.match_length = s.prev_length = MIN_MATCH - 1;
7743  s.match_available = 0;
7744  strm.next_in = next;
7745  strm.input = input;
7746  strm.avail_in = avail;
7747  s.wrap = wrap;
7748  return Z_OK;
7749}
7750
7751
7752exports.deflateInit = deflateInit;
7753exports.deflateInit2 = deflateInit2;
7754exports.deflateReset = deflateReset;
7755exports.deflateResetKeep = deflateResetKeep;
7756exports.deflateSetHeader = deflateSetHeader;
7757exports.deflate = deflate;
7758exports.deflateEnd = deflateEnd;
7759exports.deflateSetDictionary = deflateSetDictionary;
7760exports.deflateInfo = 'pako deflate (from Nodeca project)';
7761
7762/* Not implemented
7763exports.deflateBound = deflateBound;
7764exports.deflateCopy = deflateCopy;
7765exports.deflateParams = deflateParams;
7766exports.deflatePending = deflatePending;
7767exports.deflatePrime = deflatePrime;
7768exports.deflateTune = deflateTune;
7769*/
7770
7771},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(require,module,exports){
7772'use strict';
7773
7774// (C) 1995-2013 Jean-loup Gailly and Mark Adler
7775// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
7776//
7777// This software is provided 'as-is', without any express or implied
7778// warranty. In no event will the authors be held liable for any damages
7779// arising from the use of this software.
7780//
7781// Permission is granted to anyone to use this software for any purpose,
7782// including commercial applications, and to alter it and redistribute it
7783// freely, subject to the following restrictions:
7784//
7785// 1. The origin of this software must not be misrepresented; you must not
7786//   claim that you wrote the original software. If you use this software
7787//   in a product, an acknowledgment in the product documentation would be
7788//   appreciated but is not required.
7789// 2. Altered source versions must be plainly marked as such, and must not be
7790//   misrepresented as being the original software.
7791// 3. This notice may not be removed or altered from any source distribution.
7792
7793function GZheader() {
7794  /* true if compressed data believed to be text */
7795  this.text       = 0;
7796  /* modification time */
7797  this.time       = 0;
7798  /* extra flags (not used when writing a gzip file) */
7799  this.xflags     = 0;
7800  /* operating system */
7801  this.os         = 0;
7802  /* pointer to extra field or Z_NULL if none */
7803  this.extra      = null;
7804  /* extra field length (valid if extra != Z_NULL) */
7805  this.extra_len  = 0; // Actually, we don't need it in JS,
7806                       // but leave for few code modifications
7807
7808  //
7809  // Setup limits is not necessary because in js we should not preallocate memory
7810  // for inflate use constant limit in 65536 bytes
7811  //
7812
7813  /* space at extra (only when reading header) */
7814  // this.extra_max  = 0;
7815  /* pointer to zero-terminated file name or Z_NULL */
7816  this.name       = '';
7817  /* space at name (only when reading header) */
7818  // this.name_max   = 0;
7819  /* pointer to zero-terminated comment or Z_NULL */
7820  this.comment    = '';
7821  /* space at comment (only when reading header) */
7822  // this.comm_max   = 0;
7823  /* true if there was or will be a header crc */
7824  this.hcrc       = 0;
7825  /* true when done reading gzip header (not used when writing a gzip file) */
7826  this.done       = false;
7827}
7828
7829module.exports = GZheader;
7830
7831},{}],48:[function(require,module,exports){
7832'use strict';
7833
7834// (C) 1995-2013 Jean-loup Gailly and Mark Adler
7835// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
7836//
7837// This software is provided 'as-is', without any express or implied
7838// warranty. In no event will the authors be held liable for any damages
7839// arising from the use of this software.
7840//
7841// Permission is granted to anyone to use this software for any purpose,
7842// including commercial applications, and to alter it and redistribute it
7843// freely, subject to the following restrictions:
7844//
7845// 1. The origin of this software must not be misrepresented; you must not
7846//   claim that you wrote the original software. If you use this software
7847//   in a product, an acknowledgment in the product documentation would be
7848//   appreciated but is not required.
7849// 2. Altered source versions must be plainly marked as such, and must not be
7850//   misrepresented as being the original software.
7851// 3. This notice may not be removed or altered from any source distribution.
7852
7853// See state defs from inflate.js
7854var BAD = 30;       /* got a data error -- remain here until reset */
7855var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
7856
7857/*
7858   Decode literal, length, and distance codes and write out the resulting
7859   literal and match bytes until either not enough input or output is
7860   available, an end-of-block is encountered, or a data error is encountered.
7861   When large enough input and output buffers are supplied to inflate(), for
7862   example, a 16K input buffer and a 64K output buffer, more than 95% of the
7863   inflate execution time is spent in this routine.
7864
7865   Entry assumptions:
7866
7867        state.mode === LEN
7868        strm.avail_in >= 6
7869        strm.avail_out >= 258
7870        start >= strm.avail_out
7871        state.bits < 8
7872
7873   On return, state.mode is one of:
7874
7875        LEN -- ran out of enough output space or enough available input
7876        TYPE -- reached end of block code, inflate() to interpret next block
7877        BAD -- error in block data
7878
7879   Notes:
7880
7881    - The maximum input bits used by a length/distance pair is 15 bits for the
7882      length code, 5 bits for the length extra, 15 bits for the distance code,
7883      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
7884      Therefore if strm.avail_in >= 6, then there is enough input to avoid
7885      checking for available input while decoding.
7886
7887    - The maximum bytes that a single length/distance pair can output is 258
7888      bytes, which is the maximum length that can be coded.  inflate_fast()
7889      requires strm.avail_out >= 258 for each loop to avoid checking for
7890      output space.
7891 */
7892module.exports = function inflate_fast(strm, start) {
7893  var state;
7894  var _in;                    /* local strm.input */
7895  var last;                   /* have enough input while in < last */
7896  var _out;                   /* local strm.output */
7897  var beg;                    /* inflate()'s initial strm.output */
7898  var end;                    /* while out < end, enough space available */
7899//#ifdef INFLATE_STRICT
7900  var dmax;                   /* maximum distance from zlib header */
7901//#endif
7902  var wsize;                  /* window size or zero if not using window */
7903  var whave;                  /* valid bytes in the window */
7904  var wnext;                  /* window write index */
7905  // Use `s_window` instead `window`, avoid conflict with instrumentation tools
7906  var s_window;               /* allocated sliding window, if wsize != 0 */
7907  var hold;                   /* local strm.hold */
7908  var bits;                   /* local strm.bits */
7909  var lcode;                  /* local strm.lencode */
7910  var dcode;                  /* local strm.distcode */
7911  var lmask;                  /* mask for first level of length codes */
7912  var dmask;                  /* mask for first level of distance codes */
7913  var here;                   /* retrieved table entry */
7914  var op;                     /* code bits, operation, extra bits, or */
7915                              /*  window position, window bytes to copy */
7916  var len;                    /* match length, unused bytes */
7917  var dist;                   /* match distance */
7918  var from;                   /* where to copy match from */
7919  var from_source;
7920
7921
7922  var input, output; // JS specific, because we have no pointers
7923
7924  /* copy state to local variables */
7925  state = strm.state;
7926  //here = state.here;
7927  _in = strm.next_in;
7928  input = strm.input;
7929  last = _in + (strm.avail_in - 5);
7930  _out = strm.next_out;
7931  output = strm.output;
7932  beg = _out - (start - strm.avail_out);
7933  end = _out + (strm.avail_out - 257);
7934//#ifdef INFLATE_STRICT
7935  dmax = state.dmax;
7936//#endif
7937  wsize = state.wsize;
7938  whave = state.whave;
7939  wnext = state.wnext;
7940  s_window = state.window;
7941  hold = state.hold;
7942  bits = state.bits;
7943  lcode = state.lencode;
7944  dcode = state.distcode;
7945  lmask = (1 << state.lenbits) - 1;
7946  dmask = (1 << state.distbits) - 1;
7947
7948
7949  /* decode literals and length/distances until end-of-block or not enough
7950     input data or output space */
7951
7952  top:
7953  do {
7954    if (bits < 15) {
7955      hold += input[_in++] << bits;
7956      bits += 8;
7957      hold += input[_in++] << bits;
7958      bits += 8;
7959    }
7960
7961    here = lcode[hold & lmask];
7962
7963    dolen:
7964    for (;;) { // Goto emulation
7965      op = here >>> 24/*here.bits*/;
7966      hold >>>= op;
7967      bits -= op;
7968      op = (here >>> 16) & 0xff/*here.op*/;
7969      if (op === 0) {                          /* literal */
7970        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
7971        //        "inflate:         literal '%c'\n" :
7972        //        "inflate:         literal 0x%02x\n", here.val));
7973        output[_out++] = here & 0xffff/*here.val*/;
7974      }
7975      else if (op & 16) {                     /* length base */
7976        len = here & 0xffff/*here.val*/;
7977        op &= 15;                           /* number of extra bits */
7978        if (op) {
7979          if (bits < op) {
7980            hold += input[_in++] << bits;
7981            bits += 8;
7982          }
7983          len += hold & ((1 << op) - 1);
7984          hold >>>= op;
7985          bits -= op;
7986        }
7987        //Tracevv((stderr, "inflate:         length %u\n", len));
7988        if (bits < 15) {
7989          hold += input[_in++] << bits;
7990          bits += 8;
7991          hold += input[_in++] << bits;
7992          bits += 8;
7993        }
7994        here = dcode[hold & dmask];
7995
7996        dodist:
7997        for (;;) { // goto emulation
7998          op = here >>> 24/*here.bits*/;
7999          hold >>>= op;
8000          bits -= op;
8001          op = (here >>> 16) & 0xff/*here.op*/;
8002
8003          if (op & 16) {                      /* distance base */
8004            dist = here & 0xffff/*here.val*/;
8005            op &= 15;                       /* number of extra bits */
8006            if (bits < op) {
8007              hold += input[_in++] << bits;
8008              bits += 8;
8009              if (bits < op) {
8010                hold += input[_in++] << bits;
8011                bits += 8;
8012              }
8013            }
8014            dist += hold & ((1 << op) - 1);
8015//#ifdef INFLATE_STRICT
8016            if (dist > dmax) {
8017              strm.msg = 'invalid distance too far back';
8018              state.mode = BAD;
8019              break top;
8020            }
8021//#endif
8022            hold >>>= op;
8023            bits -= op;
8024            //Tracevv((stderr, "inflate:         distance %u\n", dist));
8025            op = _out - beg;                /* max distance in output */
8026            if (dist > op) {                /* see if copy from window */
8027              op = dist - op;               /* distance back in window */
8028              if (op > whave) {
8029                if (state.sane) {
8030                  strm.msg = 'invalid distance too far back';
8031                  state.mode = BAD;
8032                  break top;
8033                }
8034
8035// (!) This block is disabled in zlib defailts,
8036// don't enable it for binary compatibility
8037//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
8038//                if (len <= op - whave) {
8039//                  do {
8040//                    output[_out++] = 0;
8041//                  } while (--len);
8042//                  continue top;
8043//                }
8044//                len -= op - whave;
8045//                do {
8046//                  output[_out++] = 0;
8047//                } while (--op > whave);
8048//                if (op === 0) {
8049//                  from = _out - dist;
8050//                  do {
8051//                    output[_out++] = output[from++];
8052//                  } while (--len);
8053//                  continue top;
8054//                }
8055//#endif
8056              }
8057              from = 0; // window index
8058              from_source = s_window;
8059              if (wnext === 0) {           /* very common case */
8060                from += wsize - op;
8061                if (op < len) {         /* some from window */
8062                  len -= op;
8063                  do {
8064                    output[_out++] = s_window[from++];
8065                  } while (--op);
8066                  from = _out - dist;  /* rest from output */
8067                  from_source = output;
8068                }
8069              }
8070              else if (wnext < op) {      /* wrap around window */
8071                from += wsize + wnext - op;
8072                op -= wnext;
8073                if (op < len) {         /* some from end of window */
8074                  len -= op;
8075                  do {
8076                    output[_out++] = s_window[from++];
8077                  } while (--op);
8078                  from = 0;
8079                  if (wnext < len) {  /* some from start of window */
8080                    op = wnext;
8081                    len -= op;
8082                    do {
8083                      output[_out++] = s_window[from++];
8084                    } while (--op);
8085                    from = _out - dist;      /* rest from output */
8086                    from_source = output;
8087                  }
8088                }
8089              }
8090              else {                      /* contiguous in window */
8091                from += wnext - op;
8092                if (op < len) {         /* some from window */
8093                  len -= op;
8094                  do {
8095                    output[_out++] = s_window[from++];
8096                  } while (--op);
8097                  from = _out - dist;  /* rest from output */
8098                  from_source = output;
8099                }
8100              }
8101              while (len > 2) {
8102                output[_out++] = from_source[from++];
8103                output[_out++] = from_source[from++];
8104                output[_out++] = from_source[from++];
8105                len -= 3;
8106              }
8107              if (len) {
8108                output[_out++] = from_source[from++];
8109                if (len > 1) {
8110                  output[_out++] = from_source[from++];
8111                }
8112              }
8113            }
8114            else {
8115              from = _out - dist;          /* copy direct from output */
8116              do {                        /* minimum length is three */
8117                output[_out++] = output[from++];
8118                output[_out++] = output[from++];
8119                output[_out++] = output[from++];
8120                len -= 3;
8121              } while (len > 2);
8122              if (len) {
8123                output[_out++] = output[from++];
8124                if (len > 1) {
8125                  output[_out++] = output[from++];
8126                }
8127              }
8128            }
8129          }
8130          else if ((op & 64) === 0) {          /* 2nd level distance code */
8131            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
8132            continue dodist;
8133          }
8134          else {
8135            strm.msg = 'invalid distance code';
8136            state.mode = BAD;
8137            break top;
8138          }
8139
8140          break; // need to emulate goto via "continue"
8141        }
8142      }
8143      else if ((op & 64) === 0) {              /* 2nd level length code */
8144        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
8145        continue dolen;
8146      }
8147      else if (op & 32) {                     /* end-of-block */
8148        //Tracevv((stderr, "inflate:         end of block\n"));
8149        state.mode = TYPE;
8150        break top;
8151      }
8152      else {
8153        strm.msg = 'invalid literal/length code';
8154        state.mode = BAD;
8155        break top;
8156      }
8157
8158      break; // need to emulate goto via "continue"
8159    }
8160  } while (_in < last && _out < end);
8161
8162  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
8163  len = bits >> 3;
8164  _in -= len;
8165  bits -= len << 3;
8166  hold &= (1 << bits) - 1;
8167
8168  /* update state and return */
8169  strm.next_in = _in;
8170  strm.next_out = _out;
8171  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
8172  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
8173  state.hold = hold;
8174  state.bits = bits;
8175  return;
8176};
8177
8178},{}],49:[function(require,module,exports){
8179'use strict';
8180
8181// (C) 1995-2013 Jean-loup Gailly and Mark Adler
8182// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
8183//
8184// This software is provided 'as-is', without any express or implied
8185// warranty. In no event will the authors be held liable for any damages
8186// arising from the use of this software.
8187//
8188// Permission is granted to anyone to use this software for any purpose,
8189// including commercial applications, and to alter it and redistribute it
8190// freely, subject to the following restrictions:
8191//
8192// 1. The origin of this software must not be misrepresented; you must not
8193//   claim that you wrote the original software. If you use this software
8194//   in a product, an acknowledgment in the product documentation would be
8195//   appreciated but is not required.
8196// 2. Altered source versions must be plainly marked as such, and must not be
8197//   misrepresented as being the original software.
8198// 3. This notice may not be removed or altered from any source distribution.
8199
8200var utils         = require('../utils/common');
8201var adler32       = require('./adler32');
8202var crc32         = require('./crc32');
8203var inflate_fast  = require('./inffast');
8204var inflate_table = require('./inftrees');
8205
8206var CODES = 0;
8207var LENS = 1;
8208var DISTS = 2;
8209
8210/* Public constants ==========================================================*/
8211/* ===========================================================================*/
8212
8213
8214/* Allowed flush values; see deflate() and inflate() below for details */
8215//var Z_NO_FLUSH      = 0;
8216//var Z_PARTIAL_FLUSH = 1;
8217//var Z_SYNC_FLUSH    = 2;
8218//var Z_FULL_FLUSH    = 3;
8219var Z_FINISH        = 4;
8220var Z_BLOCK         = 5;
8221var Z_TREES         = 6;
8222
8223
8224/* Return codes for the compression/decompression functions. Negative values
8225 * are errors, positive values are used for special but normal events.
8226 */
8227var Z_OK            = 0;
8228var Z_STREAM_END    = 1;
8229var Z_NEED_DICT     = 2;
8230//var Z_ERRNO         = -1;
8231var Z_STREAM_ERROR  = -2;
8232var Z_DATA_ERROR    = -3;
8233var Z_MEM_ERROR     = -4;
8234var Z_BUF_ERROR     = -5;
8235//var Z_VERSION_ERROR = -6;
8236
8237/* The deflate compression method */
8238var Z_DEFLATED  = 8;
8239
8240
8241/* STATES ====================================================================*/
8242/* ===========================================================================*/
8243
8244
8245var    HEAD = 1;       /* i: waiting for magic header */
8246var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
8247var    TIME = 3;       /* i: waiting for modification time (gzip) */
8248var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
8249var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
8250var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
8251var    NAME = 7;       /* i: waiting for end of file name (gzip) */
8252var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
8253var    HCRC = 9;       /* i: waiting for header crc (gzip) */
8254var    DICTID = 10;    /* i: waiting for dictionary check value */
8255var    DICT = 11;      /* waiting for inflateSetDictionary() call */
8256var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
8257var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
8258var        STORED = 14;    /* i: waiting for stored size (length and complement) */
8259var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
8260var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
8261var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
8262var        LENLENS = 18;   /* i: waiting for code length code lengths */
8263var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
8264var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
8265var            LEN = 21;       /* i: waiting for length/lit/eob code */
8266var            LENEXT = 22;    /* i: waiting for length extra bits */
8267var            DIST = 23;      /* i: waiting for distance code */
8268var            DISTEXT = 24;   /* i: waiting for distance extra bits */
8269var            MATCH = 25;     /* o: waiting for output space to copy string */
8270var            LIT = 26;       /* o: waiting for output space to write literal */
8271var    CHECK = 27;     /* i: waiting for 32-bit check value */
8272var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
8273var    DONE = 29;      /* finished check, done -- remain here until reset */
8274var    BAD = 30;       /* got a data error -- remain here until reset */
8275var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
8276var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
8277
8278/* ===========================================================================*/
8279
8280
8281
8282var ENOUGH_LENS = 852;
8283var ENOUGH_DISTS = 592;
8284//var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
8285
8286var MAX_WBITS = 15;
8287/* 32K LZ77 window */
8288var DEF_WBITS = MAX_WBITS;
8289
8290
8291function zswap32(q) {
8292  return  (((q >>> 24) & 0xff) +
8293          ((q >>> 8) & 0xff00) +
8294          ((q & 0xff00) << 8) +
8295          ((q & 0xff) << 24));
8296}
8297
8298
8299function InflateState() {
8300  this.mode = 0;             /* current inflate mode */
8301  this.last = false;          /* true if processing last block */
8302  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
8303  this.havedict = false;      /* true if dictionary provided */
8304  this.flags = 0;             /* gzip header method and flags (0 if zlib) */
8305  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
8306  this.check = 0;             /* protected copy of check value */
8307  this.total = 0;             /* protected copy of output count */
8308  // TODO: may be {}
8309  this.head = null;           /* where to save gzip header information */
8310
8311  /* sliding window */
8312  this.wbits = 0;             /* log base 2 of requested window size */
8313  this.wsize = 0;             /* window size or zero if not using window */
8314  this.whave = 0;             /* valid bytes in the window */
8315  this.wnext = 0;             /* window write index */
8316  this.window = null;         /* allocated sliding window, if needed */
8317
8318  /* bit accumulator */
8319  this.hold = 0;              /* input bit accumulator */
8320  this.bits = 0;              /* number of bits in "in" */
8321
8322  /* for string and stored block copying */
8323  this.length = 0;            /* literal or length of data to copy */
8324  this.offset = 0;            /* distance back to copy string from */
8325
8326  /* for table and code decoding */
8327  this.extra = 0;             /* extra bits needed */
8328
8329  /* fixed and dynamic code tables */
8330  this.lencode = null;          /* starting table for length/literal codes */
8331  this.distcode = null;         /* starting table for distance codes */
8332  this.lenbits = 0;           /* index bits for lencode */
8333  this.distbits = 0;          /* index bits for distcode */
8334
8335  /* dynamic table building */
8336  this.ncode = 0;             /* number of code length code lengths */
8337  this.nlen = 0;              /* number of length code lengths */
8338  this.ndist = 0;             /* number of distance code lengths */
8339  this.have = 0;              /* number of code lengths in lens[] */
8340  this.next = null;              /* next available space in codes[] */
8341
8342  this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
8343  this.work = new utils.Buf16(288); /* work area for code table building */
8344
8345  /*
8346   because we don't have pointers in js, we use lencode and distcode directly
8347   as buffers so we don't need codes
8348  */
8349  //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
8350  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
8351  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
8352  this.sane = 0;                   /* if false, allow invalid distance too far */
8353  this.back = 0;                   /* bits back of last unprocessed length/lit */
8354  this.was = 0;                    /* initial length of match */
8355}
8356
8357function inflateResetKeep(strm) {
8358  var state;
8359
8360  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8361  state = strm.state;
8362  strm.total_in = strm.total_out = state.total = 0;
8363  strm.msg = ''; /*Z_NULL*/
8364  if (state.wrap) {       /* to support ill-conceived Java test suite */
8365    strm.adler = state.wrap & 1;
8366  }
8367  state.mode = HEAD;
8368  state.last = 0;
8369  state.havedict = 0;
8370  state.dmax = 32768;
8371  state.head = null/*Z_NULL*/;
8372  state.hold = 0;
8373  state.bits = 0;
8374  //state.lencode = state.distcode = state.next = state.codes;
8375  state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
8376  state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
8377
8378  state.sane = 1;
8379  state.back = -1;
8380  //Tracev((stderr, "inflate: reset\n"));
8381  return Z_OK;
8382}
8383
8384function inflateReset(strm) {
8385  var state;
8386
8387  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8388  state = strm.state;
8389  state.wsize = 0;
8390  state.whave = 0;
8391  state.wnext = 0;
8392  return inflateResetKeep(strm);
8393
8394}
8395
8396function inflateReset2(strm, windowBits) {
8397  var wrap;
8398  var state;
8399
8400  /* get the state */
8401  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8402  state = strm.state;
8403
8404  /* extract wrap request from windowBits parameter */
8405  if (windowBits < 0) {
8406    wrap = 0;
8407    windowBits = -windowBits;
8408  }
8409  else {
8410    wrap = (windowBits >> 4) + 1;
8411    if (windowBits < 48) {
8412      windowBits &= 15;
8413    }
8414  }
8415
8416  /* set number of window bits, free window if different */
8417  if (windowBits && (windowBits < 8 || windowBits > 15)) {
8418    return Z_STREAM_ERROR;
8419  }
8420  if (state.window !== null && state.wbits !== windowBits) {
8421    state.window = null;
8422  }
8423
8424  /* update state and reset the rest of it */
8425  state.wrap = wrap;
8426  state.wbits = windowBits;
8427  return inflateReset(strm);
8428}
8429
8430function inflateInit2(strm, windowBits) {
8431  var ret;
8432  var state;
8433
8434  if (!strm) { return Z_STREAM_ERROR; }
8435  //strm.msg = Z_NULL;                 /* in case we return an error */
8436
8437  state = new InflateState();
8438
8439  //if (state === Z_NULL) return Z_MEM_ERROR;
8440  //Tracev((stderr, "inflate: allocated\n"));
8441  strm.state = state;
8442  state.window = null/*Z_NULL*/;
8443  ret = inflateReset2(strm, windowBits);
8444  if (ret !== Z_OK) {
8445    strm.state = null/*Z_NULL*/;
8446  }
8447  return ret;
8448}
8449
8450function inflateInit(strm) {
8451  return inflateInit2(strm, DEF_WBITS);
8452}
8453
8454
8455/*
8456 Return state with length and distance decoding tables and index sizes set to
8457 fixed code decoding.  Normally this returns fixed tables from inffixed.h.
8458 If BUILDFIXED is defined, then instead this routine builds the tables the
8459 first time it's called, and returns those tables the first time and
8460 thereafter.  This reduces the size of the code by about 2K bytes, in
8461 exchange for a little execution time.  However, BUILDFIXED should not be
8462 used for threaded applications, since the rewriting of the tables and virgin
8463 may not be thread-safe.
8464 */
8465var virgin = true;
8466
8467var lenfix, distfix; // We have no pointers in JS, so keep tables separate
8468
8469function fixedtables(state) {
8470  /* build fixed huffman tables if first call (may not be thread safe) */
8471  if (virgin) {
8472    var sym;
8473
8474    lenfix = new utils.Buf32(512);
8475    distfix = new utils.Buf32(32);
8476
8477    /* literal/length table */
8478    sym = 0;
8479    while (sym < 144) { state.lens[sym++] = 8; }
8480    while (sym < 256) { state.lens[sym++] = 9; }
8481    while (sym < 280) { state.lens[sym++] = 7; }
8482    while (sym < 288) { state.lens[sym++] = 8; }
8483
8484    inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });
8485
8486    /* distance table */
8487    sym = 0;
8488    while (sym < 32) { state.lens[sym++] = 5; }
8489
8490    inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });
8491
8492    /* do this just once */
8493    virgin = false;
8494  }
8495
8496  state.lencode = lenfix;
8497  state.lenbits = 9;
8498  state.distcode = distfix;
8499  state.distbits = 5;
8500}
8501
8502
8503/*
8504 Update the window with the last wsize (normally 32K) bytes written before
8505 returning.  If window does not exist yet, create it.  This is only called
8506 when a window is already in use, or when output has been written during this
8507 inflate call, but the end of the deflate stream has not been reached yet.
8508 It is also called to create a window for dictionary data when a dictionary
8509 is loaded.
8510
8511 Providing output buffers larger than 32K to inflate() should provide a speed
8512 advantage, since only the last 32K of output is copied to the sliding window
8513 upon return from inflate(), and since all distances after the first 32K of
8514 output will fall in the output data, making match copies simpler and faster.
8515 The advantage may be dependent on the size of the processor's data caches.
8516 */
8517function updatewindow(strm, src, end, copy) {
8518  var dist;
8519  var state = strm.state;
8520
8521  /* if it hasn't been done already, allocate space for the window */
8522  if (state.window === null) {
8523    state.wsize = 1 << state.wbits;
8524    state.wnext = 0;
8525    state.whave = 0;
8526
8527    state.window = new utils.Buf8(state.wsize);
8528  }
8529
8530  /* copy state->wsize or less output bytes into the circular window */
8531  if (copy >= state.wsize) {
8532    utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
8533    state.wnext = 0;
8534    state.whave = state.wsize;
8535  }
8536  else {
8537    dist = state.wsize - state.wnext;
8538    if (dist > copy) {
8539      dist = copy;
8540    }
8541    //zmemcpy(state->window + state->wnext, end - copy, dist);
8542    utils.arraySet(state.window, src, end - copy, dist, state.wnext);
8543    copy -= dist;
8544    if (copy) {
8545      //zmemcpy(state->window, end - copy, copy);
8546      utils.arraySet(state.window, src, end - copy, copy, 0);
8547      state.wnext = copy;
8548      state.whave = state.wsize;
8549    }
8550    else {
8551      state.wnext += dist;
8552      if (state.wnext === state.wsize) { state.wnext = 0; }
8553      if (state.whave < state.wsize) { state.whave += dist; }
8554    }
8555  }
8556  return 0;
8557}
8558
8559function inflate(strm, flush) {
8560  var state;
8561  var input, output;          // input/output buffers
8562  var next;                   /* next input INDEX */
8563  var put;                    /* next output INDEX */
8564  var have, left;             /* available input and output */
8565  var hold;                   /* bit buffer */
8566  var bits;                   /* bits in bit buffer */
8567  var _in, _out;              /* save starting available input and output */
8568  var copy;                   /* number of stored or match bytes to copy */
8569  var from;                   /* where to copy match bytes from */
8570  var from_source;
8571  var here = 0;               /* current decoding table entry */
8572  var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
8573  //var last;                   /* parent table entry */
8574  var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
8575  var len;                    /* length to copy for repeats, bits to drop */
8576  var ret;                    /* return code */
8577  var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
8578  var opts;
8579
8580  var n; // temporary var for NEED_BITS
8581
8582  var order = /* permutation of code lengths */
8583    [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
8584
8585
8586  if (!strm || !strm.state || !strm.output ||
8587      (!strm.input && strm.avail_in !== 0)) {
8588    return Z_STREAM_ERROR;
8589  }
8590
8591  state = strm.state;
8592  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
8593
8594
8595  //--- LOAD() ---
8596  put = strm.next_out;
8597  output = strm.output;
8598  left = strm.avail_out;
8599  next = strm.next_in;
8600  input = strm.input;
8601  have = strm.avail_in;
8602  hold = state.hold;
8603  bits = state.bits;
8604  //---
8605
8606  _in = have;
8607  _out = left;
8608  ret = Z_OK;
8609
8610  inf_leave: // goto emulation
8611  for (;;) {
8612    switch (state.mode) {
8613    case HEAD:
8614      if (state.wrap === 0) {
8615        state.mode = TYPEDO;
8616        break;
8617      }
8618      //=== NEEDBITS(16);
8619      while (bits < 16) {
8620        if (have === 0) { break inf_leave; }
8621        have--;
8622        hold += input[next++] << bits;
8623        bits += 8;
8624      }
8625      //===//
8626      if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
8627        state.check = 0/*crc32(0L, Z_NULL, 0)*/;
8628        //=== CRC2(state.check, hold);
8629        hbuf[0] = hold & 0xff;
8630        hbuf[1] = (hold >>> 8) & 0xff;
8631        state.check = crc32(state.check, hbuf, 2, 0);
8632        //===//
8633
8634        //=== INITBITS();
8635        hold = 0;
8636        bits = 0;
8637        //===//
8638        state.mode = FLAGS;
8639        break;
8640      }
8641      state.flags = 0;           /* expect zlib header */
8642      if (state.head) {
8643        state.head.done = false;
8644      }
8645      if (!(state.wrap & 1) ||   /* check if zlib header allowed */
8646        (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
8647        strm.msg = 'incorrect header check';
8648        state.mode = BAD;
8649        break;
8650      }
8651      if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
8652        strm.msg = 'unknown compression method';
8653        state.mode = BAD;
8654        break;
8655      }
8656      //--- DROPBITS(4) ---//
8657      hold >>>= 4;
8658      bits -= 4;
8659      //---//
8660      len = (hold & 0x0f)/*BITS(4)*/ + 8;
8661      if (state.wbits === 0) {
8662        state.wbits = len;
8663      }
8664      else if (len > state.wbits) {
8665        strm.msg = 'invalid window size';
8666        state.mode = BAD;
8667        break;
8668      }
8669      state.dmax = 1 << len;
8670      //Tracev((stderr, "inflate:   zlib header ok\n"));
8671      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
8672      state.mode = hold & 0x200 ? DICTID : TYPE;
8673      //=== INITBITS();
8674      hold = 0;
8675      bits = 0;
8676      //===//
8677      break;
8678    case FLAGS:
8679      //=== NEEDBITS(16); */
8680      while (bits < 16) {
8681        if (have === 0) { break inf_leave; }
8682        have--;
8683        hold += input[next++] << bits;
8684        bits += 8;
8685      }
8686      //===//
8687      state.flags = hold;
8688      if ((state.flags & 0xff) !== Z_DEFLATED) {
8689        strm.msg = 'unknown compression method';
8690        state.mode = BAD;
8691        break;
8692      }
8693      if (state.flags & 0xe000) {
8694        strm.msg = 'unknown header flags set';
8695        state.mode = BAD;
8696        break;
8697      }
8698      if (state.head) {
8699        state.head.text = ((hold >> 8) & 1);
8700      }
8701      if (state.flags & 0x0200) {
8702        //=== CRC2(state.check, hold);
8703        hbuf[0] = hold & 0xff;
8704        hbuf[1] = (hold >>> 8) & 0xff;
8705        state.check = crc32(state.check, hbuf, 2, 0);
8706        //===//
8707      }
8708      //=== INITBITS();
8709      hold = 0;
8710      bits = 0;
8711      //===//
8712      state.mode = TIME;
8713      /* falls through */
8714    case TIME:
8715      //=== NEEDBITS(32); */
8716      while (bits < 32) {
8717        if (have === 0) { break inf_leave; }
8718        have--;
8719        hold += input[next++] << bits;
8720        bits += 8;
8721      }
8722      //===//
8723      if (state.head) {
8724        state.head.time = hold;
8725      }
8726      if (state.flags & 0x0200) {
8727        //=== CRC4(state.check, hold)
8728        hbuf[0] = hold & 0xff;
8729        hbuf[1] = (hold >>> 8) & 0xff;
8730        hbuf[2] = (hold >>> 16) & 0xff;
8731        hbuf[3] = (hold >>> 24) & 0xff;
8732        state.check = crc32(state.check, hbuf, 4, 0);
8733        //===
8734      }
8735      //=== INITBITS();
8736      hold = 0;
8737      bits = 0;
8738      //===//
8739      state.mode = OS;
8740      /* falls through */
8741    case OS:
8742      //=== NEEDBITS(16); */
8743      while (bits < 16) {
8744        if (have === 0) { break inf_leave; }
8745        have--;
8746        hold += input[next++] << bits;
8747        bits += 8;
8748      }
8749      //===//
8750      if (state.head) {
8751        state.head.xflags = (hold & 0xff);
8752        state.head.os = (hold >> 8);
8753      }
8754      if (state.flags & 0x0200) {
8755        //=== CRC2(state.check, hold);
8756        hbuf[0] = hold & 0xff;
8757        hbuf[1] = (hold >>> 8) & 0xff;
8758        state.check = crc32(state.check, hbuf, 2, 0);
8759        //===//
8760      }
8761      //=== INITBITS();
8762      hold = 0;
8763      bits = 0;
8764      //===//
8765      state.mode = EXLEN;
8766      /* falls through */
8767    case EXLEN:
8768      if (state.flags & 0x0400) {
8769        //=== NEEDBITS(16); */
8770        while (bits < 16) {
8771          if (have === 0) { break inf_leave; }
8772          have--;
8773          hold += input[next++] << bits;
8774          bits += 8;
8775        }
8776        //===//
8777        state.length = hold;
8778        if (state.head) {
8779          state.head.extra_len = hold;
8780        }
8781        if (state.flags & 0x0200) {
8782          //=== CRC2(state.check, hold);
8783          hbuf[0] = hold & 0xff;
8784          hbuf[1] = (hold >>> 8) & 0xff;
8785          state.check = crc32(state.check, hbuf, 2, 0);
8786          //===//
8787        }
8788        //=== INITBITS();
8789        hold = 0;
8790        bits = 0;
8791        //===//
8792      }
8793      else if (state.head) {
8794        state.head.extra = null/*Z_NULL*/;
8795      }
8796      state.mode = EXTRA;
8797      /* falls through */
8798    case EXTRA:
8799      if (state.flags & 0x0400) {
8800        copy = state.length;
8801        if (copy > have) { copy = have; }
8802        if (copy) {
8803          if (state.head) {
8804            len = state.head.extra_len - state.length;
8805            if (!state.head.extra) {
8806              // Use untyped array for more conveniend processing later
8807              state.head.extra = new Array(state.head.extra_len);
8808            }
8809            utils.arraySet(
8810              state.head.extra,
8811              input,
8812              next,
8813              // extra field is limited to 65536 bytes
8814              // - no need for additional size check
8815              copy,
8816              /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
8817              len
8818            );
8819            //zmemcpy(state.head.extra + len, next,
8820            //        len + copy > state.head.extra_max ?
8821            //        state.head.extra_max - len : copy);
8822          }
8823          if (state.flags & 0x0200) {
8824            state.check = crc32(state.check, input, copy, next);
8825          }
8826          have -= copy;
8827          next += copy;
8828          state.length -= copy;
8829        }
8830        if (state.length) { break inf_leave; }
8831      }
8832      state.length = 0;
8833      state.mode = NAME;
8834      /* falls through */
8835    case NAME:
8836      if (state.flags & 0x0800) {
8837        if (have === 0) { break inf_leave; }
8838        copy = 0;
8839        do {
8840          // TODO: 2 or 1 bytes?
8841          len = input[next + copy++];
8842          /* use constant limit because in js we should not preallocate memory */
8843          if (state.head && len &&
8844              (state.length < 65536 /*state.head.name_max*/)) {
8845            state.head.name += String.fromCharCode(len);
8846          }
8847        } while (len && copy < have);
8848
8849        if (state.flags & 0x0200) {
8850          state.check = crc32(state.check, input, copy, next);
8851        }
8852        have -= copy;
8853        next += copy;
8854        if (len) { break inf_leave; }
8855      }
8856      else if (state.head) {
8857        state.head.name = null;
8858      }
8859      state.length = 0;
8860      state.mode = COMMENT;
8861      /* falls through */
8862    case COMMENT:
8863      if (state.flags & 0x1000) {
8864        if (have === 0) { break inf_leave; }
8865        copy = 0;
8866        do {
8867          len = input[next + copy++];
8868          /* use constant limit because in js we should not preallocate memory */
8869          if (state.head && len &&
8870              (state.length < 65536 /*state.head.comm_max*/)) {
8871            state.head.comment += String.fromCharCode(len);
8872          }
8873        } while (len && copy < have);
8874        if (state.flags & 0x0200) {
8875          state.check = crc32(state.check, input, copy, next);
8876        }
8877        have -= copy;
8878        next += copy;
8879        if (len) { break inf_leave; }
8880      }
8881      else if (state.head) {
8882        state.head.comment = null;
8883      }
8884      state.mode = HCRC;
8885      /* falls through */
8886    case HCRC:
8887      if (state.flags & 0x0200) {
8888        //=== NEEDBITS(16); */
8889        while (bits < 16) {
8890          if (have === 0) { break inf_leave; }
8891          have--;
8892          hold += input[next++] << bits;
8893          bits += 8;
8894        }
8895        //===//
8896        if (hold !== (state.check & 0xffff)) {
8897          strm.msg = 'header crc mismatch';
8898          state.mode = BAD;
8899          break;
8900        }
8901        //=== INITBITS();
8902        hold = 0;
8903        bits = 0;
8904        //===//
8905      }
8906      if (state.head) {
8907        state.head.hcrc = ((state.flags >> 9) & 1);
8908        state.head.done = true;
8909      }
8910      strm.adler = state.check = 0;
8911      state.mode = TYPE;
8912      break;
8913    case DICTID:
8914      //=== NEEDBITS(32); */
8915      while (bits < 32) {
8916        if (have === 0) { break inf_leave; }
8917        have--;
8918        hold += input[next++] << bits;
8919        bits += 8;
8920      }
8921      //===//
8922      strm.adler = state.check = zswap32(hold);
8923      //=== INITBITS();
8924      hold = 0;
8925      bits = 0;
8926      //===//
8927      state.mode = DICT;
8928      /* falls through */
8929    case DICT:
8930      if (state.havedict === 0) {
8931        //--- RESTORE() ---
8932        strm.next_out = put;
8933        strm.avail_out = left;
8934        strm.next_in = next;
8935        strm.avail_in = have;
8936        state.hold = hold;
8937        state.bits = bits;
8938        //---
8939        return Z_NEED_DICT;
8940      }
8941      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
8942      state.mode = TYPE;
8943      /* falls through */
8944    case TYPE:
8945      if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
8946      /* falls through */
8947    case TYPEDO:
8948      if (state.last) {
8949        //--- BYTEBITS() ---//
8950        hold >>>= bits & 7;
8951        bits -= bits & 7;
8952        //---//
8953        state.mode = CHECK;
8954        break;
8955      }
8956      //=== NEEDBITS(3); */
8957      while (bits < 3) {
8958        if (have === 0) { break inf_leave; }
8959        have--;
8960        hold += input[next++] << bits;
8961        bits += 8;
8962      }
8963      //===//
8964      state.last = (hold & 0x01)/*BITS(1)*/;
8965      //--- DROPBITS(1) ---//
8966      hold >>>= 1;
8967      bits -= 1;
8968      //---//
8969
8970      switch ((hold & 0x03)/*BITS(2)*/) {
8971      case 0:                             /* stored block */
8972        //Tracev((stderr, "inflate:     stored block%s\n",
8973        //        state.last ? " (last)" : ""));
8974        state.mode = STORED;
8975        break;
8976      case 1:                             /* fixed block */
8977        fixedtables(state);
8978        //Tracev((stderr, "inflate:     fixed codes block%s\n",
8979        //        state.last ? " (last)" : ""));
8980        state.mode = LEN_;             /* decode codes */
8981        if (flush === Z_TREES) {
8982          //--- DROPBITS(2) ---//
8983          hold >>>= 2;
8984          bits -= 2;
8985          //---//
8986          break inf_leave;
8987        }
8988        break;
8989      case 2:                             /* dynamic block */
8990        //Tracev((stderr, "inflate:     dynamic codes block%s\n",
8991        //        state.last ? " (last)" : ""));
8992        state.mode = TABLE;
8993        break;
8994      case 3:
8995        strm.msg = 'invalid block type';
8996        state.mode = BAD;
8997      }
8998      //--- DROPBITS(2) ---//
8999      hold >>>= 2;
9000      bits -= 2;
9001      //---//
9002      break;
9003    case STORED:
9004      //--- BYTEBITS() ---// /* go to byte boundary */
9005      hold >>>= bits & 7;
9006      bits -= bits & 7;
9007      //---//
9008      //=== NEEDBITS(32); */
9009      while (bits < 32) {
9010        if (have === 0) { break inf_leave; }
9011        have--;
9012        hold += input[next++] << bits;
9013        bits += 8;
9014      }
9015      //===//
9016      if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
9017        strm.msg = 'invalid stored block lengths';
9018        state.mode = BAD;
9019        break;
9020      }
9021      state.length = hold & 0xffff;
9022      //Tracev((stderr, "inflate:       stored length %u\n",
9023      //        state.length));
9024      //=== INITBITS();
9025      hold = 0;
9026      bits = 0;
9027      //===//
9028      state.mode = COPY_;
9029      if (flush === Z_TREES) { break inf_leave; }
9030      /* falls through */
9031    case COPY_:
9032      state.mode = COPY;
9033      /* falls through */
9034    case COPY:
9035      copy = state.length;
9036      if (copy) {
9037        if (copy > have) { copy = have; }
9038        if (copy > left) { copy = left; }
9039        if (copy === 0) { break inf_leave; }
9040        //--- zmemcpy(put, next, copy); ---
9041        utils.arraySet(output, input, next, copy, put);
9042        //---//
9043        have -= copy;
9044        next += copy;
9045        left -= copy;
9046        put += copy;
9047        state.length -= copy;
9048        break;
9049      }
9050      //Tracev((stderr, "inflate:       stored end\n"));
9051      state.mode = TYPE;
9052      break;
9053    case TABLE:
9054      //=== NEEDBITS(14); */
9055      while (bits < 14) {
9056        if (have === 0) { break inf_leave; }
9057        have--;
9058        hold += input[next++] << bits;
9059        bits += 8;
9060      }
9061      //===//
9062      state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
9063      //--- DROPBITS(5) ---//
9064      hold >>>= 5;
9065      bits -= 5;
9066      //---//
9067      state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
9068      //--- DROPBITS(5) ---//
9069      hold >>>= 5;
9070      bits -= 5;
9071      //---//
9072      state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
9073      //--- DROPBITS(4) ---//
9074      hold >>>= 4;
9075      bits -= 4;
9076      //---//
9077//#ifndef PKZIP_BUG_WORKAROUND
9078      if (state.nlen > 286 || state.ndist > 30) {
9079        strm.msg = 'too many length or distance symbols';
9080        state.mode = BAD;
9081        break;
9082      }
9083//#endif
9084      //Tracev((stderr, "inflate:       table sizes ok\n"));
9085      state.have = 0;
9086      state.mode = LENLENS;
9087      /* falls through */
9088    case LENLENS:
9089      while (state.have < state.ncode) {
9090        //=== NEEDBITS(3);
9091        while (bits < 3) {
9092          if (have === 0) { break inf_leave; }
9093          have--;
9094          hold += input[next++] << bits;
9095          bits += 8;
9096        }
9097        //===//
9098        state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
9099        //--- DROPBITS(3) ---//
9100        hold >>>= 3;
9101        bits -= 3;
9102        //---//
9103      }
9104      while (state.have < 19) {
9105        state.lens[order[state.have++]] = 0;
9106      }
9107      // We have separate tables & no pointers. 2 commented lines below not needed.
9108      //state.next = state.codes;
9109      //state.lencode = state.next;
9110      // Switch to use dynamic table
9111      state.lencode = state.lendyn;
9112      state.lenbits = 7;
9113
9114      opts = { bits: state.lenbits };
9115      ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
9116      state.lenbits = opts.bits;
9117
9118      if (ret) {
9119        strm.msg = 'invalid code lengths set';
9120        state.mode = BAD;
9121        break;
9122      }
9123      //Tracev((stderr, "inflate:       code lengths ok\n"));
9124      state.have = 0;
9125      state.mode = CODELENS;
9126      /* falls through */
9127    case CODELENS:
9128      while (state.have < state.nlen + state.ndist) {
9129        for (;;) {
9130          here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
9131          here_bits = here >>> 24;
9132          here_op = (here >>> 16) & 0xff;
9133          here_val = here & 0xffff;
9134
9135          if ((here_bits) <= bits) { break; }
9136          //--- PULLBYTE() ---//
9137          if (have === 0) { break inf_leave; }
9138          have--;
9139          hold += input[next++] << bits;
9140          bits += 8;
9141          //---//
9142        }
9143        if (here_val < 16) {
9144          //--- DROPBITS(here.bits) ---//
9145          hold >>>= here_bits;
9146          bits -= here_bits;
9147          //---//
9148          state.lens[state.have++] = here_val;
9149        }
9150        else {
9151          if (here_val === 16) {
9152            //=== NEEDBITS(here.bits + 2);
9153            n = here_bits + 2;
9154            while (bits < n) {
9155              if (have === 0) { break inf_leave; }
9156              have--;
9157              hold += input[next++] << bits;
9158              bits += 8;
9159            }
9160            //===//
9161            //--- DROPBITS(here.bits) ---//
9162            hold >>>= here_bits;
9163            bits -= here_bits;
9164            //---//
9165            if (state.have === 0) {
9166              strm.msg = 'invalid bit length repeat';
9167              state.mode = BAD;
9168              break;
9169            }
9170            len = state.lens[state.have - 1];
9171            copy = 3 + (hold & 0x03);//BITS(2);
9172            //--- DROPBITS(2) ---//
9173            hold >>>= 2;
9174            bits -= 2;
9175            //---//
9176          }
9177          else if (here_val === 17) {
9178            //=== NEEDBITS(here.bits + 3);
9179            n = here_bits + 3;
9180            while (bits < n) {
9181              if (have === 0) { break inf_leave; }
9182              have--;
9183              hold += input[next++] << bits;
9184              bits += 8;
9185            }
9186            //===//
9187            //--- DROPBITS(here.bits) ---//
9188            hold >>>= here_bits;
9189            bits -= here_bits;
9190            //---//
9191            len = 0;
9192            copy = 3 + (hold & 0x07);//BITS(3);
9193            //--- DROPBITS(3) ---//
9194            hold >>>= 3;
9195            bits -= 3;
9196            //---//
9197          }
9198          else {
9199            //=== NEEDBITS(here.bits + 7);
9200            n = here_bits + 7;
9201            while (bits < n) {
9202              if (have === 0) { break inf_leave; }
9203              have--;
9204              hold += input[next++] << bits;
9205              bits += 8;
9206            }
9207            //===//
9208            //--- DROPBITS(here.bits) ---//
9209            hold >>>= here_bits;
9210            bits -= here_bits;
9211            //---//
9212            len = 0;
9213            copy = 11 + (hold & 0x7f);//BITS(7);
9214            //--- DROPBITS(7) ---//
9215            hold >>>= 7;
9216            bits -= 7;
9217            //---//
9218          }
9219          if (state.have + copy > state.nlen + state.ndist) {
9220            strm.msg = 'invalid bit length repeat';
9221            state.mode = BAD;
9222            break;
9223          }
9224          while (copy--) {
9225            state.lens[state.have++] = len;
9226          }
9227        }
9228      }
9229
9230      /* handle error breaks in while */
9231      if (state.mode === BAD) { break; }
9232
9233      /* check for end-of-block code (better have one) */
9234      if (state.lens[256] === 0) {
9235        strm.msg = 'invalid code -- missing end-of-block';
9236        state.mode = BAD;
9237        break;
9238      }
9239
9240      /* build code tables -- note: do not change the lenbits or distbits
9241         values here (9 and 6) without reading the comments in inftrees.h
9242         concerning the ENOUGH constants, which depend on those values */
9243      state.lenbits = 9;
9244
9245      opts = { bits: state.lenbits };
9246      ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
9247      // We have separate tables & no pointers. 2 commented lines below not needed.
9248      // state.next_index = opts.table_index;
9249      state.lenbits = opts.bits;
9250      // state.lencode = state.next;
9251
9252      if (ret) {
9253        strm.msg = 'invalid literal/lengths set';
9254        state.mode = BAD;
9255        break;
9256      }
9257
9258      state.distbits = 6;
9259      //state.distcode.copy(state.codes);
9260      // Switch to use dynamic table
9261      state.distcode = state.distdyn;
9262      opts = { bits: state.distbits };
9263      ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
9264      // We have separate tables & no pointers. 2 commented lines below not needed.
9265      // state.next_index = opts.table_index;
9266      state.distbits = opts.bits;
9267      // state.distcode = state.next;
9268
9269      if (ret) {
9270        strm.msg = 'invalid distances set';
9271        state.mode = BAD;
9272        break;
9273      }
9274      //Tracev((stderr, 'inflate:       codes ok\n'));
9275      state.mode = LEN_;
9276      if (flush === Z_TREES) { break inf_leave; }
9277      /* falls through */
9278    case LEN_:
9279      state.mode = LEN;
9280      /* falls through */
9281    case LEN:
9282      if (have >= 6 && left >= 258) {
9283        //--- RESTORE() ---
9284        strm.next_out = put;
9285        strm.avail_out = left;
9286        strm.next_in = next;
9287        strm.avail_in = have;
9288        state.hold = hold;
9289        state.bits = bits;
9290        //---
9291        inflate_fast(strm, _out);
9292        //--- LOAD() ---
9293        put = strm.next_out;
9294        output = strm.output;
9295        left = strm.avail_out;
9296        next = strm.next_in;
9297        input = strm.input;
9298        have = strm.avail_in;
9299        hold = state.hold;
9300        bits = state.bits;
9301        //---
9302
9303        if (state.mode === TYPE) {
9304          state.back = -1;
9305        }
9306        break;
9307      }
9308      state.back = 0;
9309      for (;;) {
9310        here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
9311        here_bits = here >>> 24;
9312        here_op = (here >>> 16) & 0xff;
9313        here_val = here & 0xffff;
9314
9315        if (here_bits <= bits) { break; }
9316        //--- PULLBYTE() ---//
9317        if (have === 0) { break inf_leave; }
9318        have--;
9319        hold += input[next++] << bits;
9320        bits += 8;
9321        //---//
9322      }
9323      if (here_op && (here_op & 0xf0) === 0) {
9324        last_bits = here_bits;
9325        last_op = here_op;
9326        last_val = here_val;
9327        for (;;) {
9328          here = state.lencode[last_val +
9329                  ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
9330          here_bits = here >>> 24;
9331          here_op = (here >>> 16) & 0xff;
9332          here_val = here & 0xffff;
9333
9334          if ((last_bits + here_bits) <= bits) { break; }
9335          //--- PULLBYTE() ---//
9336          if (have === 0) { break inf_leave; }
9337          have--;
9338          hold += input[next++] << bits;
9339          bits += 8;
9340          //---//
9341        }
9342        //--- DROPBITS(last.bits) ---//
9343        hold >>>= last_bits;
9344        bits -= last_bits;
9345        //---//
9346        state.back += last_bits;
9347      }
9348      //--- DROPBITS(here.bits) ---//
9349      hold >>>= here_bits;
9350      bits -= here_bits;
9351      //---//
9352      state.back += here_bits;
9353      state.length = here_val;
9354      if (here_op === 0) {
9355        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
9356        //        "inflate:         literal '%c'\n" :
9357        //        "inflate:         literal 0x%02x\n", here.val));
9358        state.mode = LIT;
9359        break;
9360      }
9361      if (here_op & 32) {
9362        //Tracevv((stderr, "inflate:         end of block\n"));
9363        state.back = -1;
9364        state.mode = TYPE;
9365        break;
9366      }
9367      if (here_op & 64) {
9368        strm.msg = 'invalid literal/length code';
9369        state.mode = BAD;
9370        break;
9371      }
9372      state.extra = here_op & 15;
9373      state.mode = LENEXT;
9374      /* falls through */
9375    case LENEXT:
9376      if (state.extra) {
9377        //=== NEEDBITS(state.extra);
9378        n = state.extra;
9379        while (bits < n) {
9380          if (have === 0) { break inf_leave; }
9381          have--;
9382          hold += input[next++] << bits;
9383          bits += 8;
9384        }
9385        //===//
9386        state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
9387        //--- DROPBITS(state.extra) ---//
9388        hold >>>= state.extra;
9389        bits -= state.extra;
9390        //---//
9391        state.back += state.extra;
9392      }
9393      //Tracevv((stderr, "inflate:         length %u\n", state.length));
9394      state.was = state.length;
9395      state.mode = DIST;
9396      /* falls through */
9397    case DIST:
9398      for (;;) {
9399        here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
9400        here_bits = here >>> 24;
9401        here_op = (here >>> 16) & 0xff;
9402        here_val = here & 0xffff;
9403
9404        if ((here_bits) <= bits) { break; }
9405        //--- PULLBYTE() ---//
9406        if (have === 0) { break inf_leave; }
9407        have--;
9408        hold += input[next++] << bits;
9409        bits += 8;
9410        //---//
9411      }
9412      if ((here_op & 0xf0) === 0) {
9413        last_bits = here_bits;
9414        last_op = here_op;
9415        last_val = here_val;
9416        for (;;) {
9417          here = state.distcode[last_val +
9418                  ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
9419          here_bits = here >>> 24;
9420          here_op = (here >>> 16) & 0xff;
9421          here_val = here & 0xffff;
9422
9423          if ((last_bits + here_bits) <= bits) { break; }
9424          //--- PULLBYTE() ---//
9425          if (have === 0) { break inf_leave; }
9426          have--;
9427          hold += input[next++] << bits;
9428          bits += 8;
9429          //---//
9430        }
9431        //--- DROPBITS(last.bits) ---//
9432        hold >>>= last_bits;
9433        bits -= last_bits;
9434        //---//
9435        state.back += last_bits;
9436      }
9437      //--- DROPBITS(here.bits) ---//
9438      hold >>>= here_bits;
9439      bits -= here_bits;
9440      //---//
9441      state.back += here_bits;
9442      if (here_op & 64) {
9443        strm.msg = 'invalid distance code';
9444        state.mode = BAD;
9445        break;
9446      }
9447      state.offset = here_val;
9448      state.extra = (here_op) & 15;
9449      state.mode = DISTEXT;
9450      /* falls through */
9451    case DISTEXT:
9452      if (state.extra) {
9453        //=== NEEDBITS(state.extra);
9454        n = state.extra;
9455        while (bits < n) {
9456          if (have === 0) { break inf_leave; }
9457          have--;
9458          hold += input[next++] << bits;
9459          bits += 8;
9460        }
9461        //===//
9462        state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
9463        //--- DROPBITS(state.extra) ---//
9464        hold >>>= state.extra;
9465        bits -= state.extra;
9466        //---//
9467        state.back += state.extra;
9468      }
9469//#ifdef INFLATE_STRICT
9470      if (state.offset > state.dmax) {
9471        strm.msg = 'invalid distance too far back';
9472        state.mode = BAD;
9473        break;
9474      }
9475//#endif
9476      //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
9477      state.mode = MATCH;
9478      /* falls through */
9479    case MATCH:
9480      if (left === 0) { break inf_leave; }
9481      copy = _out - left;
9482      if (state.offset > copy) {         /* copy from window */
9483        copy = state.offset - copy;
9484        if (copy > state.whave) {
9485          if (state.sane) {
9486            strm.msg = 'invalid distance too far back';
9487            state.mode = BAD;
9488            break;
9489          }
9490// (!) This block is disabled in zlib defailts,
9491// don't enable it for binary compatibility
9492//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
9493//          Trace((stderr, "inflate.c too far\n"));
9494//          copy -= state.whave;
9495//          if (copy > state.length) { copy = state.length; }
9496//          if (copy > left) { copy = left; }
9497//          left -= copy;
9498//          state.length -= copy;
9499//          do {
9500//            output[put++] = 0;
9501//          } while (--copy);
9502//          if (state.length === 0) { state.mode = LEN; }
9503//          break;
9504//#endif
9505        }
9506        if (copy > state.wnext) {
9507          copy -= state.wnext;
9508          from = state.wsize - copy;
9509        }
9510        else {
9511          from = state.wnext - copy;
9512        }
9513        if (copy > state.length) { copy = state.length; }
9514        from_source = state.window;
9515      }
9516      else {                              /* copy from output */
9517        from_source = output;
9518        from = put - state.offset;
9519        copy = state.length;
9520      }
9521      if (copy > left) { copy = left; }
9522      left -= copy;
9523      state.length -= copy;
9524      do {
9525        output[put++] = from_source[from++];
9526      } while (--copy);
9527      if (state.length === 0) { state.mode = LEN; }
9528      break;
9529    case LIT:
9530      if (left === 0) { break inf_leave; }
9531      output[put++] = state.length;
9532      left--;
9533      state.mode = LEN;
9534      break;
9535    case CHECK:
9536      if (state.wrap) {
9537        //=== NEEDBITS(32);
9538        while (bits < 32) {
9539          if (have === 0) { break inf_leave; }
9540          have--;
9541          // Use '|' insdead of '+' to make sure that result is signed
9542          hold |= input[next++] << bits;
9543          bits += 8;
9544        }
9545        //===//
9546        _out -= left;
9547        strm.total_out += _out;
9548        state.total += _out;
9549        if (_out) {
9550          strm.adler = state.check =
9551              /*UPDATE(state.check, put - _out, _out);*/
9552              (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
9553
9554        }
9555        _out = left;
9556        // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
9557        if ((state.flags ? hold : zswap32(hold)) !== state.check) {
9558          strm.msg = 'incorrect data check';
9559          state.mode = BAD;
9560          break;
9561        }
9562        //=== INITBITS();
9563        hold = 0;
9564        bits = 0;
9565        //===//
9566        //Tracev((stderr, "inflate:   check matches trailer\n"));
9567      }
9568      state.mode = LENGTH;
9569      /* falls through */
9570    case LENGTH:
9571      if (state.wrap && state.flags) {
9572        //=== NEEDBITS(32);
9573        while (bits < 32) {
9574          if (have === 0) { break inf_leave; }
9575          have--;
9576          hold += input[next++] << bits;
9577          bits += 8;
9578        }
9579        //===//
9580        if (hold !== (state.total & 0xffffffff)) {
9581          strm.msg = 'incorrect length check';
9582          state.mode = BAD;
9583          break;
9584        }
9585        //=== INITBITS();
9586        hold = 0;
9587        bits = 0;
9588        //===//
9589        //Tracev((stderr, "inflate:   length matches trailer\n"));
9590      }
9591      state.mode = DONE;
9592      /* falls through */
9593    case DONE:
9594      ret = Z_STREAM_END;
9595      break inf_leave;
9596    case BAD:
9597      ret = Z_DATA_ERROR;
9598      break inf_leave;
9599    case MEM:
9600      return Z_MEM_ERROR;
9601    case SYNC:
9602      /* falls through */
9603    default:
9604      return Z_STREAM_ERROR;
9605    }
9606  }
9607
9608  // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
9609
9610  /*
9611     Return from inflate(), updating the total counts and the check value.
9612     If there was no progress during the inflate() call, return a buffer
9613     error.  Call updatewindow() to create and/or update the window state.
9614     Note: a memory error from inflate() is non-recoverable.
9615   */
9616
9617  //--- RESTORE() ---
9618  strm.next_out = put;
9619  strm.avail_out = left;
9620  strm.next_in = next;
9621  strm.avail_in = have;
9622  state.hold = hold;
9623  state.bits = bits;
9624  //---
9625
9626  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
9627                      (state.mode < CHECK || flush !== Z_FINISH))) {
9628    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
9629      state.mode = MEM;
9630      return Z_MEM_ERROR;
9631    }
9632  }
9633  _in -= strm.avail_in;
9634  _out -= strm.avail_out;
9635  strm.total_in += _in;
9636  strm.total_out += _out;
9637  state.total += _out;
9638  if (state.wrap && _out) {
9639    strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
9640      (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
9641  }
9642  strm.data_type = state.bits + (state.last ? 64 : 0) +
9643                    (state.mode === TYPE ? 128 : 0) +
9644                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
9645  if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
9646    ret = Z_BUF_ERROR;
9647  }
9648  return ret;
9649}
9650
9651function inflateEnd(strm) {
9652
9653  if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
9654    return Z_STREAM_ERROR;
9655  }
9656
9657  var state = strm.state;
9658  if (state.window) {
9659    state.window = null;
9660  }
9661  strm.state = null;
9662  return Z_OK;
9663}
9664
9665function inflateGetHeader(strm, head) {
9666  var state;
9667
9668  /* check state */
9669  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9670  state = strm.state;
9671  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
9672
9673  /* save header structure */
9674  state.head = head;
9675  head.done = false;
9676  return Z_OK;
9677}
9678
9679function inflateSetDictionary(strm, dictionary) {
9680  var dictLength = dictionary.length;
9681
9682  var state;
9683  var dictid;
9684  var ret;
9685
9686  /* check state */
9687  if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
9688  state = strm.state;
9689
9690  if (state.wrap !== 0 && state.mode !== DICT) {
9691    return Z_STREAM_ERROR;
9692  }
9693
9694  /* check for correct dictionary identifier */
9695  if (state.mode === DICT) {
9696    dictid = 1; /* adler32(0, null, 0)*/
9697    /* dictid = adler32(dictid, dictionary, dictLength); */
9698    dictid = adler32(dictid, dictionary, dictLength, 0);
9699    if (dictid !== state.check) {
9700      return Z_DATA_ERROR;
9701    }
9702  }
9703  /* copy dictionary to window using updatewindow(), which will amend the
9704   existing dictionary if appropriate */
9705  ret = updatewindow(strm, dictionary, dictLength, dictLength);
9706  if (ret) {
9707    state.mode = MEM;
9708    return Z_MEM_ERROR;
9709  }
9710  state.havedict = 1;
9711  // Tracev((stderr, "inflate:   dictionary set\n"));
9712  return Z_OK;
9713}
9714
9715exports.inflateReset = inflateReset;
9716exports.inflateReset2 = inflateReset2;
9717exports.inflateResetKeep = inflateResetKeep;
9718exports.inflateInit = inflateInit;
9719exports.inflateInit2 = inflateInit2;
9720exports.inflate = inflate;
9721exports.inflateEnd = inflateEnd;
9722exports.inflateGetHeader = inflateGetHeader;
9723exports.inflateSetDictionary = inflateSetDictionary;
9724exports.inflateInfo = 'pako inflate (from Nodeca project)';
9725
9726/* Not implemented
9727exports.inflateCopy = inflateCopy;
9728exports.inflateGetDictionary = inflateGetDictionary;
9729exports.inflateMark = inflateMark;
9730exports.inflatePrime = inflatePrime;
9731exports.inflateSync = inflateSync;
9732exports.inflateSyncPoint = inflateSyncPoint;
9733exports.inflateUndermine = inflateUndermine;
9734*/
9735
9736},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(require,module,exports){
9737'use strict';
9738
9739// (C) 1995-2013 Jean-loup Gailly and Mark Adler
9740// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
9741//
9742// This software is provided 'as-is', without any express or implied
9743// warranty. In no event will the authors be held liable for any damages
9744// arising from the use of this software.
9745//
9746// Permission is granted to anyone to use this software for any purpose,
9747// including commercial applications, and to alter it and redistribute it
9748// freely, subject to the following restrictions:
9749//
9750// 1. The origin of this software must not be misrepresented; you must not
9751//   claim that you wrote the original software. If you use this software
9752//   in a product, an acknowledgment in the product documentation would be
9753//   appreciated but is not required.
9754// 2. Altered source versions must be plainly marked as such, and must not be
9755//   misrepresented as being the original software.
9756// 3. This notice may not be removed or altered from any source distribution.
9757
9758var utils = require('../utils/common');
9759
9760var MAXBITS = 15;
9761var ENOUGH_LENS = 852;
9762var ENOUGH_DISTS = 592;
9763//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
9764
9765var CODES = 0;
9766var LENS = 1;
9767var DISTS = 2;
9768
9769var lbase = [ /* Length codes 257..285 base */
9770  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
9771  35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
9772];
9773
9774var lext = [ /* Length codes 257..285 extra */
9775  16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
9776  19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
9777];
9778
9779var dbase = [ /* Distance codes 0..29 base */
9780  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
9781  257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
9782  8193, 12289, 16385, 24577, 0, 0
9783];
9784
9785var dext = [ /* Distance codes 0..29 extra */
9786  16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
9787  23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
9788  28, 28, 29, 29, 64, 64
9789];
9790
9791module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
9792{
9793  var bits = opts.bits;
9794      //here = opts.here; /* table entry for duplication */
9795
9796  var len = 0;               /* a code's length in bits */
9797  var sym = 0;               /* index of code symbols */
9798  var min = 0, max = 0;          /* minimum and maximum code lengths */
9799  var root = 0;              /* number of index bits for root table */
9800  var curr = 0;              /* number of index bits for current table */
9801  var drop = 0;              /* code bits to drop for sub-table */
9802  var left = 0;                   /* number of prefix codes available */
9803  var used = 0;              /* code entries in table used */
9804  var huff = 0;              /* Huffman code */
9805  var incr;              /* for incrementing code, index */
9806  var fill;              /* index for replicating entries */
9807  var low;               /* low bits for current root entry */
9808  var mask;              /* mask for low root bits */
9809  var next;             /* next available space in table */
9810  var base = null;     /* base value table to use */
9811  var base_index = 0;
9812//  var shoextra;    /* extra bits table to use */
9813  var end;                    /* use base and extra for symbol > end */
9814  var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
9815  var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
9816  var extra = null;
9817  var extra_index = 0;
9818
9819  var here_bits, here_op, here_val;
9820
9821  /*
9822   Process a set of code lengths to create a canonical Huffman code.  The
9823   code lengths are lens[0..codes-1].  Each length corresponds to the
9824   symbols 0..codes-1.  The Huffman code is generated by first sorting the
9825   symbols by length from short to long, and retaining the symbol order
9826   for codes with equal lengths.  Then the code starts with all zero bits
9827   for the first code of the shortest length, and the codes are integer
9828   increments for the same length, and zeros are appended as the length
9829   increases.  For the deflate format, these bits are stored backwards
9830   from their more natural integer increment ordering, and so when the
9831   decoding tables are built in the large loop below, the integer codes
9832   are incremented backwards.
9833
9834   This routine assumes, but does not check, that all of the entries in
9835   lens[] are in the range 0..MAXBITS.  The caller must assure this.
9836   1..MAXBITS is interpreted as that code length.  zero means that that
9837   symbol does not occur in this code.
9838
9839   The codes are sorted by computing a count of codes for each length,
9840   creating from that a table of starting indices for each length in the
9841   sorted table, and then entering the symbols in order in the sorted
9842   table.  The sorted table is work[], with that space being provided by
9843   the caller.
9844
9845   The length counts are used for other purposes as well, i.e. finding
9846   the minimum and maximum length codes, determining if there are any
9847   codes at all, checking for a valid set of lengths, and looking ahead
9848   at length counts to determine sub-table sizes when building the
9849   decoding tables.
9850   */
9851
9852  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
9853  for (len = 0; len <= MAXBITS; len++) {
9854    count[len] = 0;
9855  }
9856  for (sym = 0; sym < codes; sym++) {
9857    count[lens[lens_index + sym]]++;
9858  }
9859
9860  /* bound code lengths, force root to be within code lengths */
9861  root = bits;
9862  for (max = MAXBITS; max >= 1; max--) {
9863    if (count[max] !== 0) { break; }
9864  }
9865  if (root > max) {
9866    root = max;
9867  }
9868  if (max === 0) {                     /* no symbols to code at all */
9869    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
9870    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
9871    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
9872    table[table_index++] = (1 << 24) | (64 << 16) | 0;
9873
9874
9875    //table.op[opts.table_index] = 64;
9876    //table.bits[opts.table_index] = 1;
9877    //table.val[opts.table_index++] = 0;
9878    table[table_index++] = (1 << 24) | (64 << 16) | 0;
9879
9880    opts.bits = 1;
9881    return 0;     /* no symbols, but wait for decoding to report error */
9882  }
9883  for (min = 1; min < max; min++) {
9884    if (count[min] !== 0) { break; }
9885  }
9886  if (root < min) {
9887    root = min;
9888  }
9889
9890  /* check for an over-subscribed or incomplete set of lengths */
9891  left = 1;
9892  for (len = 1; len <= MAXBITS; len++) {
9893    left <<= 1;
9894    left -= count[len];
9895    if (left < 0) {
9896      return -1;
9897    }        /* over-subscribed */
9898  }
9899  if (left > 0 && (type === CODES || max !== 1)) {
9900    return -1;                      /* incomplete set */
9901  }
9902
9903  /* generate offsets into symbol table for each length for sorting */
9904  offs[1] = 0;
9905  for (len = 1; len < MAXBITS; len++) {
9906    offs[len + 1] = offs[len] + count[len];
9907  }
9908
9909  /* sort symbols by length, by symbol order within each length */
9910  for (sym = 0; sym < codes; sym++) {
9911    if (lens[lens_index + sym] !== 0) {
9912      work[offs[lens[lens_index + sym]]++] = sym;
9913    }
9914  }
9915
9916  /*
9917   Create and fill in decoding tables.  In this loop, the table being
9918   filled is at next and has curr index bits.  The code being used is huff
9919   with length len.  That code is converted to an index by dropping drop
9920   bits off of the bottom.  For codes where len is less than drop + curr,
9921   those top drop + curr - len bits are incremented through all values to
9922   fill the table with replicated entries.
9923
9924   root is the number of index bits for the root table.  When len exceeds
9925   root, sub-tables are created pointed to by the root entry with an index
9926   of the low root bits of huff.  This is saved in low to check for when a
9927   new sub-table should be started.  drop is zero when the root table is
9928   being filled, and drop is root when sub-tables are being filled.
9929
9930   When a new sub-table is needed, it is necessary to look ahead in the
9931   code lengths to determine what size sub-table is needed.  The length
9932   counts are used for this, and so count[] is decremented as codes are
9933   entered in the tables.
9934
9935   used keeps track of how many table entries have been allocated from the
9936   provided *table space.  It is checked for LENS and DIST tables against
9937   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
9938   the initial root table size constants.  See the comments in inftrees.h
9939   for more information.
9940
9941   sym increments through all symbols, and the loop terminates when
9942   all codes of length max, i.e. all codes, have been processed.  This
9943   routine permits incomplete codes, so another loop after this one fills
9944   in the rest of the decoding tables with invalid code markers.
9945   */
9946
9947  /* set up for code type */
9948  // poor man optimization - use if-else instead of switch,
9949  // to avoid deopts in old v8
9950  if (type === CODES) {
9951    base = extra = work;    /* dummy value--not used */
9952    end = 19;
9953
9954  } else if (type === LENS) {
9955    base = lbase;
9956    base_index -= 257;
9957    extra = lext;
9958    extra_index -= 257;
9959    end = 256;
9960
9961  } else {                    /* DISTS */
9962    base = dbase;
9963    extra = dext;
9964    end = -1;
9965  }
9966
9967  /* initialize opts for loop */
9968  huff = 0;                   /* starting code */
9969  sym = 0;                    /* starting code symbol */
9970  len = min;                  /* starting code length */
9971  next = table_index;              /* current table to fill in */
9972  curr = root;                /* current table index bits */
9973  drop = 0;                   /* current bits to drop from code for index */
9974  low = -1;                   /* trigger new sub-table when len > root */
9975  used = 1 << root;          /* use root table entries */
9976  mask = used - 1;            /* mask for comparing low */
9977
9978  /* check available table space */
9979  if ((type === LENS && used > ENOUGH_LENS) ||
9980    (type === DISTS && used > ENOUGH_DISTS)) {
9981    return 1;
9982  }
9983
9984  /* process all codes and make table entries */
9985  for (;;) {
9986    /* create table entry */
9987    here_bits = len - drop;
9988    if (work[sym] < end) {
9989      here_op = 0;
9990      here_val = work[sym];
9991    }
9992    else if (work[sym] > end) {
9993      here_op = extra[extra_index + work[sym]];
9994      here_val = base[base_index + work[sym]];
9995    }
9996    else {
9997      here_op = 32 + 64;         /* end of block */
9998      here_val = 0;
9999    }
10000
10001    /* replicate for those indices with low len bits equal to huff */
10002    incr = 1 << (len - drop);
10003    fill = 1 << curr;
10004    min = fill;                 /* save offset to next table */
10005    do {
10006      fill -= incr;
10007      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
10008    } while (fill !== 0);
10009
10010    /* backwards increment the len-bit code huff */
10011    incr = 1 << (len - 1);
10012    while (huff & incr) {
10013      incr >>= 1;
10014    }
10015    if (incr !== 0) {
10016      huff &= incr - 1;
10017      huff += incr;
10018    } else {
10019      huff = 0;
10020    }
10021
10022    /* go to next symbol, update count, len */
10023    sym++;
10024    if (--count[len] === 0) {
10025      if (len === max) { break; }
10026      len = lens[lens_index + work[sym]];
10027    }
10028
10029    /* create new sub-table if needed */
10030    if (len > root && (huff & mask) !== low) {
10031      /* if first time, transition to sub-tables */
10032      if (drop === 0) {
10033        drop = root;
10034      }
10035
10036      /* increment past last table */
10037      next += min;            /* here min is 1 << curr */
10038
10039      /* determine length of next table */
10040      curr = len - drop;
10041      left = 1 << curr;
10042      while (curr + drop < max) {
10043        left -= count[curr + drop];
10044        if (left <= 0) { break; }
10045        curr++;
10046        left <<= 1;
10047      }
10048
10049      /* check for enough space */
10050      used += 1 << curr;
10051      if ((type === LENS && used > ENOUGH_LENS) ||
10052        (type === DISTS && used > ENOUGH_DISTS)) {
10053        return 1;
10054      }
10055
10056      /* point entry in root table to sub-table */
10057      low = huff & mask;
10058      /*table.op[low] = curr;
10059      table.bits[low] = root;
10060      table.val[low] = next - opts.table_index;*/
10061      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
10062    }
10063  }
10064
10065  /* fill in remaining table entry if code is incomplete (guaranteed to have
10066   at most one remaining entry, since if the code is incomplete, the
10067   maximum code length that was allowed to get this far is one bit) */
10068  if (huff !== 0) {
10069    //table.op[next + huff] = 64;            /* invalid code marker */
10070    //table.bits[next + huff] = len - drop;
10071    //table.val[next + huff] = 0;
10072    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
10073  }
10074
10075  /* set return parameters */
10076  //opts.table_index += used;
10077  opts.bits = root;
10078  return 0;
10079};
10080
10081},{"../utils/common":41}],51:[function(require,module,exports){
10082'use strict';
10083
10084// (C) 1995-2013 Jean-loup Gailly and Mark Adler
10085// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
10086//
10087// This software is provided 'as-is', without any express or implied
10088// warranty. In no event will the authors be held liable for any damages
10089// arising from the use of this software.
10090//
10091// Permission is granted to anyone to use this software for any purpose,
10092// including commercial applications, and to alter it and redistribute it
10093// freely, subject to the following restrictions:
10094//
10095// 1. The origin of this software must not be misrepresented; you must not
10096//   claim that you wrote the original software. If you use this software
10097//   in a product, an acknowledgment in the product documentation would be
10098//   appreciated but is not required.
10099// 2. Altered source versions must be plainly marked as such, and must not be
10100//   misrepresented as being the original software.
10101// 3. This notice may not be removed or altered from any source distribution.
10102
10103module.exports = {
10104  2:      'need dictionary',     /* Z_NEED_DICT       2  */
10105  1:      'stream end',          /* Z_STREAM_END      1  */
10106  0:      '',                    /* Z_OK              0  */
10107  '-1':   'file error',          /* Z_ERRNO         (-1) */
10108  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
10109  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
10110  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
10111  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
10112  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
10113};
10114
10115},{}],52:[function(require,module,exports){
10116'use strict';
10117
10118// (C) 1995-2013 Jean-loup Gailly and Mark Adler
10119// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
10120//
10121// This software is provided 'as-is', without any express or implied
10122// warranty. In no event will the authors be held liable for any damages
10123// arising from the use of this software.
10124//
10125// Permission is granted to anyone to use this software for any purpose,
10126// including commercial applications, and to alter it and redistribute it
10127// freely, subject to the following restrictions:
10128//
10129// 1. The origin of this software must not be misrepresented; you must not
10130//   claim that you wrote the original software. If you use this software
10131//   in a product, an acknowledgment in the product documentation would be
10132//   appreciated but is not required.
10133// 2. Altered source versions must be plainly marked as such, and must not be
10134//   misrepresented as being the original software.
10135// 3. This notice may not be removed or altered from any source distribution.
10136
10137var utils = require('../utils/common');
10138
10139/* Public constants ==========================================================*/
10140/* ===========================================================================*/
10141
10142
10143//var Z_FILTERED          = 1;
10144//var Z_HUFFMAN_ONLY      = 2;
10145//var Z_RLE               = 3;
10146var Z_FIXED               = 4;
10147//var Z_DEFAULT_STRATEGY  = 0;
10148
10149/* Possible values of the data_type field (though see inflate()) */
10150var Z_BINARY              = 0;
10151var Z_TEXT                = 1;
10152//var Z_ASCII             = 1; // = Z_TEXT
10153var Z_UNKNOWN             = 2;
10154
10155/*============================================================================*/
10156
10157
10158function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
10159
10160// From zutil.h
10161
10162var STORED_BLOCK = 0;
10163var STATIC_TREES = 1;
10164var DYN_TREES    = 2;
10165/* The three kinds of block type */
10166
10167var MIN_MATCH    = 3;
10168var MAX_MATCH    = 258;
10169/* The minimum and maximum match lengths */
10170
10171// From deflate.h
10172/* ===========================================================================
10173 * Internal compression state.
10174 */
10175
10176var LENGTH_CODES  = 29;
10177/* number of length codes, not counting the special END_BLOCK code */
10178
10179var LITERALS      = 256;
10180/* number of literal bytes 0..255 */
10181
10182var L_CODES       = LITERALS + 1 + LENGTH_CODES;
10183/* number of Literal or Length codes, including the END_BLOCK code */
10184
10185var D_CODES       = 30;
10186/* number of distance codes */
10187
10188var BL_CODES      = 19;
10189/* number of codes used to transfer the bit lengths */
10190
10191var HEAP_SIZE     = 2 * L_CODES + 1;
10192/* maximum heap size */
10193
10194var MAX_BITS      = 15;
10195/* All codes must not exceed MAX_BITS bits */
10196
10197var Buf_size      = 16;
10198/* size of bit buffer in bi_buf */
10199
10200
10201/* ===========================================================================
10202 * Constants
10203 */
10204
10205var MAX_BL_BITS = 7;
10206/* Bit length codes must not exceed MAX_BL_BITS bits */
10207
10208var END_BLOCK   = 256;
10209/* end of block literal code */
10210
10211var REP_3_6     = 16;
10212/* repeat previous bit length 3-6 times (2 bits of repeat count) */
10213
10214var REPZ_3_10   = 17;
10215/* repeat a zero length 3-10 times  (3 bits of repeat count) */
10216
10217var REPZ_11_138 = 18;
10218/* repeat a zero length 11-138 times  (7 bits of repeat count) */
10219
10220/* eslint-disable comma-spacing,array-bracket-spacing */
10221var extra_lbits =   /* extra bits for each length code */
10222  [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];
10223
10224var extra_dbits =   /* extra bits for each distance code */
10225  [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];
10226
10227var extra_blbits =  /* extra bits for each bit length code */
10228  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
10229
10230var bl_order =
10231  [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
10232/* eslint-enable comma-spacing,array-bracket-spacing */
10233
10234/* The lengths of the bit length codes are sent in order of decreasing
10235 * probability, to avoid transmitting the lengths for unused bit length codes.
10236 */
10237
10238/* ===========================================================================
10239 * Local data. These are initialized only once.
10240 */
10241
10242// We pre-fill arrays with 0 to avoid uninitialized gaps
10243
10244var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
10245
10246// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
10247var static_ltree  = new Array((L_CODES + 2) * 2);
10248zero(static_ltree);
10249/* The static literal tree. Since the bit lengths are imposed, there is no
10250 * need for the L_CODES extra codes used during heap construction. However
10251 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
10252 * below).
10253 */
10254
10255var static_dtree  = new Array(D_CODES * 2);
10256zero(static_dtree);
10257/* The static distance tree. (Actually a trivial tree since all codes use
10258 * 5 bits.)
10259 */
10260
10261var _dist_code    = new Array(DIST_CODE_LEN);
10262zero(_dist_code);
10263/* Distance codes. The first 256 values correspond to the distances
10264 * 3 .. 258, the last 256 values correspond to the top 8 bits of
10265 * the 15 bit distances.
10266 */
10267
10268var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
10269zero(_length_code);
10270/* length code for each normalized match length (0 == MIN_MATCH) */
10271
10272var base_length   = new Array(LENGTH_CODES);
10273zero(base_length);
10274/* First normalized length for each code (0 = MIN_MATCH) */
10275
10276var base_dist     = new Array(D_CODES);
10277zero(base_dist);
10278/* First normalized distance for each code (0 = distance of 1) */
10279
10280
10281function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
10282
10283  this.static_tree  = static_tree;  /* static tree or NULL */
10284  this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
10285  this.extra_base   = extra_base;   /* base index for extra_bits */
10286  this.elems        = elems;        /* max number of elements in the tree */
10287  this.max_length   = max_length;   /* max bit length for the codes */
10288
10289  // show if `static_tree` has data or dummy - needed for monomorphic objects
10290  this.has_stree    = static_tree && static_tree.length;
10291}
10292
10293
10294var static_l_desc;
10295var static_d_desc;
10296var static_bl_desc;
10297
10298
10299function TreeDesc(dyn_tree, stat_desc) {
10300  this.dyn_tree = dyn_tree;     /* the dynamic tree */
10301  this.max_code = 0;            /* largest code with non zero frequency */
10302  this.stat_desc = stat_desc;   /* the corresponding static tree */
10303}
10304
10305
10306
10307function d_code(dist) {
10308  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
10309}
10310
10311
10312/* ===========================================================================
10313 * Output a short LSB first on the stream.
10314 * IN assertion: there is enough room in pendingBuf.
10315 */
10316function put_short(s, w) {
10317//    put_byte(s, (uch)((w) & 0xff));
10318//    put_byte(s, (uch)((ush)(w) >> 8));
10319  s.pending_buf[s.pending++] = (w) & 0xff;
10320  s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
10321}
10322
10323
10324/* ===========================================================================
10325 * Send a value on a given number of bits.
10326 * IN assertion: length <= 16 and value fits in length bits.
10327 */
10328function send_bits(s, value, length) {
10329  if (s.bi_valid > (Buf_size - length)) {
10330    s.bi_buf |= (value << s.bi_valid) & 0xffff;
10331    put_short(s, s.bi_buf);
10332    s.bi_buf = value >> (Buf_size - s.bi_valid);
10333    s.bi_valid += length - Buf_size;
10334  } else {
10335    s.bi_buf |= (value << s.bi_valid) & 0xffff;
10336    s.bi_valid += length;
10337  }
10338}
10339
10340
10341function send_code(s, c, tree) {
10342  send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
10343}
10344
10345
10346/* ===========================================================================
10347 * Reverse the first len bits of a code, using straightforward code (a faster
10348 * method would use a table)
10349 * IN assertion: 1 <= len <= 15
10350 */
10351function bi_reverse(code, len) {
10352  var res = 0;
10353  do {
10354    res |= code & 1;
10355    code >>>= 1;
10356    res <<= 1;
10357  } while (--len > 0);
10358  return res >>> 1;
10359}
10360
10361
10362/* ===========================================================================
10363 * Flush the bit buffer, keeping at most 7 bits in it.
10364 */
10365function bi_flush(s) {
10366  if (s.bi_valid === 16) {
10367    put_short(s, s.bi_buf);
10368    s.bi_buf = 0;
10369    s.bi_valid = 0;
10370
10371  } else if (s.bi_valid >= 8) {
10372    s.pending_buf[s.pending++] = s.bi_buf & 0xff;
10373    s.bi_buf >>= 8;
10374    s.bi_valid -= 8;
10375  }
10376}
10377
10378
10379/* ===========================================================================
10380 * Compute the optimal bit lengths for a tree and update the total bit length
10381 * for the current block.
10382 * IN assertion: the fields freq and dad are set, heap[heap_max] and
10383 *    above are the tree nodes sorted by increasing frequency.
10384 * OUT assertions: the field len is set to the optimal bit length, the
10385 *     array bl_count contains the frequencies for each bit length.
10386 *     The length opt_len is updated; static_len is also updated if stree is
10387 *     not null.
10388 */
10389function gen_bitlen(s, desc)
10390//    deflate_state *s;
10391//    tree_desc *desc;    /* the tree descriptor */
10392{
10393  var tree            = desc.dyn_tree;
10394  var max_code        = desc.max_code;
10395  var stree           = desc.stat_desc.static_tree;
10396  var has_stree       = desc.stat_desc.has_stree;
10397  var extra           = desc.stat_desc.extra_bits;
10398  var base            = desc.stat_desc.extra_base;
10399  var max_length      = desc.stat_desc.max_length;
10400  var h;              /* heap index */
10401  var n, m;           /* iterate over the tree elements */
10402  var bits;           /* bit length */
10403  var xbits;          /* extra bits */
10404  var f;              /* frequency */
10405  var overflow = 0;   /* number of elements with bit length too large */
10406
10407  for (bits = 0; bits <= MAX_BITS; bits++) {
10408    s.bl_count[bits] = 0;
10409  }
10410
10411  /* In a first pass, compute the optimal bit lengths (which may
10412   * overflow in the case of the bit length tree).
10413   */
10414  tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
10415
10416  for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
10417    n = s.heap[h];
10418    bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
10419    if (bits > max_length) {
10420      bits = max_length;
10421      overflow++;
10422    }
10423    tree[n * 2 + 1]/*.Len*/ = bits;
10424    /* We overwrite tree[n].Dad which is no longer needed */
10425
10426    if (n > max_code) { continue; } /* not a leaf node */
10427
10428    s.bl_count[bits]++;
10429    xbits = 0;
10430    if (n >= base) {
10431      xbits = extra[n - base];
10432    }
10433    f = tree[n * 2]/*.Freq*/;
10434    s.opt_len += f * (bits + xbits);
10435    if (has_stree) {
10436      s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
10437    }
10438  }
10439  if (overflow === 0) { return; }
10440
10441  // Trace((stderr,"\nbit length overflow\n"));
10442  /* This happens for example on obj2 and pic of the Calgary corpus */
10443
10444  /* Find the first bit length which could increase: */
10445  do {
10446    bits = max_length - 1;
10447    while (s.bl_count[bits] === 0) { bits--; }
10448    s.bl_count[bits]--;      /* move one leaf down the tree */
10449    s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
10450    s.bl_count[max_length]--;
10451    /* The brother of the overflow item also moves one step up,
10452     * but this does not affect bl_count[max_length]
10453     */
10454    overflow -= 2;
10455  } while (overflow > 0);
10456
10457  /* Now recompute all bit lengths, scanning in increasing frequency.
10458   * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
10459   * lengths instead of fixing only the wrong ones. This idea is taken
10460   * from 'ar' written by Haruhiko Okumura.)
10461   */
10462  for (bits = max_length; bits !== 0; bits--) {
10463    n = s.bl_count[bits];
10464    while (n !== 0) {
10465      m = s.heap[--h];
10466      if (m > max_code) { continue; }
10467      if (tree[m * 2 + 1]/*.Len*/ !== bits) {
10468        // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
10469        s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
10470        tree[m * 2 + 1]/*.Len*/ = bits;
10471      }
10472      n--;
10473    }
10474  }
10475}
10476
10477
10478/* ===========================================================================
10479 * Generate the codes for a given tree and bit counts (which need not be
10480 * optimal).
10481 * IN assertion: the array bl_count contains the bit length statistics for
10482 * the given tree and the field len is set for all tree elements.
10483 * OUT assertion: the field code is set for all tree elements of non
10484 *     zero code length.
10485 */
10486function gen_codes(tree, max_code, bl_count)
10487//    ct_data *tree;             /* the tree to decorate */
10488//    int max_code;              /* largest code with non zero frequency */
10489//    ushf *bl_count;            /* number of codes at each bit length */
10490{
10491  var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
10492  var code = 0;              /* running code value */
10493  var bits;                  /* bit index */
10494  var n;                     /* code index */
10495
10496  /* The distribution counts are first used to generate the code values
10497   * without bit reversal.
10498   */
10499  for (bits = 1; bits <= MAX_BITS; bits++) {
10500    next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
10501  }
10502  /* Check that the bit counts in bl_count are consistent. The last code
10503   * must be all ones.
10504   */
10505  //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
10506  //        "inconsistent bit counts");
10507  //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
10508
10509  for (n = 0;  n <= max_code; n++) {
10510    var len = tree[n * 2 + 1]/*.Len*/;
10511    if (len === 0) { continue; }
10512    /* Now reverse the bits */
10513    tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
10514
10515    //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
10516    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
10517  }
10518}
10519
10520
10521/* ===========================================================================
10522 * Initialize the various 'constant' tables.
10523 */
10524function tr_static_init() {
10525  var n;        /* iterates over tree elements */
10526  var bits;     /* bit counter */
10527  var length;   /* length value */
10528  var code;     /* code value */
10529  var dist;     /* distance index */
10530  var bl_count = new Array(MAX_BITS + 1);
10531  /* number of codes at each bit length for an optimal tree */
10532
10533  // do check in _tr_init()
10534  //if (static_init_done) return;
10535
10536  /* For some embedded targets, global variables are not initialized: */
10537/*#ifdef NO_INIT_GLOBAL_POINTERS
10538  static_l_desc.static_tree = static_ltree;
10539  static_l_desc.extra_bits = extra_lbits;
10540  static_d_desc.static_tree = static_dtree;
10541  static_d_desc.extra_bits = extra_dbits;
10542  static_bl_desc.extra_bits = extra_blbits;
10543#endif*/
10544
10545  /* Initialize the mapping length (0..255) -> length code (0..28) */
10546  length = 0;
10547  for (code = 0; code < LENGTH_CODES - 1; code++) {
10548    base_length[code] = length;
10549    for (n = 0; n < (1 << extra_lbits[code]); n++) {
10550      _length_code[length++] = code;
10551    }
10552  }
10553  //Assert (length == 256, "tr_static_init: length != 256");
10554  /* Note that the length 255 (match length 258) can be represented
10555   * in two different ways: code 284 + 5 bits or code 285, so we
10556   * overwrite length_code[255] to use the best encoding:
10557   */
10558  _length_code[length - 1] = code;
10559
10560  /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
10561  dist = 0;
10562  for (code = 0; code < 16; code++) {
10563    base_dist[code] = dist;
10564    for (n = 0; n < (1 << extra_dbits[code]); n++) {
10565      _dist_code[dist++] = code;
10566    }
10567  }
10568  //Assert (dist == 256, "tr_static_init: dist != 256");
10569  dist >>= 7; /* from now on, all distances are divided by 128 */
10570  for (; code < D_CODES; code++) {
10571    base_dist[code] = dist << 7;
10572    for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
10573      _dist_code[256 + dist++] = code;
10574    }
10575  }
10576  //Assert (dist == 256, "tr_static_init: 256+dist != 512");
10577
10578  /* Construct the codes of the static literal tree */
10579  for (bits = 0; bits <= MAX_BITS; bits++) {
10580    bl_count[bits] = 0;
10581  }
10582
10583  n = 0;
10584  while (n <= 143) {
10585    static_ltree[n * 2 + 1]/*.Len*/ = 8;
10586    n++;
10587    bl_count[8]++;
10588  }
10589  while (n <= 255) {
10590    static_ltree[n * 2 + 1]/*.Len*/ = 9;
10591    n++;
10592    bl_count[9]++;
10593  }
10594  while (n <= 279) {
10595    static_ltree[n * 2 + 1]/*.Len*/ = 7;
10596    n++;
10597    bl_count[7]++;
10598  }
10599  while (n <= 287) {
10600    static_ltree[n * 2 + 1]/*.Len*/ = 8;
10601    n++;
10602    bl_count[8]++;
10603  }
10604  /* Codes 286 and 287 do not exist, but we must include them in the
10605   * tree construction to get a canonical Huffman tree (longest code
10606   * all ones)
10607   */
10608  gen_codes(static_ltree, L_CODES + 1, bl_count);
10609
10610  /* The static distance tree is trivial: */
10611  for (n = 0; n < D_CODES; n++) {
10612    static_dtree[n * 2 + 1]/*.Len*/ = 5;
10613    static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
10614  }
10615
10616  // Now data ready and we can init static trees
10617  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
10618  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
10619  static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
10620
10621  //static_init_done = true;
10622}
10623
10624
10625/* ===========================================================================
10626 * Initialize a new block.
10627 */
10628function init_block(s) {
10629  var n; /* iterates over tree elements */
10630
10631  /* Initialize the trees. */
10632  for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
10633  for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
10634  for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
10635
10636  s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
10637  s.opt_len = s.static_len = 0;
10638  s.last_lit = s.matches = 0;
10639}
10640
10641
10642/* ===========================================================================
10643 * Flush the bit buffer and align the output on a byte boundary
10644 */
10645function bi_windup(s)
10646{
10647  if (s.bi_valid > 8) {
10648    put_short(s, s.bi_buf);
10649  } else if (s.bi_valid > 0) {
10650    //put_byte(s, (Byte)s->bi_buf);
10651    s.pending_buf[s.pending++] = s.bi_buf;
10652  }
10653  s.bi_buf = 0;
10654  s.bi_valid = 0;
10655}
10656
10657/* ===========================================================================
10658 * Copy a stored block, storing first the length and its
10659 * one's complement if requested.
10660 */
10661function copy_block(s, buf, len, header)
10662//DeflateState *s;
10663//charf    *buf;    /* the input data */
10664//unsigned len;     /* its length */
10665//int      header;  /* true if block header must be written */
10666{
10667  bi_windup(s);        /* align on byte boundary */
10668
10669  if (header) {
10670    put_short(s, len);
10671    put_short(s, ~len);
10672  }
10673//  while (len--) {
10674//    put_byte(s, *buf++);
10675//  }
10676  utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
10677  s.pending += len;
10678}
10679
10680/* ===========================================================================
10681 * Compares to subtrees, using the tree depth as tie breaker when
10682 * the subtrees have equal frequency. This minimizes the worst case length.
10683 */
10684function smaller(tree, n, m, depth) {
10685  var _n2 = n * 2;
10686  var _m2 = m * 2;
10687  return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
10688         (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
10689}
10690
10691/* ===========================================================================
10692 * Restore the heap property by moving down the tree starting at node k,
10693 * exchanging a node with the smallest of its two sons if necessary, stopping
10694 * when the heap property is re-established (each father smaller than its
10695 * two sons).
10696 */
10697function pqdownheap(s, tree, k)
10698//    deflate_state *s;
10699//    ct_data *tree;  /* the tree to restore */
10700//    int k;               /* node to move down */
10701{
10702  var v = s.heap[k];
10703  var j = k << 1;  /* left son of k */
10704  while (j <= s.heap_len) {
10705    /* Set j to the smallest of the two sons: */
10706    if (j < s.heap_len &&
10707      smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
10708      j++;
10709    }
10710    /* Exit if v is smaller than both sons */
10711    if (smaller(tree, v, s.heap[j], s.depth)) { break; }
10712
10713    /* Exchange v with the smallest son */
10714    s.heap[k] = s.heap[j];
10715    k = j;
10716
10717    /* And continue down the tree, setting j to the left son of k */
10718    j <<= 1;
10719  }
10720  s.heap[k] = v;
10721}
10722
10723
10724// inlined manually
10725// var SMALLEST = 1;
10726
10727/* ===========================================================================
10728 * Send the block data compressed using the given Huffman trees
10729 */
10730function compress_block(s, ltree, dtree)
10731//    deflate_state *s;
10732//    const ct_data *ltree; /* literal tree */
10733//    const ct_data *dtree; /* distance tree */
10734{
10735  var dist;           /* distance of matched string */
10736  var lc;             /* match length or unmatched char (if dist == 0) */
10737  var lx = 0;         /* running index in l_buf */
10738  var code;           /* the code to send */
10739  var extra;          /* number of extra bits to send */
10740
10741  if (s.last_lit !== 0) {
10742    do {
10743      dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
10744      lc = s.pending_buf[s.l_buf + lx];
10745      lx++;
10746
10747      if (dist === 0) {
10748        send_code(s, lc, ltree); /* send a literal byte */
10749        //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
10750      } else {
10751        /* Here, lc is the match length - MIN_MATCH */
10752        code = _length_code[lc];
10753        send_code(s, code + LITERALS + 1, ltree); /* send the length code */
10754        extra = extra_lbits[code];
10755        if (extra !== 0) {
10756          lc -= base_length[code];
10757          send_bits(s, lc, extra);       /* send the extra length bits */
10758        }
10759        dist--; /* dist is now the match distance - 1 */
10760        code = d_code(dist);
10761        //Assert (code < D_CODES, "bad d_code");
10762
10763        send_code(s, code, dtree);       /* send the distance code */
10764        extra = extra_dbits[code];
10765        if (extra !== 0) {
10766          dist -= base_dist[code];
10767          send_bits(s, dist, extra);   /* send the extra distance bits */
10768        }
10769      } /* literal or match pair ? */
10770
10771      /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
10772      //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
10773      //       "pendingBuf overflow");
10774
10775    } while (lx < s.last_lit);
10776  }
10777
10778  send_code(s, END_BLOCK, ltree);
10779}
10780
10781
10782/* ===========================================================================
10783 * Construct one Huffman tree and assigns the code bit strings and lengths.
10784 * Update the total bit length for the current block.
10785 * IN assertion: the field freq is set for all tree elements.
10786 * OUT assertions: the fields len and code are set to the optimal bit length
10787 *     and corresponding code. The length opt_len is updated; static_len is
10788 *     also updated if stree is not null. The field max_code is set.
10789 */
10790function build_tree(s, desc)
10791//    deflate_state *s;
10792//    tree_desc *desc; /* the tree descriptor */
10793{
10794  var tree     = desc.dyn_tree;
10795  var stree    = desc.stat_desc.static_tree;
10796  var has_stree = desc.stat_desc.has_stree;
10797  var elems    = desc.stat_desc.elems;
10798  var n, m;          /* iterate over heap elements */
10799  var max_code = -1; /* largest code with non zero frequency */
10800  var node;          /* new node being created */
10801
10802  /* Construct the initial heap, with least frequent element in
10803   * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
10804   * heap[0] is not used.
10805   */
10806  s.heap_len = 0;
10807  s.heap_max = HEAP_SIZE;
10808
10809  for (n = 0; n < elems; n++) {
10810    if (tree[n * 2]/*.Freq*/ !== 0) {
10811      s.heap[++s.heap_len] = max_code = n;
10812      s.depth[n] = 0;
10813
10814    } else {
10815      tree[n * 2 + 1]/*.Len*/ = 0;
10816    }
10817  }
10818
10819  /* The pkzip format requires that at least one distance code exists,
10820   * and that at least one bit should be sent even if there is only one
10821   * possible code. So to avoid special checks later on we force at least
10822   * two codes of non zero frequency.
10823   */
10824  while (s.heap_len < 2) {
10825    node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
10826    tree[node * 2]/*.Freq*/ = 1;
10827    s.depth[node] = 0;
10828    s.opt_len--;
10829
10830    if (has_stree) {
10831      s.static_len -= stree[node * 2 + 1]/*.Len*/;
10832    }
10833    /* node is 0 or 1 so it does not have extra bits */
10834  }
10835  desc.max_code = max_code;
10836
10837  /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
10838   * establish sub-heaps of increasing lengths:
10839   */
10840  for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
10841
10842  /* Construct the Huffman tree by repeatedly combining the least two
10843   * frequent nodes.
10844   */
10845  node = elems;              /* next internal node of the tree */
10846  do {
10847    //pqremove(s, tree, n);  /* n = node of least frequency */
10848    /*** pqremove ***/
10849    n = s.heap[1/*SMALLEST*/];
10850    s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
10851    pqdownheap(s, tree, 1/*SMALLEST*/);
10852    /***/
10853
10854    m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
10855
10856    s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
10857    s.heap[--s.heap_max] = m;
10858
10859    /* Create a new node father of n and m */
10860    tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
10861    s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
10862    tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
10863
10864    /* and insert the new node in the heap */
10865    s.heap[1/*SMALLEST*/] = node++;
10866    pqdownheap(s, tree, 1/*SMALLEST*/);
10867
10868  } while (s.heap_len >= 2);
10869
10870  s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
10871
10872  /* At this point, the fields freq and dad are set. We can now
10873   * generate the bit lengths.
10874   */
10875  gen_bitlen(s, desc);
10876
10877  /* The field len is now set, we can generate the bit codes */
10878  gen_codes(tree, max_code, s.bl_count);
10879}
10880
10881
10882/* ===========================================================================
10883 * Scan a literal or distance tree to determine the frequencies of the codes
10884 * in the bit length tree.
10885 */
10886function scan_tree(s, tree, max_code)
10887//    deflate_state *s;
10888//    ct_data *tree;   /* the tree to be scanned */
10889//    int max_code;    /* and its largest code of non zero frequency */
10890{
10891  var n;                     /* iterates over all tree elements */
10892  var prevlen = -1;          /* last emitted length */
10893  var curlen;                /* length of current code */
10894
10895  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
10896
10897  var count = 0;             /* repeat count of the current code */
10898  var max_count = 7;         /* max repeat count */
10899  var min_count = 4;         /* min repeat count */
10900
10901  if (nextlen === 0) {
10902    max_count = 138;
10903    min_count = 3;
10904  }
10905  tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
10906
10907  for (n = 0; n <= max_code; n++) {
10908    curlen = nextlen;
10909    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
10910
10911    if (++count < max_count && curlen === nextlen) {
10912      continue;
10913
10914    } else if (count < min_count) {
10915      s.bl_tree[curlen * 2]/*.Freq*/ += count;
10916
10917    } else if (curlen !== 0) {
10918
10919      if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
10920      s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
10921
10922    } else if (count <= 10) {
10923      s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
10924
10925    } else {
10926      s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
10927    }
10928
10929    count = 0;
10930    prevlen = curlen;
10931
10932    if (nextlen === 0) {
10933      max_count = 138;
10934      min_count = 3;
10935
10936    } else if (curlen === nextlen) {
10937      max_count = 6;
10938      min_count = 3;
10939
10940    } else {
10941      max_count = 7;
10942      min_count = 4;
10943    }
10944  }
10945}
10946
10947
10948/* ===========================================================================
10949 * Send a literal or distance tree in compressed form, using the codes in
10950 * bl_tree.
10951 */
10952function send_tree(s, tree, max_code)
10953//    deflate_state *s;
10954//    ct_data *tree; /* the tree to be scanned */
10955//    int max_code;       /* and its largest code of non zero frequency */
10956{
10957  var n;                     /* iterates over all tree elements */
10958  var prevlen = -1;          /* last emitted length */
10959  var curlen;                /* length of current code */
10960
10961  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
10962
10963  var count = 0;             /* repeat count of the current code */
10964  var max_count = 7;         /* max repeat count */
10965  var min_count = 4;         /* min repeat count */
10966
10967  /* tree[max_code+1].Len = -1; */  /* guard already set */
10968  if (nextlen === 0) {
10969    max_count = 138;
10970    min_count = 3;
10971  }
10972
10973  for (n = 0; n <= max_code; n++) {
10974    curlen = nextlen;
10975    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
10976
10977    if (++count < max_count && curlen === nextlen) {
10978      continue;
10979
10980    } else if (count < min_count) {
10981      do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
10982
10983    } else if (curlen !== 0) {
10984      if (curlen !== prevlen) {
10985        send_code(s, curlen, s.bl_tree);
10986        count--;
10987      }
10988      //Assert(count >= 3 && count <= 6, " 3_6?");
10989      send_code(s, REP_3_6, s.bl_tree);
10990      send_bits(s, count - 3, 2);
10991
10992    } else if (count <= 10) {
10993      send_code(s, REPZ_3_10, s.bl_tree);
10994      send_bits(s, count - 3, 3);
10995
10996    } else {
10997      send_code(s, REPZ_11_138, s.bl_tree);
10998      send_bits(s, count - 11, 7);
10999    }
11000
11001    count = 0;
11002    prevlen = curlen;
11003    if (nextlen === 0) {
11004      max_count = 138;
11005      min_count = 3;
11006
11007    } else if (curlen === nextlen) {
11008      max_count = 6;
11009      min_count = 3;
11010
11011    } else {
11012      max_count = 7;
11013      min_count = 4;
11014    }
11015  }
11016}
11017
11018
11019/* ===========================================================================
11020 * Construct the Huffman tree for the bit lengths and return the index in
11021 * bl_order of the last bit length code to send.
11022 */
11023function build_bl_tree(s) {
11024  var max_blindex;  /* index of last bit length code of non zero freq */
11025
11026  /* Determine the bit length frequencies for literal and distance trees */
11027  scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
11028  scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
11029
11030  /* Build the bit length tree: */
11031  build_tree(s, s.bl_desc);
11032  /* opt_len now includes the length of the tree representations, except
11033   * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
11034   */
11035
11036  /* Determine the number of bit length codes to send. The pkzip format
11037   * requires that at least 4 bit length codes be sent. (appnote.txt says
11038   * 3 but the actual value used is 4.)
11039   */
11040  for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
11041    if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
11042      break;
11043    }
11044  }
11045  /* Update opt_len to include the bit length tree and counts */
11046  s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
11047  //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
11048  //        s->opt_len, s->static_len));
11049
11050  return max_blindex;
11051}
11052
11053
11054/* ===========================================================================
11055 * Send the header for a block using dynamic Huffman trees: the counts, the
11056 * lengths of the bit length codes, the literal tree and the distance tree.
11057 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
11058 */
11059function send_all_trees(s, lcodes, dcodes, blcodes)
11060//    deflate_state *s;
11061//    int lcodes, dcodes, blcodes; /* number of codes for each tree */
11062{
11063  var rank;                    /* index in bl_order */
11064
11065  //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
11066  //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
11067  //        "too many codes");
11068  //Tracev((stderr, "\nbl counts: "));
11069  send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
11070  send_bits(s, dcodes - 1,   5);
11071  send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
11072  for (rank = 0; rank < blcodes; rank++) {
11073    //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
11074    send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
11075  }
11076  //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
11077
11078  send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
11079  //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
11080
11081  send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
11082  //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
11083}
11084
11085
11086/* ===========================================================================
11087 * Check if the data type is TEXT or BINARY, using the following algorithm:
11088 * - TEXT if the two conditions below are satisfied:
11089 *    a) There are no non-portable control characters belonging to the
11090 *       "black list" (0..6, 14..25, 28..31).
11091 *    b) There is at least one printable character belonging to the
11092 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
11093 * - BINARY otherwise.
11094 * - The following partially-portable control characters form a
11095 *   "gray list" that is ignored in this detection algorithm:
11096 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
11097 * IN assertion: the fields Freq of dyn_ltree are set.
11098 */
11099function detect_data_type(s) {
11100  /* black_mask is the bit mask of black-listed bytes
11101   * set bits 0..6, 14..25, and 28..31
11102   * 0xf3ffc07f = binary 11110011111111111100000001111111
11103   */
11104  var black_mask = 0xf3ffc07f;
11105  var n;
11106
11107  /* Check for non-textual ("black-listed") bytes. */
11108  for (n = 0; n <= 31; n++, black_mask >>>= 1) {
11109    if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
11110      return Z_BINARY;
11111    }
11112  }
11113
11114  /* Check for textual ("white-listed") bytes. */
11115  if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
11116      s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
11117    return Z_TEXT;
11118  }
11119  for (n = 32; n < LITERALS; n++) {
11120    if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
11121      return Z_TEXT;
11122    }
11123  }
11124
11125  /* There are no "black-listed" or "white-listed" bytes:
11126   * this stream either is empty or has tolerated ("gray-listed") bytes only.
11127   */
11128  return Z_BINARY;
11129}
11130
11131
11132var static_init_done = false;
11133
11134/* ===========================================================================
11135 * Initialize the tree data structures for a new zlib stream.
11136 */
11137function _tr_init(s)
11138{
11139
11140  if (!static_init_done) {
11141    tr_static_init();
11142    static_init_done = true;
11143  }
11144
11145  s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
11146  s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
11147  s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
11148
11149  s.bi_buf = 0;
11150  s.bi_valid = 0;
11151
11152  /* Initialize the first block of the first file: */
11153  init_block(s);
11154}
11155
11156
11157/* ===========================================================================
11158 * Send a stored block
11159 */
11160function _tr_stored_block(s, buf, stored_len, last)
11161//DeflateState *s;
11162//charf *buf;       /* input block */
11163//ulg stored_len;   /* length of input block */
11164//int last;         /* one if this is the last block for a file */
11165{
11166  send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
11167  copy_block(s, buf, stored_len, true); /* with header */
11168}
11169
11170
11171/* ===========================================================================
11172 * Send one empty static block to give enough lookahead for inflate.
11173 * This takes 10 bits, of which 7 may remain in the bit buffer.
11174 */
11175function _tr_align(s) {
11176  send_bits(s, STATIC_TREES << 1, 3);
11177  send_code(s, END_BLOCK, static_ltree);
11178  bi_flush(s);
11179}
11180
11181
11182/* ===========================================================================
11183 * Determine the best encoding for the current block: dynamic trees, static
11184 * trees or store, and output the encoded block to the zip file.
11185 */
11186function _tr_flush_block(s, buf, stored_len, last)
11187//DeflateState *s;
11188//charf *buf;       /* input block, or NULL if too old */
11189//ulg stored_len;   /* length of input block */
11190//int last;         /* one if this is the last block for a file */
11191{
11192  var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
11193  var max_blindex = 0;        /* index of last bit length code of non zero freq */
11194
11195  /* Build the Huffman trees unless a stored block is forced */
11196  if (s.level > 0) {
11197
11198    /* Check if the file is binary or text */
11199    if (s.strm.data_type === Z_UNKNOWN) {
11200      s.strm.data_type = detect_data_type(s);
11201    }
11202
11203    /* Construct the literal and distance trees */
11204    build_tree(s, s.l_desc);
11205    // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
11206    //        s->static_len));
11207
11208    build_tree(s, s.d_desc);
11209    // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
11210    //        s->static_len));
11211    /* At this point, opt_len and static_len are the total bit lengths of
11212     * the compressed block data, excluding the tree representations.
11213     */
11214
11215    /* Build the bit length tree for the above two trees, and get the index
11216     * in bl_order of the last bit length code to send.
11217     */
11218    max_blindex = build_bl_tree(s);
11219
11220    /* Determine the best encoding. Compute the block lengths in bytes. */
11221    opt_lenb = (s.opt_len + 3 + 7) >>> 3;
11222    static_lenb = (s.static_len + 3 + 7) >>> 3;
11223
11224    // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
11225    //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
11226    //        s->last_lit));
11227
11228    if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
11229
11230  } else {
11231    // Assert(buf != (char*)0, "lost buf");
11232    opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
11233  }
11234
11235  if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
11236    /* 4: two words for the lengths */
11237
11238    /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
11239     * Otherwise we can't have processed more than WSIZE input bytes since
11240     * the last block flush, because compression would have been
11241     * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
11242     * transform a block into a stored block.
11243     */
11244    _tr_stored_block(s, buf, stored_len, last);
11245
11246  } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
11247
11248    send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
11249    compress_block(s, static_ltree, static_dtree);
11250
11251  } else {
11252    send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
11253    send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
11254    compress_block(s, s.dyn_ltree, s.dyn_dtree);
11255  }
11256  // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
11257  /* The above check is made mod 2^32, for files larger than 512 MB
11258   * and uLong implemented on 32 bits.
11259   */
11260  init_block(s);
11261
11262  if (last) {
11263    bi_windup(s);
11264  }
11265  // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
11266  //       s->compressed_len-7*last));
11267}
11268
11269/* ===========================================================================
11270 * Save the match info and tally the frequency counts. Return true if
11271 * the current block must be flushed.
11272 */
11273function _tr_tally(s, dist, lc)
11274//    deflate_state *s;
11275//    unsigned dist;  /* distance of matched string */
11276//    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
11277{
11278  //var out_length, in_length, dcode;
11279
11280  s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
11281  s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
11282
11283  s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
11284  s.last_lit++;
11285
11286  if (dist === 0) {
11287    /* lc is the unmatched char */
11288    s.dyn_ltree[lc * 2]/*.Freq*/++;
11289  } else {
11290    s.matches++;
11291    /* Here, lc is the match length - MIN_MATCH */
11292    dist--;             /* dist = match distance - 1 */
11293    //Assert((ush)dist < (ush)MAX_DIST(s) &&
11294    //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
11295    //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
11296
11297    s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
11298    s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
11299  }
11300
11301// (!) This block is disabled in zlib defailts,
11302// don't enable it for binary compatibility
11303
11304//#ifdef TRUNCATE_BLOCK
11305//  /* Try to guess if it is profitable to stop the current block here */
11306//  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
11307//    /* Compute an upper bound for the compressed length */
11308//    out_length = s.last_lit*8;
11309//    in_length = s.strstart - s.block_start;
11310//
11311//    for (dcode = 0; dcode < D_CODES; dcode++) {
11312//      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
11313//    }
11314//    out_length >>>= 3;
11315//    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
11316//    //       s->last_lit, in_length, out_length,
11317//    //       100L - out_length*100L/in_length));
11318//    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
11319//      return true;
11320//    }
11321//  }
11322//#endif
11323
11324  return (s.last_lit === s.lit_bufsize - 1);
11325  /* We avoid equality with lit_bufsize because of wraparound at 64K
11326   * on 16 bit machines and because stored blocks are restricted to
11327   * 64K-1 bytes.
11328   */
11329}
11330
11331exports._tr_init  = _tr_init;
11332exports._tr_stored_block = _tr_stored_block;
11333exports._tr_flush_block  = _tr_flush_block;
11334exports._tr_tally = _tr_tally;
11335exports._tr_align = _tr_align;
11336
11337},{"../utils/common":41}],53:[function(require,module,exports){
11338'use strict';
11339
11340// (C) 1995-2013 Jean-loup Gailly and Mark Adler
11341// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
11342//
11343// This software is provided 'as-is', without any express or implied
11344// warranty. In no event will the authors be held liable for any damages
11345// arising from the use of this software.
11346//
11347// Permission is granted to anyone to use this software for any purpose,
11348// including commercial applications, and to alter it and redistribute it
11349// freely, subject to the following restrictions:
11350//
11351// 1. The origin of this software must not be misrepresented; you must not
11352//   claim that you wrote the original software. If you use this software
11353//   in a product, an acknowledgment in the product documentation would be
11354//   appreciated but is not required.
11355// 2. Altered source versions must be plainly marked as such, and must not be
11356//   misrepresented as being the original software.
11357// 3. This notice may not be removed or altered from any source distribution.
11358
11359function ZStream() {
11360  /* next input byte */
11361  this.input = null; // JS specific, because we have no pointers
11362  this.next_in = 0;
11363  /* number of bytes available at input */
11364  this.avail_in = 0;
11365  /* total number of input bytes read so far */
11366  this.total_in = 0;
11367  /* next output byte should be put there */
11368  this.output = null; // JS specific, because we have no pointers
11369  this.next_out = 0;
11370  /* remaining free space at output */
11371  this.avail_out = 0;
11372  /* total number of bytes output so far */
11373  this.total_out = 0;
11374  /* last error message, NULL if no error */
11375  this.msg = ''/*Z_NULL*/;
11376  /* not visible by applications */
11377  this.state = null;
11378  /* best guess about the data type: binary or text */
11379  this.data_type = 2/*Z_UNKNOWN*/;
11380  /* adler32 value of the uncompressed data */
11381  this.adler = 0;
11382}
11383
11384module.exports = ZStream;
11385
11386},{}],54:[function(require,module,exports){
11387(function (global){
11388(function (global, undefined) {
11389    "use strict";
11390
11391    if (global.setImmediate) {
11392        return;
11393    }
11394
11395    var nextHandle = 1; // Spec says greater than zero
11396    var tasksByHandle = {};
11397    var currentlyRunningATask = false;
11398    var doc = global.document;
11399    var registerImmediate;
11400
11401    function setImmediate(callback) {
11402      // Callback can either be a function or a string
11403      if (typeof callback !== "function") {
11404        callback = new Function("" + callback);
11405      }
11406      // Copy function arguments
11407      var args = new Array(arguments.length - 1);
11408      for (var i = 0; i < args.length; i++) {
11409          args[i] = arguments[i + 1];
11410      }
11411      // Store and register the task
11412      var task = { callback: callback, args: args };
11413      tasksByHandle[nextHandle] = task;
11414      registerImmediate(nextHandle);
11415      return nextHandle++;
11416    }
11417
11418    function clearImmediate(handle) {
11419        delete tasksByHandle[handle];
11420    }
11421
11422    function run(task) {
11423        var callback = task.callback;
11424        var args = task.args;
11425        switch (args.length) {
11426        case 0:
11427            callback();
11428            break;
11429        case 1:
11430            callback(args[0]);
11431            break;
11432        case 2:
11433            callback(args[0], args[1]);
11434            break;
11435        case 3:
11436            callback(args[0], args[1], args[2]);
11437            break;
11438        default:
11439            callback.apply(undefined, args);
11440            break;
11441        }
11442    }
11443
11444    function runIfPresent(handle) {
11445        // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
11446        // So if we're currently running a task, we'll need to delay this invocation.
11447        if (currentlyRunningATask) {
11448            // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
11449            // "too much recursion" error.
11450            setTimeout(runIfPresent, 0, handle);
11451        } else {
11452            var task = tasksByHandle[handle];
11453            if (task) {
11454                currentlyRunningATask = true;
11455                try {
11456                    run(task);
11457                } finally {
11458                    clearImmediate(handle);
11459                    currentlyRunningATask = false;
11460                }
11461            }
11462        }
11463    }
11464
11465    function installNextTickImplementation() {
11466        registerImmediate = function(handle) {
11467            process.nextTick(function () { runIfPresent(handle); });
11468        };
11469    }
11470
11471    function canUsePostMessage() {
11472        // The test against `importScripts` prevents this implementation from being installed inside a web worker,
11473        // where `global.postMessage` means something completely different and can't be used for this purpose.
11474        if (global.postMessage && !global.importScripts) {
11475            var postMessageIsAsynchronous = true;
11476            var oldOnMessage = global.onmessage;
11477            global.onmessage = function() {
11478                postMessageIsAsynchronous = false;
11479            };
11480            global.postMessage("", "*");
11481            global.onmessage = oldOnMessage;
11482            return postMessageIsAsynchronous;
11483        }
11484    }
11485
11486    function installPostMessageImplementation() {
11487        // Installs an event handler on `global` for the `message` event: see
11488        // * https://developer.mozilla.org/en/DOM/window.postMessage
11489        // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
11490
11491        var messagePrefix = "setImmediate$" + Math.random() + "$";
11492        var onGlobalMessage = function(event) {
11493            if (event.source === global &&
11494                typeof event.data === "string" &&
11495                event.data.indexOf(messagePrefix) === 0) {
11496                runIfPresent(+event.data.slice(messagePrefix.length));
11497            }
11498        };
11499
11500        if (global.addEventListener) {
11501            global.addEventListener("message", onGlobalMessage, false);
11502        } else {
11503            global.attachEvent("onmessage", onGlobalMessage);
11504        }
11505
11506        registerImmediate = function(handle) {
11507            global.postMessage(messagePrefix + handle, "*");
11508        };
11509    }
11510
11511    function installMessageChannelImplementation() {
11512        var channel = new MessageChannel();
11513        channel.port1.onmessage = function(event) {
11514            var handle = event.data;
11515            runIfPresent(handle);
11516        };
11517
11518        registerImmediate = function(handle) {
11519            channel.port2.postMessage(handle);
11520        };
11521    }
11522
11523    function installReadyStateChangeImplementation() {
11524        var html = doc.documentElement;
11525        registerImmediate = function(handle) {
11526            // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
11527            // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
11528            var script = doc.createElement("script");
11529            script.onreadystatechange = function () {
11530                runIfPresent(handle);
11531                script.onreadystatechange = null;
11532                html.removeChild(script);
11533                script = null;
11534            };
11535            html.appendChild(script);
11536        };
11537    }
11538
11539    function installSetTimeoutImplementation() {
11540        registerImmediate = function(handle) {
11541            setTimeout(runIfPresent, 0, handle);
11542        };
11543    }
11544
11545    // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
11546    var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
11547    attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
11548
11549    // Don't get fooled by e.g. browserify environments.
11550    if ({}.toString.call(global.process) === "[object process]") {
11551        // For Node.js before 0.9
11552        installNextTickImplementation();
11553
11554    } else if (canUsePostMessage()) {
11555        // For non-IE10 modern browsers
11556        installPostMessageImplementation();
11557
11558    } else if (global.MessageChannel) {
11559        // For web workers, where supported
11560        installMessageChannelImplementation();
11561
11562    } else if (doc && "onreadystatechange" in doc.createElement("script")) {
11563        // For IE 6–8
11564        installReadyStateChangeImplementation();
11565
11566    } else {
11567        // For older browsers
11568        installSetTimeoutImplementation();
11569    }
11570
11571    attachTo.setImmediate = setImmediate;
11572    attachTo.clearImmediate = clearImmediate;
11573}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
11574
11575}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11576},{}]},{},[10])(10)
11577});