Guest User

teste

a guest
Jun 27th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*!
  2.  
  3. JSZip v3.1.3 - 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>
  7. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  8.  
  9. JSZip uses the library pako released under the MIT license :
  10. https://github.com/nodeca/pako/blob/master/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';
  15. var utils = require('./utils');
  16. var support = require('./support');
  17. // private property
  18. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  19.  
  20.  
  21. // public method for encoding
  22. exports.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
  54. exports.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.  
  124. var external = require("./external");
  125. var DataWorker = require('./stream/DataWorker');
  126. var DataLengthProbe = require('./stream/DataLengthProbe');
  127. var Crc32Probe = require('./stream/Crc32Probe');
  128. var DataLengthProbe = require('./stream/DataLengthProbe');
  129.  
  130. /**
  131.  * Represent a compressed object, with everything needed to decompress it.
  132.  * @constructor
  133.  * @param {number} compressedSize the size of the data compressed.
  134.  * @param {number} uncompressedSize the size of the data after decompression.
  135.  * @param {number} crc32 the crc32 of the decompressed file.
  136.  * @param {object} compression the type of compression, see lib/compressions.js.
  137.  * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
  138.  */
  139. function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
  140.     this.compressedSize = compressedSize;
  141.     this.uncompressedSize = uncompressedSize;
  142.     this.crc32 = crc32;
  143.     this.compression = compression;
  144.     this.compressedContent = data;
  145. }
  146.  
  147. CompressedObject.prototype = {
  148.     /**
  149.      * Create a worker to get the uncompressed content.
  150.      * @return {GenericWorker} the worker.
  151.      */
  152.     getContentWorker : function () {
  153.         var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
  154.         .pipe(this.compression.uncompressWorker())
  155.         .pipe(new DataLengthProbe("data_length"));
  156.  
  157.         var that = this;
  158.         worker.on("end", function () {
  159.             if(this.streamInfo['data_length'] !== that.uncompressedSize) {
  160.                 throw new Error("Bug : uncompressed data size mismatch");
  161.             }
  162.         });
  163.         return worker;
  164.     },
  165.     /**
  166.      * Create a worker to get the compressed content.
  167.      * @return {GenericWorker} the worker.
  168.      */
  169.     getCompressedWorker : function () {
  170.         return new DataWorker(external.Promise.resolve(this.compressedContent))
  171.         .withStreamInfo("compressedSize", this.compressedSize)
  172.         .withStreamInfo("uncompressedSize", this.uncompressedSize)
  173.         .withStreamInfo("crc32", this.crc32)
  174.         .withStreamInfo("compression", this.compression)
  175.         ;
  176.     }
  177. };
  178.  
  179. /**
  180.  * Chain the given worker with other workers to compress the content with the
  181.  * given compresion.
  182.  * @param {GenericWorker} uncompressedWorker the worker to pipe.
  183.  * @param {Object} compression the compression object.
  184.  * @param {Object} compressionOptions the options to use when compressing.
  185.  * @return {GenericWorker} the new worker compressing the content.
  186.  */
  187. CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
  188.     return uncompressedWorker
  189.     .pipe(new Crc32Probe())
  190.     .pipe(new DataLengthProbe("uncompressedSize"))
  191.     .pipe(compression.compressWorker(compressionOptions))
  192.     .pipe(new DataLengthProbe("compressedSize"))
  193.     .withStreamInfo("compression", compression);
  194. };
  195.  
  196. module.exports = CompressedObject;
  197.  
  198. },{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){
  199. 'use strict';
  200.  
  201. var GenericWorker = require("./stream/GenericWorker");
  202.  
  203. exports.STORE = {
  204.     magic: "\x00\x00",
  205.     compressWorker : function (compressionOptions) {
  206.         return new GenericWorker("STORE compression");
  207.     },
  208.     uncompressWorker : function () {
  209.         return new GenericWorker("STORE decompression");
  210.     }
  211. };
  212. exports.DEFLATE = require('./flate');
  213.  
  214. },{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){
  215. 'use strict';
  216.  
  217. var utils = require('./utils');
  218.  
  219. /**
  220.  * The following functions come from pako, from pako/lib/zlib/crc32.js
  221.  * released under the MIT license, see pako https://github.com/nodeca/pako/
  222.  */
  223.  
  224. // Use ordinary array, since untyped makes no boost here
  225. function makeTable() {
  226.     var c, table = [];
  227.  
  228.     for(var n =0; n < 256; n++){
  229.         c = n;
  230.         for(var k =0; k < 8; k++){
  231.             c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  232.         }
  233.         table[n] = c;
  234.     }
  235.  
  236.     return table;
  237. }
  238.  
  239. // Create table on load. Just 255 signed longs. Not a problem.
  240. var crcTable = makeTable();
  241.  
  242.  
  243. function crc32(crc, buf, len, pos) {
  244.     var t = crcTable, end = pos + len;
  245.  
  246.     crc = crc ^ (-1);
  247.  
  248.     for (var i = pos; i < end; i++ ) {
  249.         crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  250.     }
  251.  
  252.     return (crc ^ (-1)); // >>> 0;
  253. }
  254.  
  255. // That's all for the pako functions.
  256.  
  257. /**
  258.  * Compute the crc32 of a string.
  259.  * This is almost the same as the function crc32, but for strings. Using the
  260.  * same function for the two use cases leads to horrible performances.
  261.  * @param {Number} crc the starting value of the crc.
  262.  * @param {String} str the string to use.
  263.  * @param {Number} len the length of the string.
  264.  * @param {Number} pos the starting position for the crc32 computation.
  265.  * @return {Number} the computed crc32.
  266.  */
  267. function crc32str(crc, str, len, pos) {
  268.     var t = crcTable, end = pos + len;
  269.  
  270.     crc = crc ^ (-1);
  271.  
  272.     for (var i = pos; i < end; i++ ) {
  273.         crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
  274.     }
  275.  
  276.     return (crc ^ (-1)); // >>> 0;
  277. }
  278.  
  279. module.exports = function crc32wrapper(input, crc) {
  280.     if (typeof input === "undefined" || !input.length) {
  281.         return 0;
  282.     }
  283.  
  284.     var isArray = utils.getTypeOf(input) !== "string";
  285.  
  286.     if(isArray) {
  287.         return crc32(crc|0, input, input.length, 0);
  288.     } else {
  289.         return crc32str(crc|0, input, input.length, 0);
  290.     }
  291. };
  292. // vim: set shiftwidth=4 softtabstop=4:
  293.  
  294. },{"./utils":32}],5:[function(require,module,exports){
  295. 'use strict';
  296. exports.base64 = false;
  297. exports.binary = false;
  298. exports.dir = false;
  299. exports.createFolders = true;
  300. exports.date = null;
  301. exports.compression = null;
  302. exports.compressionOptions = null;
  303. exports.comment = null;
  304. exports.unixPermissions = null;
  305. exports.dosPermissions = null;
  306.  
  307. },{}],6:[function(require,module,exports){
  308. /* global Promise */
  309. 'use strict';
  310.  
  311. // load the global object first:
  312. // - it should be better integrated in the system (unhandledRejection in node)
  313. // - the environment may have a custom Promise implementation (see zone.js)
  314. var ES6Promise = null;
  315. if (typeof Promise !== "undefined") {
  316.     ES6Promise = Promise;
  317. } else {
  318.     ES6Promise = require("lie");
  319. }
  320.  
  321. /**
  322.  * Let the user use/change some implementations.
  323.  */
  324. module.exports = {
  325.     Promise: ES6Promise
  326. };
  327.  
  328. },{"lie":58}],7:[function(require,module,exports){
  329. 'use strict';
  330. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  331.  
  332. var pako = require("pako");
  333. var utils = require("./utils");
  334. var GenericWorker = require("./stream/GenericWorker");
  335.  
  336. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  337.  
  338. exports.magic = "\x08\x00";
  339.  
  340. /**
  341.  * Create a worker that uses pako to inflate/deflate.
  342.  * @constructor
  343.  * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  344.  * @param {Object} options the options to use when (de)compressing.
  345.  */
  346. function FlateWorker(action, options) {
  347.     GenericWorker.call(this, "FlateWorker/" + action);
  348.  
  349.     this._pako = new pako[action]({
  350.         raw:true,
  351.         level : options.level || -1 // default compression
  352.     });
  353.     // the `meta` object from the last chunk received
  354.     // this allow this worker to pass around metadata
  355.     this.meta = {};
  356.  
  357.     var self = this;
  358.     this._pako.onData = function(data) {
  359.         self.push({
  360.             data : data,
  361.             meta : self.meta
  362.         });
  363.     };
  364. }
  365.  
  366. utils.inherits(FlateWorker, GenericWorker);
  367.  
  368. /**
  369.  * @see GenericWorker.processChunk
  370.  */
  371. FlateWorker.prototype.processChunk = function (chunk) {
  372.     this.meta = chunk.meta;
  373.     this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  374. };
  375.  
  376. /**
  377.  * @see GenericWorker.flush
  378.  */
  379. FlateWorker.prototype.flush = function () {
  380.     GenericWorker.prototype.flush.call(this);
  381.     this._pako.push([], true);
  382. };
  383. /**
  384.  * @see GenericWorker.cleanUp
  385.  */
  386. FlateWorker.prototype.cleanUp = function () {
  387.     GenericWorker.prototype.cleanUp.call(this);
  388.     this._pako = null;
  389. };
  390.  
  391. exports.compressWorker = function (compressionOptions) {
  392.     return new FlateWorker("Deflate", compressionOptions);
  393. };
  394. exports.uncompressWorker = function () {
  395.     return new FlateWorker("Inflate", {});
  396. };
  397.  
  398. },{"./stream/GenericWorker":28,"./utils":32,"pako":59}],8:[function(require,module,exports){
  399. 'use strict';
  400.  
  401. var utils = require('../utils');
  402. var GenericWorker = require('../stream/GenericWorker');
  403. var utf8 = require('../utf8');
  404. var crc32 = require('../crc32');
  405. var signature = require('../signature');
  406.  
  407. /**
  408.  * Transform an integer into a string in hexadecimal.
  409.  * @private
  410.  * @param {number} dec the number to convert.
  411.  * @param {number} bytes the number of bytes to generate.
  412.  * @returns {string} the result.
  413.  */
  414. var decToHex = function(dec, bytes) {
  415.     var hex = "", i;
  416.     for (i = 0; i < bytes; i++) {
  417.         hex += String.fromCharCode(dec & 0xff);
  418.         dec = dec >>> 8;
  419.     }
  420.     return hex;
  421. };
  422.  
  423. /**
  424.  * Generate the UNIX part of the external file attributes.
  425.  * @param {Object} unixPermissions the unix permissions or null.
  426.  * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  427.  * @return {Number} a 32 bit integer.
  428.  *
  429.  * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  430.  *
  431.  * TTTTsstrwxrwxrwx0000000000ADVSHR
  432.  * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  433.  *     ^^^_________________________ setuid, setgid, sticky
  434.  *        ^^^^^^^^^________________ permissions
  435.  *                 ^^^^^^^^^^______ not used ?
  436.  *                           ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  437.  */
  438. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  439.  
  440.     var result = unixPermissions;
  441.     if (!unixPermissions) {
  442.         // I can't use octal values in strict mode, hence the hexa.
  443.         //  040775 => 0x41fd
  444.         // 0100664 => 0x81b4
  445.         result = isDir ? 0x41fd : 0x81b4;
  446.     }
  447.     return (result & 0xFFFF) << 16;
  448. };
  449.  
  450. /**
  451.  * Generate the DOS part of the external file attributes.
  452.  * @param {Object} dosPermissions the dos permissions or null.
  453.  * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  454.  * @return {Number} a 32 bit integer.
  455.  *
  456.  * Bit 0     Read-Only
  457.  * Bit 1     Hidden
  458.  * Bit 2     System
  459.  * Bit 3     Volume Label
  460.  * Bit 4     Directory
  461.  * Bit 5     Archive
  462.  */
  463. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  464.  
  465.     // the dir flag is already set for compatibility
  466.     return (dosPermissions || 0)  & 0x3F;
  467. };
  468.  
  469. /**
  470.  * Generate the various parts used in the construction of the final zip file.
  471.  * @param {Object} streamInfo the hash with informations about the compressed file.
  472.  * @param {Boolean} streamedContent is the content streamed ?
  473.  * @param {Boolean} streamingEnded is the stream finished ?
  474.  * @param {number} offset the current offset from the start of the zip file.
  475.  * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  476.  * @param {Function} encodeFileName the function to encode the file name / comment.
  477.  * @return {Object} the zip parts.
  478.  */
  479. var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
  480.     var file = streamInfo['file'],
  481.     compression = streamInfo['compression'],
  482.     useCustomEncoding = encodeFileName !== utf8.utf8encode,
  483.     encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  484.     utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  485.     comment = file.comment,
  486.     encodedComment = utils.transformTo("string", encodeFileName(comment)),
  487.     utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  488.     useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  489.     useUTF8ForComment = utfEncodedComment.length !== comment.length,
  490.     dosTime,
  491.     dosDate,
  492.     extraFields = "",
  493.     unicodePathExtraField = "",
  494.     unicodeCommentExtraField = "",
  495.     dir = file.dir,
  496.     date = file.date;
  497.  
  498.  
  499.     var dataInfo = {
  500.         crc32 : 0,
  501.         compressedSize : 0,
  502.         uncompressedSize : 0
  503.     };
  504.  
  505.     // if the content is streamed, the sizes/crc32 are only available AFTER
  506.     // the end of the stream.
  507.     if (!streamedContent || streamingEnded) {
  508.         dataInfo.crc32 = streamInfo['crc32'];
  509.         dataInfo.compressedSize = streamInfo['compressedSize'];
  510.         dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
  511.     }
  512.  
  513.     var bitflag = 0;
  514.     if (streamedContent) {
  515.         // Bit 3: the sizes/crc32 are set to zero in the local header.
  516.         // The correct values are put in the data descriptor immediately
  517.         // following the compressed data.
  518.         bitflag |= 0x0008;
  519.     }
  520.     if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
  521.         // Bit 11: Language encoding flag (EFS).
  522.         bitflag |= 0x0800;
  523.     }
  524.  
  525.  
  526.     var extFileAttr = 0;
  527.     var versionMadeBy = 0;
  528.     if (dir) {
  529.         // dos or unix, we set the dos dir flag
  530.         extFileAttr |= 0x00010;
  531.     }
  532.     if(platform === "UNIX") {
  533.         versionMadeBy = 0x031E; // UNIX, version 3.0
  534.         extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  535.     } else { // DOS or other, fallback to DOS
  536.         versionMadeBy = 0x0014; // DOS, version 2.0
  537.         extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  538.     }
  539.  
  540.     // date
  541.     // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  542.     // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  543.     // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  544.  
  545.     dosTime = date.getUTCHours();
  546.     dosTime = dosTime << 6;
  547.     dosTime = dosTime | date.getUTCMinutes();
  548.     dosTime = dosTime << 5;
  549.     dosTime = dosTime | date.getUTCSeconds() / 2;
  550.  
  551.     dosDate = date.getUTCFullYear() - 1980;
  552.     dosDate = dosDate << 4;
  553.     dosDate = dosDate | (date.getUTCMonth() + 1);
  554.     dosDate = dosDate << 5;
  555.     dosDate = dosDate | date.getUTCDate();
  556.  
  557.     if (useUTF8ForFileName) {
  558.         // set the unicode path extra field. unzip needs at least one extra
  559.         // field to correctly handle unicode path, so using the path is as good
  560.         // as any other information. This could improve the situation with
  561.         // other archive managers too.
  562.         // This field is usually used without the utf8 flag, with a non
  563.         // unicode path in the header (winrar, winzip). This helps (a bit)
  564.         // with the messy Windows' default compressed folders feature but
  565.         // breaks on p7zip which doesn't seek the unicode path extra field.
  566.         // So for now, UTF-8 everywhere !
  567.         unicodePathExtraField =
  568.             // Version
  569.             decToHex(1, 1) +
  570.             // NameCRC32
  571.             decToHex(crc32(encodedFileName), 4) +
  572.             // UnicodeName
  573.             utfEncodedFileName;
  574.  
  575.         extraFields +=
  576.             // Info-ZIP Unicode Path Extra Field
  577.             "\x75\x70" +
  578.             // size
  579.             decToHex(unicodePathExtraField.length, 2) +
  580.             // content
  581.             unicodePathExtraField;
  582.     }
  583.  
  584.     if(useUTF8ForComment) {
  585.  
  586.         unicodeCommentExtraField =
  587.             // Version
  588.             decToHex(1, 1) +
  589.             // CommentCRC32
  590.             decToHex(crc32(encodedComment), 4) +
  591.             // UnicodeName
  592.             utfEncodedComment;
  593.  
  594.         extraFields +=
  595.             // Info-ZIP Unicode Path Extra Field
  596.             "\x75\x63" +
  597.             // size
  598.             decToHex(unicodeCommentExtraField.length, 2) +
  599.             // content
  600.             unicodeCommentExtraField;
  601.     }
  602.  
  603.     var header = "";
  604.  
  605.     // version needed to extract
  606.     header += "\x0A\x00";
  607.     // general purpose bit flag
  608.     header += decToHex(bitflag, 2);
  609.     // compression method
  610.     header += compression.magic;
  611.     // last mod file time
  612.     header += decToHex(dosTime, 2);
  613.     // last mod file date
  614.     header += decToHex(dosDate, 2);
  615.     // crc-32
  616.     header += decToHex(dataInfo.crc32, 4);
  617.     // compressed size
  618.     header += decToHex(dataInfo.compressedSize, 4);
  619.     // uncompressed size
  620.     header += decToHex(dataInfo.uncompressedSize, 4);
  621.     // file name length
  622.     header += decToHex(encodedFileName.length, 2);
  623.     // extra field length
  624.     header += decToHex(extraFields.length, 2);
  625.  
  626.  
  627.     var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  628.  
  629.     var dirRecord = signature.CENTRAL_FILE_HEADER +
  630.         // version made by (00: DOS)
  631.         decToHex(versionMadeBy, 2) +
  632.         // file header (common to file and central directory)
  633.         header +
  634.         // file comment length
  635.         decToHex(encodedComment.length, 2) +
  636.         // disk number start
  637.         "\x00\x00" +
  638.         // internal file attributes TODO
  639.         "\x00\x00" +
  640.         // external file attributes
  641.         decToHex(extFileAttr, 4) +
  642.         // relative offset of local header
  643.         decToHex(offset, 4) +
  644.         // file name
  645.         encodedFileName +
  646.         // extra field
  647.         extraFields +
  648.         // file comment
  649.         encodedComment;
  650.  
  651.     return {
  652.         fileRecord: fileRecord,
  653.         dirRecord: dirRecord
  654.     };
  655. };
  656.  
  657. /**
  658.  * Generate the EOCD record.
  659.  * @param {Number} entriesCount the number of entries in the zip file.
  660.  * @param {Number} centralDirLength the length (in bytes) of the central dir.
  661.  * @param {Number} localDirLength the length (in bytes) of the local dir.
  662.  * @param {String} comment the zip file comment as a binary string.
  663.  * @param {Function} encodeFileName the function to encode the comment.
  664.  * @return {String} the EOCD record.
  665.  */
  666. var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
  667.     var dirEnd = "";
  668.     var encodedComment = utils.transformTo("string", encodeFileName(comment));
  669.  
  670.     // end of central dir signature
  671.     dirEnd = signature.CENTRAL_DIRECTORY_END +
  672.         // number of this disk
  673.         "\x00\x00" +
  674.         // number of the disk with the start of the central directory
  675.         "\x00\x00" +
  676.         // total number of entries in the central directory on this disk
  677.         decToHex(entriesCount, 2) +
  678.         // total number of entries in the central directory
  679.         decToHex(entriesCount, 2) +
  680.         // size of the central directory   4 bytes
  681.         decToHex(centralDirLength, 4) +
  682.         // offset of start of central directory with respect to the starting disk number
  683.         decToHex(localDirLength, 4) +
  684.         // .ZIP file comment length
  685.         decToHex(encodedComment.length, 2) +
  686.         // .ZIP file comment
  687.         encodedComment;
  688.  
  689.     return dirEnd;
  690. };
  691.  
  692. /**
  693.  * Generate data descriptors for a file entry.
  694.  * @param {Object} streamInfo the hash generated by a worker, containing informations
  695.  * on the file entry.
  696.  * @return {String} the data descriptors.
  697.  */
  698. var generateDataDescriptors = function (streamInfo) {
  699.     var descriptor = "";
  700.     descriptor = signature.DATA_DESCRIPTOR +
  701.         // crc-32                          4 bytes
  702.         decToHex(streamInfo['crc32'], 4) +
  703.         // compressed size                 4 bytes
  704.         decToHex(streamInfo['compressedSize'], 4) +
  705.         // uncompressed size               4 bytes
  706.         decToHex(streamInfo['uncompressedSize'], 4);
  707.  
  708.     return descriptor;
  709. };
  710.  
  711.  
  712. /**
  713.  * A worker to concatenate other workers to create a zip file.
  714.  * @param {Boolean} streamFiles `true` to stream the content of the files,
  715.  * `false` to accumulate it.
  716.  * @param {String} comment the comment to use.
  717.  * @param {String} platform the platform to use, "UNIX" or "DOS".
  718.  * @param {Function} encodeFileName the function to encode file names and comments.
  719.  */
  720. function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
  721.     GenericWorker.call(this, "ZipFileWorker");
  722.     // The number of bytes written so far. This doesn't count accumulated chunks.
  723.     this.bytesWritten = 0;
  724.     // The comment of the zip file
  725.     this.zipComment = comment;
  726.     // The platform "generating" the zip file.
  727.     this.zipPlatform = platform;
  728.     // the function to encode file names and comments.
  729.     this.encodeFileName = encodeFileName;
  730.     // Should we stream the content of the files ?
  731.     this.streamFiles = streamFiles;
  732.     // If `streamFiles` is false, we will need to accumulate the content of the
  733.     // files to calculate sizes / crc32 (and write them *before* the content).
  734.     // This boolean indicates if we are accumulating chunks (it will change a lot
  735.     // during the lifetime of this worker).
  736.     this.accumulate = false;
  737.     // The buffer receiving chunks when accumulating content.
  738.     this.contentBuffer = [];
  739.     // The list of generated directory records.
  740.     this.dirRecords = [];
  741.     // The offset (in bytes) from the beginning of the zip file for the current source.
  742.     this.currentSourceOffset = 0;
  743.     // The total number of entries in this zip file.
  744.     this.entriesCount = 0;
  745.     // the name of the file currently being added, null when handling the end of the zip file.
  746.     // Used for the emited metadata.
  747.     this.currentFile = null;
  748.  
  749.  
  750.  
  751.     this._sources = [];
  752. }
  753. utils.inherits(ZipFileWorker, GenericWorker);
  754.  
  755. /**
  756.  * @see GenericWorker.push
  757.  */
  758. ZipFileWorker.prototype.push = function (chunk) {
  759.  
  760.     var currentFilePercent = chunk.meta.percent || 0;
  761.     var entriesCount = this.entriesCount;
  762.     var remainingFiles = this._sources.length;
  763.  
  764.     if(this.accumulate) {
  765.         this.contentBuffer.push(chunk);
  766.     } else {
  767.         this.bytesWritten += chunk.data.length;
  768.  
  769.         GenericWorker.prototype.push.call(this, {
  770.             data : chunk.data,
  771.             meta : {
  772.                 currentFile : this.currentFile,
  773.                 percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
  774.             }
  775.         });
  776.     }
  777. };
  778.  
  779. /**
  780.  * The worker started a new source (an other worker).
  781.  * @param {Object} streamInfo the streamInfo object from the new source.
  782.  */
  783. ZipFileWorker.prototype.openedSource = function (streamInfo) {
  784.     this.currentSourceOffset = this.bytesWritten;
  785.     this.currentFile = streamInfo['file'].name;
  786.  
  787.     var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  788.  
  789.     // don't stream folders (because they don't have any content)
  790.     if(streamedContent) {
  791.         var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  792.         this.push({
  793.             data : record.fileRecord,
  794.             meta : {percent:0}
  795.         });
  796.     } else {
  797.         // we need to wait for the whole file before pushing anything
  798.         this.accumulate = true;
  799.     }
  800. };
  801.  
  802. /**
  803.  * The worker finished a source (an other worker).
  804.  * @param {Object} streamInfo the streamInfo object from the finished source.
  805.  */
  806. ZipFileWorker.prototype.closedSource = function (streamInfo) {
  807.     this.accumulate = false;
  808.     var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  809.     var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  810.  
  811.     this.dirRecords.push(record.dirRecord);
  812.     if(streamedContent) {
  813.         // after the streamed file, we put data descriptors
  814.         this.push({
  815.             data : generateDataDescriptors(streamInfo),
  816.             meta : {percent:100}
  817.         });
  818.     } else {
  819.         // the content wasn't streamed, we need to push everything now
  820.         // first the file record, then the content
  821.         this.push({
  822.             data : record.fileRecord,
  823.             meta : {percent:0}
  824.         });
  825.         while(this.contentBuffer.length) {
  826.             this.push(this.contentBuffer.shift());
  827.         }
  828.     }
  829.     this.currentFile = null;
  830. };
  831.  
  832. /**
  833.  * @see GenericWorker.flush
  834.  */
  835. ZipFileWorker.prototype.flush = function () {
  836.  
  837.     var localDirLength = this.bytesWritten;
  838.     for(var i = 0; i < this.dirRecords.length; i++) {
  839.         this.push({
  840.             data : this.dirRecords[i],
  841.             meta : {percent:100}
  842.         });
  843.     }
  844.     var centralDirLength = this.bytesWritten - localDirLength;
  845.  
  846.     var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
  847.  
  848.     this.push({
  849.         data : dirEnd,
  850.         meta : {percent:100}
  851.     });
  852. };
  853.  
  854. /**
  855.  * Prepare the next source to be read.
  856.  */
  857. ZipFileWorker.prototype.prepareNextSource = function () {
  858.     this.previous = this._sources.shift();
  859.     this.openedSource(this.previous.streamInfo);
  860.     if (this.isPaused) {
  861.         this.previous.pause();
  862.     } else {
  863.         this.previous.resume();
  864.     }
  865. };
  866.  
  867. /**
  868.  * @see GenericWorker.registerPrevious
  869.  */
  870. ZipFileWorker.prototype.registerPrevious = function (previous) {
  871.     this._sources.push(previous);
  872.     var self = this;
  873.  
  874.     previous.on('data', function (chunk) {
  875.         self.processChunk(chunk);
  876.     });
  877.     previous.on('end', function () {
  878.         self.closedSource(self.previous.streamInfo);
  879.         if(self._sources.length) {
  880.             self.prepareNextSource();
  881.         } else {
  882.             self.end();
  883.         }
  884.     });
  885.     previous.on('error', function (e) {
  886.         self.error(e);
  887.     });
  888.     return this;
  889. };
  890.  
  891. /**
  892.  * @see GenericWorker.resume
  893.  */
  894. ZipFileWorker.prototype.resume = function () {
  895.     if(!GenericWorker.prototype.resume.call(this)) {
  896.         return false;
  897.     }
  898.  
  899.     if (!this.previous && this._sources.length) {
  900.         this.prepareNextSource();
  901.         return true;
  902.     }
  903.     if (!this.previous && !this._sources.length && !this.generatedError) {
  904.         this.end();
  905.         return true;
  906.     }
  907. };
  908.  
  909. /**
  910.  * @see GenericWorker.error
  911.  */
  912. ZipFileWorker.prototype.error = function (e) {
  913.     var sources = this._sources;
  914.     if(!GenericWorker.prototype.error.call(this, e)) {
  915.         return false;
  916.     }
  917.     for(var i = 0; i < sources.length; i++) {
  918.         try {
  919.             sources[i].error(e);
  920.         } catch(e) {
  921.             // the `error` exploded, nothing to do
  922.         }
  923.     }
  924.     return true;
  925. };
  926.  
  927. /**
  928.  * @see GenericWorker.lock
  929.  */
  930. ZipFileWorker.prototype.lock = function () {
  931.     GenericWorker.prototype.lock.call(this);
  932.     var sources = this._sources;
  933.     for(var i = 0; i < sources.length; i++) {
  934.         sources[i].lock();
  935.     }
  936. };
  937.  
  938. module.exports = ZipFileWorker;
  939.  
  940. },{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
  941. 'use strict';
  942.  
  943. var compressions = require('../compressions');
  944. var ZipFileWorker = require('./ZipFileWorker');
  945.  
  946. /**
  947.  * Find the compression to use.
  948.  * @param {String} fileCompression the compression defined at the file level, if any.
  949.  * @param {String} zipCompression the compression defined at the load() level.
  950.  * @return {Object} the compression object to use.
  951.  */
  952. var getCompression = function (fileCompression, zipCompression) {
  953.  
  954.     var compressionName = fileCompression || zipCompression;
  955.     var compression = compressions[compressionName];
  956.     if (!compression) {
  957.         throw new Error(compressionName + " is not a valid compression method !");
  958.     }
  959.     return compression;
  960. };
  961.  
  962. /**
  963.  * Create a worker to generate a zip file.
  964.  * @param {JSZip} zip the JSZip instance at the right root level.
  965.  * @param {Object} options to generate the zip file.
  966.  * @param {String} comment the comment to use.
  967.  */
  968. exports.generateWorker = function (zip, options, comment) {
  969.  
  970.     var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
  971.     var entriesCount = 0;
  972.     try {
  973.  
  974.         zip.forEach(function (relativePath, file) {
  975.             entriesCount++;
  976.             var compression = getCompression(file.options.compression, options.compression);
  977.             var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  978.             var dir = file.dir, date = file.date;
  979.  
  980.             file._compressWorker(compression, compressionOptions)
  981.             .withStreamInfo("file", {
  982.                 name : relativePath,
  983.                 dir : dir,
  984.                 date : date,
  985.                 comment : file.comment || "",
  986.                 unixPermissions : file.unixPermissions,
  987.                 dosPermissions : file.dosPermissions
  988.             })
  989.             .pipe(zipFileWorker);
  990.         });
  991.         zipFileWorker.entriesCount = entriesCount;
  992.     } catch (e) {
  993.         zipFileWorker.error(e);
  994.     }
  995.  
  996.     return zipFileWorker;
  997. };
  998.  
  999. },{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
  1000. 'use strict';
  1001.  
  1002. /**
  1003.  * Representation a of zip file in js
  1004.  * @constructor
  1005.  */
  1006. function JSZip() {
  1007.     // if this constructor is used without `new`, it adds `new` before itself:
  1008.     if(!(this instanceof JSZip)) {
  1009.         return new JSZip();
  1010.     }
  1011.  
  1012.     if(arguments.length) {
  1013.         throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  1014.     }
  1015.  
  1016.     // object containing the files :
  1017.     // {
  1018.     //   "folder/" : {...},
  1019.     //   "folder/data.txt" : {...}
  1020.     // }
  1021.     this.files = {};
  1022.  
  1023.     this.comment = null;
  1024.  
  1025.     // Where we are in the hierarchy
  1026.     this.root = "";
  1027.     this.clone = function() {
  1028.         var newObj = new JSZip();
  1029.         for (var i in this) {
  1030.             if (typeof this[i] !== "function") {
  1031.                 newObj[i] = this[i];
  1032.             }
  1033.         }
  1034.         return newObj;
  1035.     };
  1036. }
  1037. JSZip.prototype = require('./object');
  1038. JSZip.prototype.loadAsync = require('./load');
  1039. JSZip.support = require('./support');
  1040. JSZip.defaults = require('./defaults');
  1041.  
  1042. // TODO find a better way to handle this version,
  1043. // a require('package.json').version doesn't work with webpack, see #327
  1044. JSZip.version = "3.1.3";
  1045.  
  1046. JSZip.loadAsync = function (content, options) {
  1047.     return new JSZip().loadAsync(content, options);
  1048. };
  1049.  
  1050. JSZip.external = require("./external");
  1051. module.exports = JSZip;
  1052.  
  1053. },{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
  1054. 'use strict';
  1055. var utils = require('./utils');
  1056. var external = require("./external");
  1057. var utf8 = require('./utf8');
  1058. var utils = require('./utils');
  1059. var ZipEntries = require('./zipEntries');
  1060. var Crc32Probe = require('./stream/Crc32Probe');
  1061. var nodejsUtils = require("./nodejsUtils");
  1062.  
  1063. /**
  1064.  * Check the CRC32 of an entry.
  1065.  * @param {ZipEntry} zipEntry the zip entry to check.
  1066.  * @return {Promise} the result.
  1067.  */
  1068. function checkEntryCRC32(zipEntry) {
  1069.     return new external.Promise(function (resolve, reject) {
  1070.         var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  1071.         worker.on("error", function (e) {
  1072.             reject(e);
  1073.         })
  1074.         .on("end", function () {
  1075.             if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  1076.                 reject(new Error("Corrupted zip : CRC32 mismatch"));
  1077.             } else {
  1078.                 resolve();
  1079.             }
  1080.         })
  1081.         .resume();
  1082.     });
  1083. }
  1084.  
  1085. module.exports = function(data, options) {
  1086.     var zip = this;
  1087.     options = utils.extend(options || {}, {
  1088.         base64: false,
  1089.         checkCRC32: false,
  1090.         optimizedBinaryString: false,
  1091.         createFolders: false,
  1092.         decodeFileName: utf8.utf8decode
  1093.     });
  1094.  
  1095.     if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1096.         return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  1097.     }
  1098.  
  1099.     return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  1100.     .then(function(data) {
  1101.         var zipEntries = new ZipEntries(options);
  1102.         zipEntries.load(data);
  1103.         return zipEntries;
  1104.     }).then(function checkCRC32(zipEntries) {
  1105.         var promises = [external.Promise.resolve(zipEntries)];
  1106.         var files = zipEntries.files;
  1107.         if (options.checkCRC32) {
  1108.             for (var i = 0; i < files.length; i++) {
  1109.                 promises.push(checkEntryCRC32(files[i]));
  1110.             }
  1111.         }
  1112.         return external.Promise.all(promises);
  1113.     }).then(function addFiles(results) {
  1114.         var zipEntries = results.shift();
  1115.         var files = zipEntries.files;
  1116.         for (var i = 0; i < files.length; i++) {
  1117.             var input = files[i];
  1118.             zip.file(input.fileNameStr, input.decompressed, {
  1119.                 binary: true,
  1120.                 optimizedBinaryString: true,
  1121.                 date: input.date,
  1122.                 dir: input.dir,
  1123.                 comment : input.fileCommentStr.length ? input.fileCommentStr : null,
  1124.                 unixPermissions : input.unixPermissions,
  1125.                 dosPermissions : input.dosPermissions,
  1126.                 createFolders: options.createFolders
  1127.             });
  1128.         }
  1129.         if (zipEntries.zipComment.length) {
  1130.             zip.comment = zipEntries.zipComment;
  1131.         }
  1132.  
  1133.         return zip;
  1134.     });
  1135. };
  1136.  
  1137. },{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
  1138. "use strict";
  1139.  
  1140. var utils = require('../utils');
  1141. var GenericWorker = require('../stream/GenericWorker');
  1142.  
  1143. /**
  1144.  * A worker that use a nodejs stream as source.
  1145.  * @constructor
  1146.  * @param {String} filename the name of the file entry for this stream.
  1147.  * @param {Readable} stream the nodejs stream.
  1148.  */
  1149. function NodejsStreamInputAdapter(filename, stream) {
  1150.     GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
  1151.     this._upstreamEnded = false;
  1152.     this._bindStream(stream);
  1153. }
  1154.  
  1155. utils.inherits(NodejsStreamInputAdapter, GenericWorker);
  1156.  
  1157. /**
  1158.  * Prepare the stream and bind the callbacks on it.
  1159.  * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
  1160.  * @param {Stream} stream the nodejs stream to use.
  1161.  */
  1162. NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
  1163.     var self = this;
  1164.     this._stream = stream;
  1165.     stream.pause();
  1166.     stream
  1167.     .on("data", function (chunk) {
  1168.         self.push({
  1169.             data: chunk,
  1170.             meta : {
  1171.                 percent : 0
  1172.             }
  1173.         });
  1174.     })
  1175.     .on("error", function (e) {
  1176.         if(self.isPaused) {
  1177.             this.generatedError = e;
  1178.         } else {
  1179.             self.error(e);
  1180.         }
  1181.     })
  1182.     .on("end", function () {
  1183.         if(self.isPaused) {
  1184.             self._upstreamEnded = true;
  1185.         } else {
  1186.             self.end();
  1187.         }
  1188.     });
  1189. };
  1190. NodejsStreamInputAdapter.prototype.pause = function () {
  1191.     if(!GenericWorker.prototype.pause.call(this)) {
  1192.         return false;
  1193.     }
  1194.     this._stream.pause();
  1195.     return true;
  1196. };
  1197. NodejsStreamInputAdapter.prototype.resume = function () {
  1198.     if(!GenericWorker.prototype.resume.call(this)) {
  1199.         return false;
  1200.     }
  1201.  
  1202.     if(this._upstreamEnded) {
  1203.         this.end();
  1204.     } else {
  1205.         this._stream.resume();
  1206.     }
  1207.  
  1208.     return true;
  1209. };
  1210.  
  1211. module.exports = NodejsStreamInputAdapter;
  1212.  
  1213. },{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
  1214. 'use strict';
  1215.  
  1216. var Readable = require('readable-stream').Readable;
  1217.  
  1218. var util = require('util');
  1219. util.inherits(NodejsStreamOutputAdapter, Readable);
  1220.  
  1221. /**
  1222. * A nodejs stream using a worker as source.
  1223. * @see the SourceWrapper in http://nodejs.org/api/stream.html
  1224. * @constructor
  1225. * @param {StreamHelper} helper the helper wrapping the worker
  1226. * @param {Object} options the nodejs stream options
  1227. * @param {Function} updateCb the update callback.
  1228. */
  1229. function NodejsStreamOutputAdapter(helper, options, updateCb) {
  1230.     Readable.call(this, options);
  1231.     this._helper = helper;
  1232.  
  1233.     var self = this;
  1234.     helper.on("data", function (data, meta) {
  1235.         if (!self.push(data)) {
  1236.             self._helper.pause();
  1237.         }
  1238.         if(updateCb) {
  1239.             updateCb(meta);
  1240.         }
  1241.     })
  1242.     .on("error", function(e) {
  1243.         self.emit('error', e);
  1244.     })
  1245.     .on("end", function () {
  1246.         self.push(null);
  1247.     });
  1248. }
  1249.  
  1250.  
  1251. NodejsStreamOutputAdapter.prototype._read = function() {
  1252.     this._helper.resume();
  1253. };
  1254.  
  1255. module.exports = NodejsStreamOutputAdapter;
  1256.  
  1257. },{"readable-stream":16,"util":undefined}],14:[function(require,module,exports){
  1258. 'use strict';
  1259.  
  1260. module.exports = {
  1261.     /**
  1262.      * True if this is running in Nodejs, will be undefined in a browser.
  1263.      * In a browser, browserify won't include this file and the whole module
  1264.      * will be resolved an empty object.
  1265.      */
  1266.     isNode : typeof Buffer !== "undefined",
  1267.     /**
  1268.      * Create a new nodejs Buffer.
  1269.      * @param {Object} data the data to pass to the constructor.
  1270.      * @param {String} encoding the encoding to use.
  1271.      * @return {Buffer} a new Buffer.
  1272.      */
  1273.     newBuffer : function(data, encoding){
  1274.         return new Buffer(data, encoding);
  1275.     },
  1276.     /**
  1277.      * Find out if an object is a Buffer.
  1278.      * @param {Object} b the object to test.
  1279.      * @return {Boolean} true if the object is a Buffer, false otherwise.
  1280.      */
  1281.     isBuffer : function(b){
  1282.         return Buffer.isBuffer(b);
  1283.     },
  1284.  
  1285.     isStream : function (obj) {
  1286.         return obj &&
  1287.             typeof obj.on === "function" &&
  1288.             typeof obj.pause === "function" &&
  1289.             typeof obj.resume === "function";
  1290.     }
  1291. };
  1292.  
  1293. },{}],15:[function(require,module,exports){
  1294. 'use strict';
  1295. var utf8 = require('./utf8');
  1296. var utils = require('./utils');
  1297. var GenericWorker = require('./stream/GenericWorker');
  1298. var StreamHelper = require('./stream/StreamHelper');
  1299. var defaults = require('./defaults');
  1300. var CompressedObject = require('./compressedObject');
  1301. var ZipObject = require('./zipObject');
  1302. var generate = require("./generate");
  1303. var nodejsUtils = require("./nodejsUtils");
  1304. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  1305.  
  1306.  
  1307. /**
  1308.  * Add a file in the current folder.
  1309.  * @private
  1310.  * @param {string} name the name of the file
  1311.  * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  1312.  * @param {Object} originalOptions the options of the file
  1313.  * @return {Object} the new file.
  1314.  */
  1315. var fileAdd = function(name, data, originalOptions) {
  1316.     // be sure sub folders exist
  1317.     var dataType = utils.getTypeOf(data),
  1318.         parent;
  1319.  
  1320.  
  1321.     /*
  1322.      * Correct options.
  1323.      */
  1324.  
  1325.     var o = utils.extend(originalOptions || {}, defaults);
  1326.     o.date = o.date || new Date();
  1327.     if (o.compression !== null) {
  1328.         o.compression = o.compression.toUpperCase();
  1329.     }
  1330.  
  1331.     if (typeof o.unixPermissions === "string") {
  1332.         o.unixPermissions = parseInt(o.unixPermissions, 8);
  1333.     }
  1334.  
  1335.     // UNX_IFDIR  0040000 see zipinfo.c
  1336.     if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  1337.         o.dir = true;
  1338.     }
  1339.     // Bit 4    Directory
  1340.     if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  1341.         o.dir = true;
  1342.     }
  1343.  
  1344.     if (o.dir) {
  1345.         name = forceTrailingSlash(name);
  1346.     }
  1347.     if (o.createFolders && (parent = parentFolder(name))) {
  1348.         folderAdd.call(this, parent, true);
  1349.     }
  1350.  
  1351.     var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  1352.     if (!originalOptions || typeof originalOptions.binary === "undefined") {
  1353.         o.binary = !isUnicodeString;
  1354.     }
  1355.  
  1356.  
  1357.     var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  1358.  
  1359.     if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  1360.         o.base64 = false;
  1361.         o.binary = true;
  1362.         data = "";
  1363.         o.compression = "STORE";
  1364.         dataType = "string";
  1365.     }
  1366.  
  1367.     /*
  1368.      * Convert content to fit.
  1369.      */
  1370.  
  1371.     var zipObjectContent = null;
  1372.     if (data instanceof CompressedObject || data instanceof GenericWorker) {
  1373.         zipObjectContent = data;
  1374.     } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1375.         zipObjectContent = new NodejsStreamInputAdapter(name, data);
  1376.     } else {
  1377.         zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  1378.     }
  1379.  
  1380.     var object = new ZipObject(name, zipObjectContent, o);
  1381.     this.files[name] = object;
  1382.     /*
  1383.     TODO: we can't throw an exception because we have async promises
  1384.     (we can have a promise of a Date() for example) but returning a
  1385.     promise is useless because file(name, data) returns the JSZip
  1386.     object for chaining. Should we break that to allow the user
  1387.     to catch the error ?
  1388.  
  1389.     return external.Promise.resolve(zipObjectContent)
  1390.     .then(function () {
  1391.         return object;
  1392.     });
  1393.     */
  1394. };
  1395.  
  1396. /**
  1397.  * Find the parent folder of the path.
  1398.  * @private
  1399.  * @param {string} path the path to use
  1400.  * @return {string} the parent folder, or ""
  1401.  */
  1402. var parentFolder = function (path) {
  1403.     if (path.slice(-1) === '/') {
  1404.         path = path.substring(0, path.length - 1);
  1405.     }
  1406.     var lastSlash = path.lastIndexOf('/');
  1407.     return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  1408. };
  1409.  
  1410. /**
  1411.  * Returns the path with a slash at the end.
  1412.  * @private
  1413.  * @param {String} path the path to check.
  1414.  * @return {String} the path with a trailing slash.
  1415.  */
  1416. var forceTrailingSlash = function(path) {
  1417.     // Check the name ends with a /
  1418.     if (path.slice(-1) !== "/") {
  1419.         path += "/"; // IE doesn't like substr(-1)
  1420.     }
  1421.     return path;
  1422. };
  1423.  
  1424. /**
  1425.  * Add a (sub) folder in the current folder.
  1426.  * @private
  1427.  * @param {string} name the folder's name
  1428.  * @param {boolean=} [createFolders] If true, automatically create sub
  1429.  *  folders. Defaults to false.
  1430.  * @return {Object} the new folder.
  1431.  */
  1432. var folderAdd = function(name, createFolders) {
  1433.     createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;
  1434.  
  1435.     name = forceTrailingSlash(name);
  1436.  
  1437.     // Does this folder already exist?
  1438.     if (!this.files[name]) {
  1439.         fileAdd.call(this, name, null, {
  1440.             dir: true,
  1441.             createFolders: createFolders
  1442.         });
  1443.     }
  1444.     return this.files[name];
  1445. };
  1446.  
  1447. /**
  1448. * Cross-window, cross-Node-context regular expression detection
  1449. * @param  {Object}  object Anything
  1450. * @return {Boolean}        true if the object is a regular expression,
  1451. * false otherwise
  1452. */
  1453. function isRegExp(object) {
  1454.     return Object.prototype.toString.call(object) === "[object RegExp]";
  1455. }
  1456.  
  1457. // return the actual prototype of JSZip
  1458. var out = {
  1459.     /**
  1460.      * @see loadAsync
  1461.      */
  1462.     load: function() {
  1463.         throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1464.     },
  1465.  
  1466.  
  1467.     /**
  1468.      * Call a callback function for each entry at this folder level.
  1469.      * @param {Function} cb the callback function:
  1470.      * function (relativePath, file) {...}
  1471.      * It takes 2 arguments : the relative path and the file.
  1472.      */
  1473.     forEach: function(cb) {
  1474.         var filename, relativePath, file;
  1475.         for (filename in this.files) {
  1476.             if (!this.files.hasOwnProperty(filename)) {
  1477.                 continue;
  1478.             }
  1479.             file = this.files[filename];
  1480.             relativePath = filename.slice(this.root.length, filename.length);
  1481.             if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  1482.                 cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  1483.             }
  1484.         }
  1485.     },
  1486.  
  1487.     /**
  1488.      * Filter nested files/folders with the specified function.
  1489.      * @param {Function} search the predicate to use :
  1490.      * function (relativePath, file) {...}
  1491.      * It takes 2 arguments : the relative path and the file.
  1492.      * @return {Array} An array of matching elements.
  1493.      */
  1494.     filter: function(search) {
  1495.         var result = [];
  1496.         this.forEach(function (relativePath, entry) {
  1497.             if (search(relativePath, entry)) { // the file matches the function
  1498.                 result.push(entry);
  1499.             }
  1500.  
  1501.         });
  1502.         return result;
  1503.     },
  1504.  
  1505.     /**
  1506.      * Add a file to the zip file, or search a file.
  1507.      * @param   {string|RegExp} name The name of the file to add (if data is defined),
  1508.      * the name of the file to find (if no data) or a regex to match files.
  1509.      * @param   {String|ArrayBuffer|Uint8Array|Buffer} data  The file data, either raw or base64 encoded
  1510.      * @param   {Object} o     File options
  1511.      * @return  {JSZip|Object|Array} this JSZip object (when adding a file),
  1512.      * a file (when searching by string) or an array of files (when searching by regex).
  1513.      */
  1514.     file: function(name, data, o) {
  1515.         if (arguments.length === 1) {
  1516.             if (isRegExp(name)) {
  1517.                 var regexp = name;
  1518.                 return this.filter(function(relativePath, file) {
  1519.                     return !file.dir && regexp.test(relativePath);
  1520.                 });
  1521.             }
  1522.             else { // text
  1523.                 var obj = this.files[this.root + name];
  1524.                 if (obj && !obj.dir) {
  1525.                     return obj;
  1526.                 } else {
  1527.                     return null;
  1528.                 }
  1529.             }
  1530.         }
  1531.         else { // more than one argument : we have data !
  1532.             name = this.root + name;
  1533.             fileAdd.call(this, name, data, o);
  1534.         }
  1535.         return this;
  1536.     },
  1537.  
  1538.     /**
  1539.      * Add a directory to the zip file, or search.
  1540.      * @param   {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1541.      * @return  {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1542.      */
  1543.     folder: function(arg) {
  1544.         if (!arg) {
  1545.             return this;
  1546.         }
  1547.  
  1548.         if (isRegExp(arg)) {
  1549.             return this.filter(function(relativePath, file) {
  1550.                 return file.dir && arg.test(relativePath);
  1551.             });
  1552.         }
  1553.  
  1554.         // else, name is a new folder
  1555.         var name = this.root + arg;
  1556.         var newFolder = folderAdd.call(this, name);
  1557.  
  1558.         // Allow chaining by returning a new object with this folder as the root
  1559.         var ret = this.clone();
  1560.         ret.root = newFolder.name;
  1561.         return ret;
  1562.     },
  1563.  
  1564.     /**
  1565.      * Delete a file, or a directory and all sub-files, from the zip
  1566.      * @param {string} name the name of the file to delete
  1567.      * @return {JSZip} this JSZip object
  1568.      */
  1569.     remove: function(name) {
  1570.         name = this.root + name;
  1571.         var file = this.files[name];
  1572.         if (!file) {
  1573.             // Look for any folders
  1574.             if (name.slice(-1) !== "/") {
  1575.                 name += "/";
  1576.             }
  1577.             file = this.files[name];
  1578.         }
  1579.  
  1580.         if (file && !file.dir) {
  1581.             // file
  1582.             delete this.files[name];
  1583.         } else {
  1584.             // maybe a folder, delete recursively
  1585.             var kids = this.filter(function(relativePath, file) {
  1586.                 return file.name.slice(0, name.length) === name;
  1587.             });
  1588.             for (var i = 0; i < kids.length; i++) {
  1589.                 delete this.files[kids[i].name];
  1590.             }
  1591.         }
  1592.  
  1593.         return this;
  1594.     },
  1595.  
  1596.     /**
  1597.      * Generate the complete zip file
  1598.      * @param {Object} options the options to generate the zip file :
  1599.      * - compression, "STORE" by default.
  1600.      * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1601.      * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1602.      */
  1603.     generate: function(options) {
  1604.         throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1605.     },
  1606.  
  1607.     /**
  1608.      * Generate the complete zip file as an internal stream.
  1609.      * @param {Object} options the options to generate the zip file :
  1610.      * - compression, "STORE" by default.
  1611.      * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1612.      * @return {StreamHelper} the streamed zip file.
  1613.      */
  1614.     generateInternalStream: function(options) {
  1615.       var worker, opts = {};
  1616.       try {
  1617.           opts = utils.extend(options || {}, {
  1618.               streamFiles: false,
  1619.               compression: "STORE",
  1620.               compressionOptions : null,
  1621.               type: "",
  1622.               platform: "DOS",
  1623.               comment: null,
  1624.               mimeType: 'application/zip',
  1625.               encodeFileName: utf8.utf8encode
  1626.           });
  1627.  
  1628.           opts.type = opts.type.toLowerCase();
  1629.           opts.compression = opts.compression.toUpperCase();
  1630.  
  1631.           // "binarystring" is prefered but the internals use "string".
  1632.           if(opts.type === "binarystring") {
  1633.             opts.type = "string";
  1634.           }
  1635.  
  1636.           if (!opts.type) {
  1637.             throw new Error("No output type specified.");
  1638.           }
  1639.  
  1640.           utils.checkSupport(opts.type);
  1641.  
  1642.           // accept nodejs `process.platform`
  1643.           if(
  1644.               opts.platform === 'darwin' ||
  1645.               opts.platform === 'freebsd' ||
  1646.               opts.platform === 'linux' ||
  1647.               opts.platform === 'sunos'
  1648.           ) {
  1649.               opts.platform = "UNIX";
  1650.           }
  1651.           if (opts.platform === 'win32') {
  1652.               opts.platform = "DOS";
  1653.           }
  1654.  
  1655.           var comment = opts.comment || this.comment || "";
  1656.           worker = generate.generateWorker(this, opts, comment);
  1657.       } catch (e) {
  1658.         worker = new GenericWorker("error");
  1659.         worker.error(e);
  1660.       }
  1661.       return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  1662.     },
  1663.     /**
  1664.      * Generate the complete zip file asynchronously.
  1665.      * @see generateInternalStream
  1666.      */
  1667.     generateAsync: function(options, onUpdate) {
  1668.         return this.generateInternalStream(options).accumulate(onUpdate);
  1669.     },
  1670.     /**
  1671.      * Generate the complete zip file asynchronously.
  1672.      * @see generateInternalStream
  1673.      */
  1674.     generateNodeStream: function(options, onUpdate) {
  1675.         options = options || {};
  1676.         if (!options.type) {
  1677.             options.type = "nodebuffer";
  1678.         }
  1679.         return this.generateInternalStream(options).toNodejsStream(onUpdate);
  1680.     }
  1681. };
  1682. module.exports = out;
  1683.  
  1684. },{"./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){
  1685. /*
  1686.  * This file is used by module bundlers (browserify/webpack/etc) when
  1687.  * including a stream implementation. We use "readable-stream" to get a
  1688.  * consistent behavior between nodejs versions but bundlers often have a shim
  1689.  * for "stream". Using this shim greatly improve the compatibility and greatly
  1690.  * reduce the final size of the bundle (only one stream implementation, not
  1691.  * two).
  1692.  */
  1693. module.exports = require("stream");
  1694.  
  1695. },{"stream":undefined}],17:[function(require,module,exports){
  1696. 'use strict';
  1697. var DataReader = require('./DataReader');
  1698. var utils = require('../utils');
  1699.  
  1700. function ArrayReader(data) {
  1701.     DataReader.call(this, data);
  1702.     for(var i = 0; i < this.data.length; i++) {
  1703.         data[i] = data[i] & 0xFF;
  1704.     }
  1705. }
  1706. utils.inherits(ArrayReader, DataReader);
  1707. /**
  1708.  * @see DataReader.byteAt
  1709.  */
  1710. ArrayReader.prototype.byteAt = function(i) {
  1711.     return this.data[this.zero + i];
  1712. };
  1713. /**
  1714.  * @see DataReader.lastIndexOfSignature
  1715.  */
  1716. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1717.     var sig0 = sig.charCodeAt(0),
  1718.         sig1 = sig.charCodeAt(1),
  1719.         sig2 = sig.charCodeAt(2),
  1720.         sig3 = sig.charCodeAt(3);
  1721.     for (var i = this.length - 4; i >= 0; --i) {
  1722.         if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1723.             return i - this.zero;
  1724.         }
  1725.     }
  1726.  
  1727.     return -1;
  1728. };
  1729. /**
  1730.  * @see DataReader.readAndCheckSignature
  1731.  */
  1732. ArrayReader.prototype.readAndCheckSignature = function (sig) {
  1733.     var sig0 = sig.charCodeAt(0),
  1734.         sig1 = sig.charCodeAt(1),
  1735.         sig2 = sig.charCodeAt(2),
  1736.         sig3 = sig.charCodeAt(3),
  1737.         data = this.readData(4);
  1738.     return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
  1739. };
  1740. /**
  1741.  * @see DataReader.readData
  1742.  */
  1743. ArrayReader.prototype.readData = function(size) {
  1744.     this.checkOffset(size);
  1745.     if(size === 0) {
  1746.         return [];
  1747.     }
  1748.     var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1749.     this.index += size;
  1750.     return result;
  1751. };
  1752. module.exports = ArrayReader;
  1753.  
  1754. },{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
  1755. 'use strict';
  1756. var utils = require('../utils');
  1757.  
  1758. function DataReader(data) {
  1759.     this.data = data; // type : see implementation
  1760.     this.length = data.length;
  1761.     this.index = 0;
  1762.     this.zero = 0;
  1763. }
  1764. DataReader.prototype = {
  1765.     /**
  1766.      * Check that the offset will not go too far.
  1767.      * @param {string} offset the additional offset to check.
  1768.      * @throws {Error} an Error if the offset is out of bounds.
  1769.      */
  1770.     checkOffset: function(offset) {
  1771.         this.checkIndex(this.index + offset);
  1772.     },
  1773.     /**
  1774.      * Check that the specifed index will not be too far.
  1775.      * @param {string} newIndex the index to check.
  1776.      * @throws {Error} an Error if the index is out of bounds.
  1777.      */
  1778.     checkIndex: function(newIndex) {
  1779.         if (this.length < this.zero + newIndex || newIndex < 0) {
  1780.             throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  1781.         }
  1782.     },
  1783.     /**
  1784.      * Change the index.
  1785.      * @param {number} newIndex The new index.
  1786.      * @throws {Error} if the new index is out of the data.
  1787.      */
  1788.     setIndex: function(newIndex) {
  1789.         this.checkIndex(newIndex);
  1790.         this.index = newIndex;
  1791.     },
  1792.     /**
  1793.      * Skip the next n bytes.
  1794.      * @param {number} n the number of bytes to skip.
  1795.      * @throws {Error} if the new index is out of the data.
  1796.      */
  1797.     skip: function(n) {
  1798.         this.setIndex(this.index + n);
  1799.     },
  1800.     /**
  1801.      * Get the byte at the specified index.
  1802.      * @param {number} i the index to use.
  1803.      * @return {number} a byte.
  1804.      */
  1805.     byteAt: function(i) {
  1806.         // see implementations
  1807.     },
  1808.     /**
  1809.      * Get the next number with a given byte size.
  1810.      * @param {number} size the number of bytes to read.
  1811.      * @return {number} the corresponding number.
  1812.      */
  1813.     readInt: function(size) {
  1814.         var result = 0,
  1815.             i;
  1816.         this.checkOffset(size);
  1817.         for (i = this.index + size - 1; i >= this.index; i--) {
  1818.             result = (result << 8) + this.byteAt(i);
  1819.         }
  1820.         this.index += size;
  1821.         return result;
  1822.     },
  1823.     /**
  1824.      * Get the next string with a given byte size.
  1825.      * @param {number} size the number of bytes to read.
  1826.      * @return {string} the corresponding string.
  1827.      */
  1828.     readString: function(size) {
  1829.         return utils.transformTo("string", this.readData(size));
  1830.     },
  1831.     /**
  1832.      * Get raw data without conversion, <size> bytes.
  1833.      * @param {number} size the number of bytes to read.
  1834.      * @return {Object} the raw data, implementation specific.
  1835.      */
  1836.     readData: function(size) {
  1837.         // see implementations
  1838.     },
  1839.     /**
  1840.      * Find the last occurence of a zip signature (4 bytes).
  1841.      * @param {string} sig the signature to find.
  1842.      * @return {number} the index of the last occurence, -1 if not found.
  1843.      */
  1844.     lastIndexOfSignature: function(sig) {
  1845.         // see implementations
  1846.     },
  1847.     /**
  1848.      * Read the signature (4 bytes) at the current position and compare it with sig.
  1849.      * @param {string} sig the expected signature
  1850.      * @return {boolean} true if the signature matches, false otherwise.
  1851.      */
  1852.     readAndCheckSignature: function(sig) {
  1853.         // see implementations
  1854.     },
  1855.     /**
  1856.      * Get the next date.
  1857.      * @return {Date} the date.
  1858.      */
  1859.     readDate: function() {
  1860.         var dostime = this.readInt(4);
  1861.         return new Date(Date.UTC(
  1862.         ((dostime >> 25) & 0x7f) + 1980, // year
  1863.         ((dostime >> 21) & 0x0f) - 1, // month
  1864.         (dostime >> 16) & 0x1f, // day
  1865.         (dostime >> 11) & 0x1f, // hour
  1866.         (dostime >> 5) & 0x3f, // minute
  1867.         (dostime & 0x1f) << 1)); // second
  1868.     }
  1869. };
  1870. module.exports = DataReader;
  1871.  
  1872. },{"../utils":32}],19:[function(require,module,exports){
  1873. 'use strict';
  1874. var Uint8ArrayReader = require('./Uint8ArrayReader');
  1875. var utils = require('../utils');
  1876.  
  1877. function NodeBufferReader(data) {
  1878.     Uint8ArrayReader.call(this, data);
  1879. }
  1880. utils.inherits(NodeBufferReader, Uint8ArrayReader);
  1881.  
  1882. /**
  1883.  * @see DataReader.readData
  1884.  */
  1885. NodeBufferReader.prototype.readData = function(size) {
  1886.     this.checkOffset(size);
  1887.     var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1888.     this.index += size;
  1889.     return result;
  1890. };
  1891. module.exports = NodeBufferReader;
  1892.  
  1893. },{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
  1894. 'use strict';
  1895. var DataReader = require('./DataReader');
  1896. var utils = require('../utils');
  1897.  
  1898. function StringReader(data) {
  1899.     DataReader.call(this, data);
  1900. }
  1901. utils.inherits(StringReader, DataReader);
  1902. /**
  1903.  * @see DataReader.byteAt
  1904.  */
  1905. StringReader.prototype.byteAt = function(i) {
  1906.     return this.data.charCodeAt(this.zero + i);
  1907. };
  1908. /**
  1909.  * @see DataReader.lastIndexOfSignature
  1910.  */
  1911. StringReader.prototype.lastIndexOfSignature = function(sig) {
  1912.     return this.data.lastIndexOf(sig) - this.zero;
  1913. };
  1914. /**
  1915.  * @see DataReader.readAndCheckSignature
  1916.  */
  1917. StringReader.prototype.readAndCheckSignature = function (sig) {
  1918.     var data = this.readData(4);
  1919.     return sig === data;
  1920. };
  1921. /**
  1922.  * @see DataReader.readData
  1923.  */
  1924. StringReader.prototype.readData = function(size) {
  1925.     this.checkOffset(size);
  1926.     // this will work because the constructor applied the "& 0xff" mask.
  1927.     var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1928.     this.index += size;
  1929.     return result;
  1930. };
  1931. module.exports = StringReader;
  1932.  
  1933. },{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
  1934. 'use strict';
  1935. var ArrayReader = require('./ArrayReader');
  1936. var utils = require('../utils');
  1937.  
  1938. function Uint8ArrayReader(data) {
  1939.     ArrayReader.call(this, data);
  1940. }
  1941. utils.inherits(Uint8ArrayReader, ArrayReader);
  1942. /**
  1943.  * @see DataReader.readData
  1944.  */
  1945. Uint8ArrayReader.prototype.readData = function(size) {
  1946.     this.checkOffset(size);
  1947.     if(size === 0) {
  1948.         // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  1949.         return new Uint8Array(0);
  1950.     }
  1951.     var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  1952.     this.index += size;
  1953.     return result;
  1954. };
  1955. module.exports = Uint8ArrayReader;
  1956.  
  1957. },{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
  1958. 'use strict';
  1959.  
  1960. var utils = require('../utils');
  1961. var support = require('../support');
  1962. var ArrayReader = require('./ArrayReader');
  1963. var StringReader = require('./StringReader');
  1964. var NodeBufferReader = require('./NodeBufferReader');
  1965. var Uint8ArrayReader = require('./Uint8ArrayReader');
  1966.  
  1967. /**
  1968.  * Create a reader adapted to the data.
  1969.  * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
  1970.  * @return {DataReader} the data reader.
  1971.  */
  1972. module.exports = function (data) {
  1973.     var type = utils.getTypeOf(data);
  1974.     utils.checkSupport(type);
  1975.     if (type === "string" && !support.uint8array) {
  1976.         return new StringReader(data);
  1977.     }
  1978.     if (type === "nodebuffer") {
  1979.         return new NodeBufferReader(data);
  1980.     }
  1981.     if (support.uint8array) {
  1982.         return new Uint8ArrayReader(utils.transformTo("uint8array", data));
  1983.     }
  1984.     return new ArrayReader(utils.transformTo("array", data));
  1985. };
  1986.  
  1987. // vim: set shiftwidth=4 softtabstop=4:
  1988.  
  1989. },{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
  1990. 'use strict';
  1991. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  1992. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  1993. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  1994. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  1995. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  1996. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  1997.  
  1998. },{}],24:[function(require,module,exports){
  1999. 'use strict';
  2000.  
  2001. var GenericWorker = require('./GenericWorker');
  2002. var utils = require('../utils');
  2003.  
  2004. /**
  2005.  * A worker which convert chunks to a specified type.
  2006.  * @constructor
  2007.  * @param {String} destType the destination type.
  2008.  */
  2009. function ConvertWorker(destType) {
  2010.     GenericWorker.call(this, "ConvertWorker to " + destType);
  2011.     this.destType = destType;
  2012. }
  2013. utils.inherits(ConvertWorker, GenericWorker);
  2014.  
  2015. /**
  2016.  * @see GenericWorker.processChunk
  2017.  */
  2018. ConvertWorker.prototype.processChunk = function (chunk) {
  2019.     this.push({
  2020.         data : utils.transformTo(this.destType, chunk.data),
  2021.         meta : chunk.meta
  2022.     });
  2023. };
  2024. module.exports = ConvertWorker;
  2025.  
  2026. },{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
  2027. 'use strict';
  2028.  
  2029. var GenericWorker = require('./GenericWorker');
  2030. var crc32 = require('../crc32');
  2031. var utils = require('../utils');
  2032.  
  2033. /**
  2034.  * A worker which calculate the crc32 of the data flowing through.
  2035.  * @constructor
  2036.  */
  2037. function Crc32Probe() {
  2038.     GenericWorker.call(this, "Crc32Probe");
  2039.     this.withStreamInfo("crc32", 0);
  2040. }
  2041. utils.inherits(Crc32Probe, GenericWorker);
  2042.  
  2043. /**
  2044.  * @see GenericWorker.processChunk
  2045.  */
  2046. Crc32Probe.prototype.processChunk = function (chunk) {
  2047.     this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
  2048.     this.push(chunk);
  2049. };
  2050. module.exports = Crc32Probe;
  2051.  
  2052. },{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
  2053. 'use strict';
  2054.  
  2055. var utils = require('../utils');
  2056. var GenericWorker = require('./GenericWorker');
  2057.  
  2058. /**
  2059.  * A worker which calculate the total length of the data flowing through.
  2060.  * @constructor
  2061.  * @param {String} propName the name used to expose the length
  2062.  */
  2063. function DataLengthProbe(propName) {
  2064.     GenericWorker.call(this, "DataLengthProbe for " + propName);
  2065.     this.propName = propName;
  2066.     this.withStreamInfo(propName, 0);
  2067. }
  2068. utils.inherits(DataLengthProbe, GenericWorker);
  2069.  
  2070. /**
  2071.  * @see GenericWorker.processChunk
  2072.  */
  2073. DataLengthProbe.prototype.processChunk = function (chunk) {
  2074.     if(chunk) {
  2075.         var length = this.streamInfo[this.propName] || 0;
  2076.         this.streamInfo[this.propName] = length + chunk.data.length;
  2077.     }
  2078.     GenericWorker.prototype.processChunk.call(this, chunk);
  2079. };
  2080. module.exports = DataLengthProbe;
  2081.  
  2082.  
  2083. },{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
  2084. 'use strict';
  2085.  
  2086. var utils = require('../utils');
  2087. var GenericWorker = require('./GenericWorker');
  2088.  
  2089. // the size of the generated chunks
  2090. // TODO expose this as a public variable
  2091. var DEFAULT_BLOCK_SIZE = 16 * 1024;
  2092.  
  2093. /**
  2094.  * A worker that reads a content and emits chunks.
  2095.  * @constructor
  2096.  * @param {Promise} dataP the promise of the data to split
  2097.  */
  2098. function DataWorker(dataP) {
  2099.     GenericWorker.call(this, "DataWorker");
  2100.     var self = this;
  2101.     this.dataIsReady = false;
  2102.     this.index = 0;
  2103.     this.max = 0;
  2104.     this.data = null;
  2105.     this.type = "";
  2106.  
  2107.     this._tickScheduled = false;
  2108.  
  2109.     dataP.then(function (data) {
  2110.         self.dataIsReady = true;
  2111.         self.data = data;
  2112.         self.max = data && data.length || 0;
  2113.         self.type = utils.getTypeOf(data);
  2114.         if(!self.isPaused) {
  2115.             self._tickAndRepeat();
  2116.         }
  2117.     }, function (e) {
  2118.         self.error(e);
  2119.     });
  2120. }
  2121.  
  2122. utils.inherits(DataWorker, GenericWorker);
  2123.  
  2124. /**
  2125.  * @see GenericWorker.cleanUp
  2126.  */
  2127. DataWorker.prototype.cleanUp = function () {
  2128.     GenericWorker.prototype.cleanUp.call(this);
  2129.     this.data = null;
  2130. };
  2131.  
  2132. /**
  2133.  * @see GenericWorker.resume
  2134.  */
  2135. DataWorker.prototype.resume = function () {
  2136.     if(!GenericWorker.prototype.resume.call(this)) {
  2137.         return false;
  2138.     }
  2139.  
  2140.     if (!this._tickScheduled && this.dataIsReady) {
  2141.         this._tickScheduled = true;
  2142.         utils.delay(this._tickAndRepeat, [], this);
  2143.     }
  2144.     return true;
  2145. };
  2146.  
  2147. /**
  2148.  * Trigger a tick a schedule an other call to this function.
  2149.  */
  2150. DataWorker.prototype._tickAndRepeat = function() {
  2151.     this._tickScheduled = false;
  2152.     if(this.isPaused || this.isFinished) {
  2153.         return;
  2154.     }
  2155.     this._tick();
  2156.     if(!this.isFinished) {
  2157.         utils.delay(this._tickAndRepeat, [], this);
  2158.         this._tickScheduled = true;
  2159.     }
  2160. };
  2161.  
  2162. /**
  2163.  * Read and push a chunk.
  2164.  */
  2165. DataWorker.prototype._tick = function() {
  2166.  
  2167.     if(this.isPaused || this.isFinished) {
  2168.         return false;
  2169.     }
  2170.  
  2171.     var size = DEFAULT_BLOCK_SIZE;
  2172.     var data = null, nextIndex = Math.min(this.max, this.index + size);
  2173.     if (this.index >= this.max) {
  2174.         // EOF
  2175.         return this.end();
  2176.     } else {
  2177.         switch(this.type) {
  2178.             case "string":
  2179.                 data = this.data.substring(this.index, nextIndex);
  2180.             break;
  2181.             case "uint8array":
  2182.                 data = this.data.subarray(this.index, nextIndex);
  2183.             break;
  2184.             case "array":
  2185.             case "nodebuffer":
  2186.                 data = this.data.slice(this.index, nextIndex);
  2187.             break;
  2188.         }
  2189.         this.index = nextIndex;
  2190.         return this.push({
  2191.             data : data,
  2192.             meta : {
  2193.                 percent : this.max ? this.index / this.max * 100 : 0
  2194.             }
  2195.         });
  2196.     }
  2197. };
  2198.  
  2199. module.exports = DataWorker;
  2200.  
  2201. },{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
  2202. 'use strict';
  2203.  
  2204. /**
  2205.  * A worker that does nothing but passing chunks to the next one. This is like
  2206.  * a nodejs stream but with some differences. On the good side :
  2207.  * - it works on IE 6-9 without any issue / polyfill
  2208.  * - it weights less than the full dependencies bundled with browserify
  2209.  * - it forwards errors (no need to declare an error handler EVERYWHERE)
  2210.  *
  2211.  * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
  2212.  * object containing anything (`percent` for example), see each worker for more
  2213.  * details. The latter is the real data (String, Uint8Array, etc).
  2214.  *
  2215.  * @constructor
  2216.  * @param {String} name the name of the stream (mainly used for debugging purposes)
  2217.  */
  2218. function GenericWorker(name) {
  2219.     // the name of the worker
  2220.     this.name = name || "default";
  2221.     // an object containing metadata about the workers chain
  2222.     this.streamInfo = {};
  2223.     // an error which happened when the worker was paused
  2224.     this.generatedError = null;
  2225.     // an object containing metadata to be merged by this worker into the general metadata
  2226.     this.extraStreamInfo = {};
  2227.     // true if the stream is paused (and should not do anything), false otherwise
  2228.     this.isPaused = true;
  2229.     // true if the stream is finished (and should not do anything), false otherwise
  2230.     this.isFinished = false;
  2231.     // true if the stream is locked to prevent further structure updates (pipe), false otherwise
  2232.     this.isLocked = false;
  2233.     // the event listeners
  2234.     this._listeners = {
  2235.         'data':[],
  2236.         'end':[],
  2237.         'error':[]
  2238.     };
  2239.     // the previous worker, if any
  2240.     this.previous = null;
  2241. }
  2242.  
  2243. GenericWorker.prototype = {
  2244.     /**
  2245.      * Push a chunk to the next workers.
  2246.      * @param {Object} chunk the chunk to push
  2247.      */
  2248.     push : function (chunk) {
  2249.         this.emit("data", chunk);
  2250.     },
  2251.     /**
  2252.      * End the stream.
  2253.      * @return {Boolean} true if this call ended the worker, false otherwise.
  2254.      */
  2255.     end : function () {
  2256.         if (this.isFinished) {
  2257.             return false;
  2258.         }
  2259.  
  2260.         this.flush();
  2261.         try {
  2262.             this.emit("end");
  2263.             this.cleanUp();
  2264.             this.isFinished = true;
  2265.         } catch (e) {
  2266.             this.emit("error", e);
  2267.         }
  2268.         return true;
  2269.     },
  2270.     /**
  2271.      * End the stream with an error.
  2272.      * @param {Error} e the error which caused the premature end.
  2273.      * @return {Boolean} true if this call ended the worker with an error, false otherwise.
  2274.      */
  2275.     error : function (e) {
  2276.         if (this.isFinished) {
  2277.             return false;
  2278.         }
  2279.  
  2280.         if(this.isPaused) {
  2281.             this.generatedError = e;
  2282.         } else {
  2283.             this.isFinished = true;
  2284.  
  2285.             this.emit("error", e);
  2286.  
  2287.             // in the workers chain exploded in the middle of the chain,
  2288.             // the error event will go downward but we also need to notify
  2289.             // workers upward that there has been an error.
  2290.             if(this.previous) {
  2291.                 this.previous.error(e);
  2292.             }
  2293.  
  2294.             this.cleanUp();
  2295.         }
  2296.         return true;
  2297.     },
  2298.     /**
  2299.      * Add a callback on an event.
  2300.      * @param {String} name the name of the event (data, end, error)
  2301.      * @param {Function} listener the function to call when the event is triggered
  2302.      * @return {GenericWorker} the current object for chainability
  2303.      */
  2304.     on : function (name, listener) {
  2305.         this._listeners[name].push(listener);
  2306.         return this;
  2307.     },
  2308.     /**
  2309.      * Clean any references when a worker is ending.
  2310.      */
  2311.     cleanUp : function () {
  2312.         this.streamInfo = this.generatedError = this.extraStreamInfo = null;
  2313.         this._listeners = [];
  2314.     },
  2315.     /**
  2316.      * Trigger an event. This will call registered callback with the provided arg.
  2317.      * @param {String} name the name of the event (data, end, error)
  2318.      * @param {Object} arg the argument to call the callback with.
  2319.      */
  2320.     emit : function (name, arg) {
  2321.         if (this._listeners[name]) {
  2322.             for(var i = 0; i < this._listeners[name].length; i++) {
  2323.                 this._listeners[name][i].call(this, arg);
  2324.             }
  2325.         }
  2326.     },
  2327.     /**
  2328.      * Chain a worker with an other.
  2329.      * @param {Worker} next the worker receiving events from the current one.
  2330.      * @return {worker} the next worker for chainability
  2331.      */
  2332.     pipe : function (next) {
  2333.         return next.registerPrevious(this);
  2334.     },
  2335.     /**
  2336.      * Same as `pipe` in the other direction.
  2337.      * Using an API with `pipe(next)` is very easy.
  2338.      * Implementing the API with the point of view of the next one registering
  2339.      * a source is easier, see the ZipFileWorker.
  2340.      * @param {Worker} previous the previous worker, sending events to this one
  2341.      * @return {Worker} the current worker for chainability
  2342.      */
  2343.     registerPrevious : function (previous) {
  2344.         if (this.isLocked) {
  2345.             throw new Error("The stream '" + this + "' has already been used.");
  2346.         }
  2347.  
  2348.         // sharing the streamInfo...
  2349.         this.streamInfo = previous.streamInfo;
  2350.         // ... and adding our own bits
  2351.         this.mergeStreamInfo();
  2352.         this.previous =  previous;
  2353.         var self = this;
  2354.         previous.on('data', function (chunk) {
  2355.             self.processChunk(chunk);
  2356.         });
  2357.         previous.on('end', function () {
  2358.             self.end();
  2359.         });
  2360.         previous.on('error', function (e) {
  2361.             self.error(e);
  2362.         });
  2363.         return this;
  2364.     },
  2365.     /**
  2366.      * Pause the stream so it doesn't send events anymore.
  2367.      * @return {Boolean} true if this call paused the worker, false otherwise.
  2368.      */
  2369.     pause : function () {
  2370.         if(this.isPaused || this.isFinished) {
  2371.             return false;
  2372.         }
  2373.         this.isPaused = true;
  2374.  
  2375.         if(this.previous) {
  2376.             this.previous.pause();
  2377.         }
  2378.         return true;
  2379.     },
  2380.     /**
  2381.      * Resume a paused stream.
  2382.      * @return {Boolean} true if this call resumed the worker, false otherwise.
  2383.      */
  2384.     resume : function () {
  2385.         if(!this.isPaused || this.isFinished) {
  2386.             return false;
  2387.         }
  2388.         this.isPaused = false;
  2389.  
  2390.         // if true, the worker tried to resume but failed
  2391.         var withError = false;
  2392.         if(this.generatedError) {
  2393.             this.error(this.generatedError);
  2394.             withError = true;
  2395.         }
  2396.         if(this.previous) {
  2397.             this.previous.resume();
  2398.         }
  2399.  
  2400.         return !withError;
  2401.     },
  2402.     /**
  2403.      * Flush any remaining bytes as the stream is ending.
  2404.      */
  2405.     flush : function () {},
  2406.     /**
  2407.      * Process a chunk. This is usually the method overridden.
  2408.      * @param {Object} chunk the chunk to process.
  2409.      */
  2410.     processChunk : function(chunk) {
  2411.         this.push(chunk);
  2412.     },
  2413.     /**
  2414.      * Add a key/value to be added in the workers chain streamInfo once activated.
  2415.      * @param {String} key the key to use
  2416.      * @param {Object} value the associated value
  2417.      * @return {Worker} the current worker for chainability
  2418.      */
  2419.     withStreamInfo : function (key, value) {
  2420.         this.extraStreamInfo[key] = value;
  2421.         this.mergeStreamInfo();
  2422.         return this;
  2423.     },
  2424.     /**
  2425.      * Merge this worker's streamInfo into the chain's streamInfo.
  2426.      */
  2427.     mergeStreamInfo : function () {
  2428.         for(var key in this.extraStreamInfo) {
  2429.             if (!this.extraStreamInfo.hasOwnProperty(key)) {
  2430.                 continue;
  2431.             }
  2432.             this.streamInfo[key] = this.extraStreamInfo[key];
  2433.         }
  2434.     },
  2435.  
  2436.     /**
  2437.      * Lock the stream to prevent further updates on the workers chain.
  2438.      * After calling this method, all calls to pipe will fail.
  2439.      */
  2440.     lock: function () {
  2441.         if (this.isLocked) {
  2442.             throw new Error("The stream '" + this + "' has already been used.");
  2443.         }
  2444.         this.isLocked = true;
  2445.         if (this.previous) {
  2446.             this.previous.lock();
  2447.         }
  2448.     },
  2449.  
  2450.     /**
  2451.      *
  2452.      * Pretty print the workers chain.
  2453.      */
  2454.     toString : function () {
  2455.         var me = "Worker " + this.name;
  2456.         if (this.previous) {
  2457.             return this.previous + " -> " + me;
  2458.         } else {
  2459.             return me;
  2460.         }
  2461.     }
  2462. };
  2463.  
  2464. module.exports = GenericWorker;
  2465.  
  2466. },{}],29:[function(require,module,exports){
  2467. 'use strict';
  2468.  
  2469. var utils = require('../utils');
  2470. var ConvertWorker = require('./ConvertWorker');
  2471. var GenericWorker = require('./GenericWorker');
  2472. var base64 = require('../base64');
  2473. var support = require("../support");
  2474. var external = require("../external");
  2475.  
  2476. var NodejsStreamOutputAdapter = null;
  2477. if (support.nodestream) {
  2478.     try {
  2479.         NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
  2480.     } catch(e) {}
  2481. }
  2482.  
  2483. /**
  2484.  * Apply the final transformation of the data. If the user wants a Blob for
  2485.  * example, it's easier to work with an U8intArray and finally do the
  2486.  * ArrayBuffer/Blob conversion.
  2487.  * @param {String} resultType the name of the final type
  2488.  * @param {String} chunkType the type of the data in the given array.
  2489.  * @param {Array} dataArray the array containing the data chunks to concatenate
  2490.  * @param {String|Uint8Array|Buffer} content the content to transform
  2491.  * @param {String} mimeType the mime type of the content, if applicable.
  2492.  * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  2493.  */
  2494. function transformZipOutput(resultType, chunkType, dataArray, mimeType) {
  2495.     var content = null;
  2496.     switch(resultType) {
  2497.         case "blob" :
  2498.             return utils.newBlob(dataArray, mimeType);
  2499.         case "base64" :
  2500.             content = concat(chunkType, dataArray);
  2501.             return base64.encode(content);
  2502.         default :
  2503.             content = concat(chunkType, dataArray);
  2504.             return utils.transformTo(resultType, content);
  2505.     }
  2506. }
  2507.  
  2508. /**
  2509.  * Concatenate an array of data of the given type.
  2510.  * @param {String} type the type of the data in the given array.
  2511.  * @param {Array} dataArray the array containing the data chunks to concatenate
  2512.  * @return {String|Uint8Array|Buffer} the concatenated data
  2513.  * @throws Error if the asked type is unsupported
  2514.  */
  2515. function concat (type, dataArray) {
  2516.     var i, index = 0, res = null, totalLength = 0;
  2517.     for(i = 0; i < dataArray.length; i++) {
  2518.         totalLength += dataArray[i].length;
  2519.     }
  2520.     switch(type) {
  2521.         case "string":
  2522.             return dataArray.join("");
  2523.           case "array":
  2524.             return Array.prototype.concat.apply([], dataArray);
  2525.         case "uint8array":
  2526.             res = new Uint8Array(totalLength);
  2527.             for(i = 0; i < dataArray.length; i++) {
  2528.                 res.set(dataArray[i], index);
  2529.                 index += dataArray[i].length;
  2530.             }
  2531.             return res;
  2532.         case "nodebuffer":
  2533.             return Buffer.concat(dataArray);
  2534.         default:
  2535.             throw new Error("concat : unsupported type '"  + type + "'");
  2536.     }
  2537. }
  2538.  
  2539. /**
  2540.  * Listen a StreamHelper, accumulate its content and concatenate it into a
  2541.  * complete block.
  2542.  * @param {StreamHelper} helper the helper to use.
  2543.  * @param {Function} updateCallback a callback called on each update. Called
  2544.  * with one arg :
  2545.  * - the metadata linked to the update received.
  2546.  * @return Promise the promise for the accumulation.
  2547.  */
  2548. function accumulate(helper, updateCallback) {
  2549.     return new external.Promise(function (resolve, reject){
  2550.         var dataArray = [];
  2551.         var chunkType = helper._internalType,
  2552.             resultType = helper._outputType,
  2553.             mimeType = helper._mimeType;
  2554.         helper
  2555.         .on('data', function (data, meta) {
  2556.             dataArray.push(data);
  2557.             if(updateCallback) {
  2558.                 updateCallback(meta);
  2559.             }
  2560.         })
  2561.         .on('error', function(err) {
  2562.             dataArray = [];
  2563.             reject(err);
  2564.         })
  2565.         .on('end', function (){
  2566.             try {
  2567.                 var result = transformZipOutput(resultType, chunkType, dataArray, mimeType);
  2568.                 resolve(result);
  2569.             } catch (e) {
  2570.                 reject(e);
  2571.             }
  2572.             dataArray = [];
  2573.         })
  2574.         .resume();
  2575.     });
  2576. }
  2577.  
  2578. /**
  2579.  * An helper to easily use workers outside of JSZip.
  2580.  * @constructor
  2581.  * @param {Worker} worker the worker to wrap
  2582.  * @param {String} outputType the type of data expected by the use
  2583.  * @param {String} mimeType the mime type of the content, if applicable.
  2584.  */
  2585. function StreamHelper(worker, outputType, mimeType) {
  2586.     var internalType = outputType;
  2587.     switch(outputType) {
  2588.         case "blob":
  2589.             internalType = "arraybuffer";
  2590.         break;
  2591.         case "arraybuffer":
  2592.             internalType = "uint8array";
  2593.         break;
  2594.         case "base64":
  2595.             internalType = "string";
  2596.         break;
  2597.     }
  2598.  
  2599.     try {
  2600.         // the type used internally
  2601.         this._internalType = internalType;
  2602.         // the type used to output results
  2603.         this._outputType = outputType;
  2604.         // the mime type
  2605.         this._mimeType = mimeType;
  2606.         utils.checkSupport(internalType);
  2607.         this._worker = worker.pipe(new ConvertWorker(internalType));
  2608.         // the last workers can be rewired without issues but we need to
  2609.         // prevent any updates on previous workers.
  2610.         worker.lock();
  2611.     } catch(e) {
  2612.         this._worker = new GenericWorker("error");
  2613.         this._worker.error(e);
  2614.     }
  2615. }
  2616.  
  2617. StreamHelper.prototype = {
  2618.     /**
  2619.      * Listen a StreamHelper, accumulate its content and concatenate it into a
  2620.      * complete block.
  2621.      * @param {Function} updateCb the update callback.
  2622.      * @return Promise the promise for the accumulation.
  2623.      */
  2624.     accumulate : function (updateCb) {
  2625.         return accumulate(this, updateCb);
  2626.     },
  2627.     /**
  2628.      * Add a listener on an event triggered on a stream.
  2629.      * @param {String} evt the name of the event
  2630.      * @param {Function} fn the listener
  2631.      * @return {StreamHelper} the current helper.
  2632.      */
  2633.     on : function (evt, fn) {
  2634.         var self = this;
  2635.  
  2636.         if(evt === "data") {
  2637.             this._worker.on(evt, function (chunk) {
  2638.                 fn.call(self, chunk.data, chunk.meta);
  2639.             });
  2640.         } else {
  2641.             this._worker.on(evt, function () {
  2642.                 utils.delay(fn, arguments, self);
  2643.             });
  2644.         }
  2645.         return this;
  2646.     },
  2647.     /**
  2648.      * Resume the flow of chunks.
  2649.      * @return {StreamHelper} the current helper.
  2650.      */
  2651.     resume : function () {
  2652.         utils.delay(this._worker.resume, [], this._worker);
  2653.         return this;
  2654.     },
  2655.     /**
  2656.      * Pause the flow of chunks.
  2657.      * @return {StreamHelper} the current helper.
  2658.      */
  2659.     pause : function () {
  2660.         this._worker.pause();
  2661.         return this;
  2662.     },
  2663.     /**
  2664.      * Return a nodejs stream for this helper.
  2665.      * @param {Function} updateCb the update callback.
  2666.      * @return {NodejsStreamOutputAdapter} the nodejs stream.
  2667.      */
  2668.     toNodejsStream : function (updateCb) {
  2669.         utils.checkSupport("nodestream");
  2670.         if (this._outputType !== "nodebuffer") {
  2671.             // an object stream containing blob/arraybuffer/uint8array/string
  2672.             // is strange and I don't know if it would be useful.
  2673.             // I you find this comment and have a good usecase, please open a
  2674.             // bug report !
  2675.             throw new Error(this._outputType + " is not supported by this method");
  2676.         }
  2677.  
  2678.         return new NodejsStreamOutputAdapter(this, {
  2679.             objectMode : this._outputType !== "nodebuffer"
  2680.         }, updateCb);
  2681.     }
  2682. };
  2683.  
  2684.  
  2685. module.exports = StreamHelper;
  2686.  
  2687. },{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
  2688. 'use strict';
  2689.  
  2690. exports.base64 = true;
  2691. exports.array = true;
  2692. exports.string = true;
  2693. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  2694. exports.nodebuffer = typeof Buffer !== "undefined";
  2695. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  2696. exports.uint8array = typeof Uint8Array !== "undefined";
  2697.  
  2698. if (typeof ArrayBuffer === "undefined") {
  2699.     exports.blob = false;
  2700. }
  2701. else {
  2702.     var buffer = new ArrayBuffer(0);
  2703.     try {
  2704.         exports.blob = new Blob([buffer], {
  2705.             type: "application/zip"
  2706.         }).size === 0;
  2707.     }
  2708.     catch (e) {
  2709.         try {
  2710.             var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  2711.             var builder = new Builder();
  2712.             builder.append(buffer);
  2713.             exports.blob = builder.getBlob('application/zip').size === 0;
  2714.         }
  2715.         catch (e) {
  2716.             exports.blob = false;
  2717.         }
  2718.     }
  2719. }
  2720.  
  2721. try {
  2722.     exports.nodestream = !!require('readable-stream').Readable;
  2723. } catch(e) {
  2724.     exports.nodestream = false;
  2725. }
  2726.  
  2727. },{"readable-stream":16}],31:[function(require,module,exports){
  2728. 'use strict';
  2729.  
  2730. var utils = require('./utils');
  2731. var support = require('./support');
  2732. var nodejsUtils = require('./nodejsUtils');
  2733. var GenericWorker = require('./stream/GenericWorker');
  2734.  
  2735. /**
  2736.  * The following functions come from pako, from pako/lib/utils/strings
  2737.  * released under the MIT license, see pako https://github.com/nodeca/pako/
  2738.  */
  2739.  
  2740. // Table with utf8 lengths (calculated by first byte of sequence)
  2741. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  2742. // because max possible codepoint is 0x10ffff
  2743. var _utf8len = new Array(256);
  2744. for (var i=0; i<256; i++) {
  2745.   _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  2746. }
  2747. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  2748.  
  2749. // convert string to array (typed, when possible)
  2750. var string2buf = function (str) {
  2751.     var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  2752.  
  2753.     // count binary size
  2754.     for (m_pos = 0; m_pos < str_len; m_pos++) {
  2755.         c = str.charCodeAt(m_pos);
  2756.         if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2757.             c2 = str.charCodeAt(m_pos+1);
  2758.             if ((c2 & 0xfc00) === 0xdc00) {
  2759.                 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2760.                 m_pos++;
  2761.             }
  2762.         }
  2763.         buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  2764.     }
  2765.  
  2766.     // allocate buffer
  2767.     if (support.uint8array) {
  2768.         buf = new Uint8Array(buf_len);
  2769.     } else {
  2770.         buf = new Array(buf_len);
  2771.     }
  2772.  
  2773.     // convert
  2774.     for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  2775.         c = str.charCodeAt(m_pos);
  2776.         if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2777.             c2 = str.charCodeAt(m_pos+1);
  2778.             if ((c2 & 0xfc00) === 0xdc00) {
  2779.                 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2780.                 m_pos++;
  2781.             }
  2782.         }
  2783.         if (c < 0x80) {
  2784.             /* one byte */
  2785.             buf[i++] = c;
  2786.         } else if (c < 0x800) {
  2787.             /* two bytes */
  2788.             buf[i++] = 0xC0 | (c >>> 6);
  2789.             buf[i++] = 0x80 | (c & 0x3f);
  2790.         } else if (c < 0x10000) {
  2791.             /* three bytes */
  2792.             buf[i++] = 0xE0 | (c >>> 12);
  2793.             buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2794.             buf[i++] = 0x80 | (c & 0x3f);
  2795.         } else {
  2796.             /* four bytes */
  2797.             buf[i++] = 0xf0 | (c >>> 18);
  2798.             buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  2799.             buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2800.             buf[i++] = 0x80 | (c & 0x3f);
  2801.         }
  2802.     }
  2803.  
  2804.     return buf;
  2805. };
  2806.  
  2807. // Calculate max possible position in utf8 buffer,
  2808. // that will not break sequence. If that's not possible
  2809. // - (very small limits) return max size as is.
  2810. //
  2811. // buf[] - utf8 bytes array
  2812. // max   - length limit (mandatory);
  2813. var utf8border = function(buf, max) {
  2814.     var pos;
  2815.  
  2816.     max = max || buf.length;
  2817.     if (max > buf.length) { max = buf.length; }
  2818.  
  2819.     // go back from last position, until start of sequence found
  2820.     pos = max-1;
  2821.     while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  2822.  
  2823.     // Fuckup - very small and broken sequence,
  2824.     // return max, because we should return something anyway.
  2825.     if (pos < 0) { return max; }
  2826.  
  2827.     // If we came to start of buffer - that means vuffer is too small,
  2828.     // return max too.
  2829.     if (pos === 0) { return max; }
  2830.  
  2831.     return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  2832. };
  2833.  
  2834. // convert array to string
  2835. var buf2string = function (buf) {
  2836.     var str, i, out, c, c_len;
  2837.     var len = buf.length;
  2838.  
  2839.     // Reserve max possible length (2 words per char)
  2840.     // NB: by unknown reasons, Array is significantly faster for
  2841.     //     String.fromCharCode.apply than Uint16Array.
  2842.     var utf16buf = new Array(len*2);
  2843.  
  2844.     for (out=0, i=0; i<len;) {
  2845.         c = buf[i++];
  2846.         // quick process ascii
  2847.         if (c < 0x80) { utf16buf[out++] = c; continue; }
  2848.  
  2849.         c_len = _utf8len[c];
  2850.         // skip 5 & 6 byte codes
  2851.         if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  2852.  
  2853.         // apply mask on first byte
  2854.         c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  2855.         // join the rest
  2856.         while (c_len > 1 && i < len) {
  2857.             c = (c << 6) | (buf[i++] & 0x3f);
  2858.             c_len--;
  2859.         }
  2860.  
  2861.         // terminated by end of string?
  2862.         if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  2863.  
  2864.         if (c < 0x10000) {
  2865.             utf16buf[out++] = c;
  2866.         } else {
  2867.             c -= 0x10000;
  2868.             utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  2869.             utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  2870.         }
  2871.     }
  2872.  
  2873.     // shrinkBuf(utf16buf, out)
  2874.     if (utf16buf.length !== out) {
  2875.         if(utf16buf.subarray) {
  2876.             utf16buf = utf16buf.subarray(0, out);
  2877.         } else {
  2878.             utf16buf.length = out;
  2879.         }
  2880.     }
  2881.  
  2882.     // return String.fromCharCode.apply(null, utf16buf);
  2883.     return utils.applyFromCharCode(utf16buf);
  2884. };
  2885.  
  2886.  
  2887. // That's all for the pako functions.
  2888.  
  2889.  
  2890. /**
  2891.  * Transform a javascript string into an array (typed if possible) of bytes,
  2892.  * UTF-8 encoded.
  2893.  * @param {String} str the string to encode
  2894.  * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  2895.  */
  2896. exports.utf8encode = function utf8encode(str) {
  2897.     if (support.nodebuffer) {
  2898.         return nodejsUtils.newBuffer(str, "utf-8");
  2899.     }
  2900.  
  2901.     return string2buf(str);
  2902. };
  2903.  
  2904.  
  2905. /**
  2906.  * Transform a bytes array (or a representation) representing an UTF-8 encoded
  2907.  * string into a javascript string.
  2908.  * @param {Array|Uint8Array|Buffer} buf the data de decode
  2909.  * @return {String} the decoded string.
  2910.  */
  2911. exports.utf8decode = function utf8decode(buf) {
  2912.     if (support.nodebuffer) {
  2913.         return utils.transformTo("nodebuffer", buf).toString("utf-8");
  2914.     }
  2915.  
  2916.     buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  2917.  
  2918.     return buf2string(buf);
  2919. };
  2920.  
  2921. /**
  2922.  * A worker to decode utf8 encoded binary chunks into string chunks.
  2923.  * @constructor
  2924.  */
  2925. function Utf8DecodeWorker() {
  2926.     GenericWorker.call(this, "utf-8 decode");
  2927.     // the last bytes if a chunk didn't end with a complete codepoint.
  2928.     this.leftOver = null;
  2929. }
  2930. utils.inherits(Utf8DecodeWorker, GenericWorker);
  2931.  
  2932. /**
  2933.  * @see GenericWorker.processChunk
  2934.  */
  2935. Utf8DecodeWorker.prototype.processChunk = function (chunk) {
  2936.  
  2937.     var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
  2938.  
  2939.     // 1st step, re-use what's left of the previous chunk
  2940.     if (this.leftOver && this.leftOver.length) {
  2941.         if(support.uint8array) {
  2942.             var previousData = data;
  2943.             data = new Uint8Array(previousData.length + this.leftOver.length);
  2944.             data.set(this.leftOver, 0);
  2945.             data.set(previousData, this.leftOver.length);
  2946.         } else {
  2947.             data = this.leftOver.concat(data);
  2948.         }
  2949.         this.leftOver = null;
  2950.     }
  2951.  
  2952.     var nextBoundary = utf8border(data);
  2953.     var usableData = data;
  2954.     if (nextBoundary !== data.length) {
  2955.         if (support.uint8array) {
  2956.             usableData = data.subarray(0, nextBoundary);
  2957.             this.leftOver = data.subarray(nextBoundary, data.length);
  2958.         } else {
  2959.             usableData = data.slice(0, nextBoundary);
  2960.             this.leftOver = data.slice(nextBoundary, data.length);
  2961.         }
  2962.     }
  2963.  
  2964.     this.push({
  2965.         data : exports.utf8decode(usableData),
  2966.         meta : chunk.meta
  2967.     });
  2968. };
  2969.  
  2970. /**
  2971.  * @see GenericWorker.flush
  2972.  */
  2973. Utf8DecodeWorker.prototype.flush = function () {
  2974.     if(this.leftOver && this.leftOver.length) {
  2975.         this.push({
  2976.             data : exports.utf8decode(this.leftOver),
  2977.             meta : {}
  2978.         });
  2979.         this.leftOver = null;
  2980.     }
  2981. };
  2982. exports.Utf8DecodeWorker = Utf8DecodeWorker;
  2983.  
  2984. /**
  2985.  * A worker to endcode string chunks into utf8 encoded binary chunks.
  2986.  * @constructor
  2987.  */
  2988. function Utf8EncodeWorker() {
  2989.     GenericWorker.call(this, "utf-8 encode");
  2990. }
  2991. utils.inherits(Utf8EncodeWorker, GenericWorker);
  2992.  
  2993. /**
  2994.  * @see GenericWorker.processChunk
  2995.  */
  2996. Utf8EncodeWorker.prototype.processChunk = function (chunk) {
  2997.     this.push({
  2998.         data : exports.utf8encode(chunk.data),
  2999.         meta : chunk.meta
  3000.     });
  3001. };
  3002. exports.Utf8EncodeWorker = Utf8EncodeWorker;
  3003.  
  3004. },{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
  3005. 'use strict';
  3006.  
  3007. var support = require('./support');
  3008. var base64 = require('./base64');
  3009. var nodejsUtils = require('./nodejsUtils');
  3010. var setImmediate = require('core-js/library/fn/set-immediate');
  3011. var external = require("./external");
  3012.  
  3013.  
  3014. /**
  3015.  * Convert a string that pass as a "binary string": it should represent a byte
  3016.  * array but may have > 255 char codes. Be sure to take only the first byte
  3017.  * and returns the byte array.
  3018.  * @param {String} str the string to transform.
  3019.  * @return {Array|Uint8Array} the string in a binary format.
  3020.  */
  3021. function string2binary(str) {
  3022.     var result = null;
  3023.     if (support.uint8array) {
  3024.       result = new Uint8Array(str.length);
  3025.     } else {
  3026.       result = new Array(str.length);
  3027.     }
  3028.     return stringToArrayLike(str, result);
  3029. }
  3030.  
  3031. /**
  3032.  * Create a new blob with the given content and the given type.
  3033.  * @param {Array[String|ArrayBuffer]} parts the content to put in the blob. DO NOT use
  3034.  * an Uint8Array because the stock browser of android 4 won't accept it (it
  3035.  * will be silently converted to a string, "[object Uint8Array]").
  3036.  * @param {String} type the mime type of the blob.
  3037.  * @return {Blob} the created blob.
  3038.  */
  3039. exports.newBlob = function(parts, type) {
  3040.     exports.checkSupport("blob");
  3041.  
  3042.     try {
  3043.         // Blob constructor
  3044.         return new Blob(parts, {
  3045.             type: type
  3046.         });
  3047.     }
  3048.     catch (e) {
  3049.  
  3050.         try {
  3051.             // deprecated, browser only, old way
  3052.             var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  3053.             var builder = new Builder();
  3054.             for (var i = 0; i < parts.length; i++) {
  3055.                 builder.append(parts[i]);
  3056.             }
  3057.             return builder.getBlob(type);
  3058.         }
  3059.         catch (e) {
  3060.  
  3061.             // well, fuck ?!
  3062.             throw new Error("Bug : can't construct the Blob.");
  3063.         }
  3064.     }
  3065.  
  3066.  
  3067. };
  3068. /**
  3069.  * The identity function.
  3070.  * @param {Object} input the input.
  3071.  * @return {Object} the same input.
  3072.  */
  3073. function identity(input) {
  3074.     return input;
  3075. }
  3076.  
  3077. /**
  3078.  * Fill in an array with a string.
  3079.  * @param {String} str the string to use.
  3080.  * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  3081.  * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  3082.  */
  3083. function stringToArrayLike(str, array) {
  3084.     for (var i = 0; i < str.length; ++i) {
  3085.         array[i] = str.charCodeAt(i) & 0xFF;
  3086.     }
  3087.     return array;
  3088. }
  3089.  
  3090. /**
  3091.  * An helper for the function arrayLikeToString.
  3092.  * This contains static informations and functions that
  3093.  * can be optimized by the browser JIT compiler.
  3094.  */
  3095. var arrayToStringHelper = {
  3096.     /**
  3097.      * Transform an array of int into a string, chunk by chunk.
  3098.      * See the performances notes on arrayLikeToString.
  3099.      * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3100.      * @param {String} type the type of the array.
  3101.      * @param {Integer} chunk the chunk size.
  3102.      * @return {String} the resulting string.
  3103.      * @throws Error if the chunk is too big for the stack.
  3104.      */
  3105.     stringifyByChunk: function(array, type, chunk) {
  3106.         var result = [], k = 0, len = array.length;
  3107.         // shortcut
  3108.         if (len <= chunk) {
  3109.             return String.fromCharCode.apply(null, array);
  3110.         }
  3111.         while (k < len) {
  3112.             if (type === "array" || type === "nodebuffer") {
  3113.                 result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  3114.             }
  3115.             else {
  3116.                 result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  3117.             }
  3118.             k += chunk;
  3119.         }
  3120.         return result.join("");
  3121.     },
  3122.     /**
  3123.      * Call String.fromCharCode on every item in the array.
  3124.      * This is the naive implementation, which generate A LOT of intermediate string.
  3125.      * This should be used when everything else fail.
  3126.      * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3127.      * @return {String} the result.
  3128.      */
  3129.     stringifyByChar: function(array){
  3130.         var resultStr = "";
  3131.         for(var i = 0; i < array.length; i++) {
  3132.             resultStr += String.fromCharCode(array[i]);
  3133.         }
  3134.         return resultStr;
  3135.     },
  3136.     applyCanBeUsed : {
  3137.         /**
  3138.          * true if the browser accepts to use String.fromCharCode on Uint8Array
  3139.          */
  3140.         uint8array : (function () {
  3141.             try {
  3142.                 return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
  3143.             } catch (e) {
  3144.                 return false;
  3145.             }
  3146.         })(),
  3147.         /**
  3148.          * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
  3149.          */
  3150.         nodebuffer : (function () {
  3151.             try {
  3152.                 return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.newBuffer(1)).length === 1;
  3153.             } catch (e) {
  3154.                 return false;
  3155.             }
  3156.         })()
  3157.     }
  3158. };
  3159.  
  3160. /**
  3161.  * Transform an array-like object to a string.
  3162.  * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  3163.  * @return {String} the result.
  3164.  */
  3165. function arrayLikeToString(array) {
  3166.     // Performances notes :
  3167.     // --------------------
  3168.     // String.fromCharCode.apply(null, array) is the fastest, see
  3169.     // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  3170.     // but the stack is limited (and we can get huge arrays !).
  3171.     //
  3172.     // result += String.fromCharCode(array[i]); generate too many strings !
  3173.     //
  3174.     // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  3175.     // TODO : we now have workers that split the work. Do we still need that ?
  3176.     var chunk = 65536,
  3177.         type = exports.getTypeOf(array),
  3178.         canUseApply = true;
  3179.     if (type === "uint8array") {
  3180.         canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
  3181.     } else if (type === "nodebuffer") {
  3182.         canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
  3183.     }
  3184.  
  3185.     if (canUseApply) {
  3186.         while (chunk > 1) {
  3187.             try {
  3188.                 return arrayToStringHelper.stringifyByChunk(array, type, chunk);
  3189.             } catch (e) {
  3190.                 chunk = Math.floor(chunk / 2);
  3191.             }
  3192.         }
  3193.     }
  3194.  
  3195.     // no apply or chunk error : slow and painful algorithm
  3196.     // default browser on android 4.*
  3197.     return arrayToStringHelper.stringifyByChar(array);
  3198. }
  3199.  
  3200. exports.applyFromCharCode = arrayLikeToString;
  3201.  
  3202.  
  3203. /**
  3204.  * Copy the data from an array-like to an other array-like.
  3205.  * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  3206.  * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  3207.  * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  3208.  */
  3209. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  3210.     for (var i = 0; i < arrayFrom.length; i++) {
  3211.         arrayTo[i] = arrayFrom[i];
  3212.     }
  3213.     return arrayTo;
  3214. }
  3215.  
  3216. // a matrix containing functions to transform everything into everything.
  3217. var transform = {};
  3218.  
  3219. // string to ?
  3220. transform["string"] = {
  3221.     "string": identity,
  3222.     "array": function(input) {
  3223.         return stringToArrayLike(input, new Array(input.length));
  3224.     },
  3225.     "arraybuffer": function(input) {
  3226.         return transform["string"]["uint8array"](input).buffer;
  3227.     },
  3228.     "uint8array": function(input) {
  3229.         return stringToArrayLike(input, new Uint8Array(input.length));
  3230.     },
  3231.     "nodebuffer": function(input) {
  3232.         return stringToArrayLike(input, nodejsUtils.newBuffer(input.length));
  3233.     }
  3234. };
  3235.  
  3236. // array to ?
  3237. transform["array"] = {
  3238.     "string": arrayLikeToString,
  3239.     "array": identity,
  3240.     "arraybuffer": function(input) {
  3241.         return (new Uint8Array(input)).buffer;
  3242.     },
  3243.     "uint8array": function(input) {
  3244.         return new Uint8Array(input);
  3245.     },
  3246.     "nodebuffer": function(input) {
  3247.         return nodejsUtils.newBuffer(input);
  3248.     }
  3249. };
  3250.  
  3251. // arraybuffer to ?
  3252. transform["arraybuffer"] = {
  3253.     "string": function(input) {
  3254.         return arrayLikeToString(new Uint8Array(input));
  3255.     },
  3256.     "array": function(input) {
  3257.         return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  3258.     },
  3259.     "arraybuffer": identity,
  3260.     "uint8array": function(input) {
  3261.         return new Uint8Array(input);
  3262.     },
  3263.     "nodebuffer": function(input) {
  3264.         return nodejsUtils.newBuffer(new Uint8Array(input));
  3265.     }
  3266. };
  3267.  
  3268. // uint8array to ?
  3269. transform["uint8array"] = {
  3270.     "string": arrayLikeToString,
  3271.     "array": function(input) {
  3272.         return arrayLikeToArrayLike(input, new Array(input.length));
  3273.     },
  3274.     "arraybuffer": function(input) {
  3275.         // copy the uint8array: DO NOT propagate the original ArrayBuffer, it
  3276.         // can be way larger (the whole zip file for example).
  3277.         var copy = new Uint8Array(input.length);
  3278.         if (input.length) {
  3279.             copy.set(input, 0);
  3280.         }
  3281.         return copy.buffer;
  3282.     },
  3283.     "uint8array": identity,
  3284.     "nodebuffer": function(input) {
  3285.         return nodejsUtils.newBuffer(input);
  3286.     }
  3287. };
  3288.  
  3289. // nodebuffer to ?
  3290. transform["nodebuffer"] = {
  3291.     "string": arrayLikeToString,
  3292.     "array": function(input) {
  3293.         return arrayLikeToArrayLike(input, new Array(input.length));
  3294.     },
  3295.     "arraybuffer": function(input) {
  3296.         return transform["nodebuffer"]["uint8array"](input).buffer;
  3297.     },
  3298.     "uint8array": function(input) {
  3299.         return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  3300.     },
  3301.     "nodebuffer": identity
  3302. };
  3303.  
  3304. /**
  3305.  * Transform an input into any type.
  3306.  * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  3307.  * If no output type is specified, the unmodified input will be returned.
  3308.  * @param {String} outputType the output type.
  3309.  * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  3310.  * @throws {Error} an Error if the browser doesn't support the requested output type.
  3311.  */
  3312. exports.transformTo = function(outputType, input) {
  3313.     if (!input) {
  3314.         // undefined, null, etc
  3315.         // an empty string won't harm.
  3316.         input = "";
  3317.     }
  3318.     if (!outputType) {
  3319.         return input;
  3320.     }
  3321.     exports.checkSupport(outputType);
  3322.     var inputType = exports.getTypeOf(input);
  3323.     var result = transform[inputType][outputType](input);
  3324.     return result;
  3325. };
  3326.  
  3327. /**
  3328.  * Return the type of the input.
  3329.  * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  3330.  * @param {Object} input the input to identify.
  3331.  * @return {String} the (lowercase) type of the input.
  3332.  */
  3333. exports.getTypeOf = function(input) {
  3334.     if (typeof input === "string") {
  3335.         return "string";
  3336.     }
  3337.     if (Object.prototype.toString.call(input) === "[object Array]") {
  3338.         return "array";
  3339.     }
  3340.     if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
  3341.         return "nodebuffer";
  3342.     }
  3343.     if (support.uint8array && input instanceof Uint8Array) {
  3344.         return "uint8array";
  3345.     }
  3346.     if (support.arraybuffer && input instanceof ArrayBuffer) {
  3347.         return "arraybuffer";
  3348.     }
  3349. };
  3350.  
  3351. /**
  3352.  * Throw an exception if the type is not supported.
  3353.  * @param {String} type the type to check.
  3354.  * @throws {Error} an Error if the browser doesn't support the requested type.
  3355.  */
  3356. exports.checkSupport = function(type) {
  3357.     var supported = support[type.toLowerCase()];
  3358.     if (!supported) {
  3359.         throw new Error(type + " is not supported by this platform");
  3360.     }
  3361. };
  3362.  
  3363. exports.MAX_VALUE_16BITS = 65535;
  3364. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  3365.  
  3366. /**
  3367.  * Prettify a string read as binary.
  3368.  * @param {string} str the string to prettify.
  3369.  * @return {string} a pretty string.
  3370.  */
  3371. exports.pretty = function(str) {
  3372.     var res = '',
  3373.         code, i;
  3374.     for (i = 0; i < (str || "").length; i++) {
  3375.         code = str.charCodeAt(i);
  3376.         res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  3377.     }
  3378.     return res;
  3379. };
  3380.  
  3381. /**
  3382.  * Defer the call of a function.
  3383.  * @param {Function} callback the function to call asynchronously.
  3384.  * @param {Array} args the arguments to give to the callback.
  3385.  */
  3386. exports.delay = function(callback, args, self) {
  3387.     setImmediate(function () {
  3388.         callback.apply(self || null, args || []);
  3389.     });
  3390. };
  3391.  
  3392. /**
  3393.  * Extends a prototype with an other, without calling a constructor with
  3394.  * side effects. Inspired by nodejs' `utils.inherits`
  3395.  * @param {Function} ctor the constructor to augment
  3396.  * @param {Function} superCtor the parent constructor to use
  3397.  */
  3398. exports.inherits = function (ctor, superCtor) {
  3399.     var Obj = function() {};
  3400.     Obj.prototype = superCtor.prototype;
  3401.     ctor.prototype = new Obj();
  3402. };
  3403.  
  3404. /**
  3405.  * Merge the objects passed as parameters into a new one.
  3406.  * @private
  3407.  * @param {...Object} var_args All objects to merge.
  3408.  * @return {Object} a new object with the data of the others.
  3409.  */
  3410. exports.extend = function() {
  3411.     var result = {}, i, attr;
  3412.     for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  3413.         for (attr in arguments[i]) {
  3414.             if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  3415.                 result[attr] = arguments[i][attr];
  3416.             }
  3417.         }
  3418.     }
  3419.     return result;
  3420. };
  3421.  
  3422. /**
  3423.  * Transform arbitrary content into a Promise.
  3424.  * @param {String} name a name for the content being processed.
  3425.  * @param {Object} inputData the content to process.
  3426.  * @param {Boolean} isBinary true if the content is not an unicode string
  3427.  * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
  3428.  * @param {Boolean} isBase64 true if the string content is encoded with base64.
  3429.  * @return {Promise} a promise in a format usable by JSZip.
  3430.  */
  3431. exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
  3432.  
  3433.     // if inputData is already a promise, this flatten it.
  3434.     var promise = external.Promise.resolve(inputData).then(function(data) {
  3435.        
  3436.        
  3437.         var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
  3438.  
  3439.         if (isBlob && typeof FileReader !== "undefined") {
  3440.             return new external.Promise(function (resolve, reject) {
  3441.                 var reader = new FileReader();
  3442.  
  3443.                 reader.onload = function(e) {
  3444.                     resolve(e.target.result);
  3445.                 };
  3446.                 reader.onerror = function(e) {
  3447.                     reject(e.target.error);
  3448.                 };
  3449.                 reader.readAsArrayBuffer(data);
  3450.             });
  3451.         } else {
  3452.             return data;
  3453.         }
  3454.     });
  3455.  
  3456.     return promise.then(function(data) {
  3457.         var dataType = exports.getTypeOf(data);
  3458.  
  3459.         if (!dataType) {
  3460.             return external.Promise.reject(
  3461.                 new Error("The data of '" + name + "' is in an unsupported format !")
  3462.             );
  3463.         }
  3464.         // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  3465.         if (dataType === "arraybuffer") {
  3466.             data = exports.transformTo("uint8array", data);
  3467.         } else if (dataType === "string") {
  3468.             if (isBase64) {
  3469.                 data = base64.decode(data);
  3470.             }
  3471.             else if (isBinary) {
  3472.                 // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
  3473.                 if (isOptimizedBinaryString !== true) {
  3474.                     // this is a string, not in a base64 format.
  3475.                     // Be sure that this is a correct "binary string"
  3476.                     data = string2binary(data);
  3477.                 }
  3478.             }
  3479.         }
  3480.         return data;
  3481.     });
  3482. };
  3483.  
  3484. },{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"core-js/library/fn/set-immediate":36}],33:[function(require,module,exports){
  3485. 'use strict';
  3486. var readerFor = require('./reader/readerFor');
  3487. var utils = require('./utils');
  3488. var sig = require('./signature');
  3489. var ZipEntry = require('./zipEntry');
  3490. var utf8 = require('./utf8');
  3491. var support = require('./support');
  3492. //  class ZipEntries {{{
  3493. /**
  3494.  * All the entries in the zip file.
  3495.  * @constructor
  3496.  * @param {Object} loadOptions Options for loading the stream.
  3497.  */
  3498. function ZipEntries(loadOptions) {
  3499.     this.files = [];
  3500.     this.loadOptions = loadOptions;
  3501. }
  3502. ZipEntries.prototype = {
  3503.     /**
  3504.      * Check that the reader is on the speficied signature.
  3505.      * @param {string} expectedSignature the expected signature.
  3506.      * @throws {Error} if it is an other signature.
  3507.      */
  3508.     checkSignature: function(expectedSignature) {
  3509.         if (!this.reader.readAndCheckSignature(expectedSignature)) {
  3510.             this.reader.index -= 4;
  3511.             var signature = this.reader.readString(4);
  3512.             throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  3513.         }
  3514.     },
  3515.     /**
  3516.      * Check if the given signature is at the given index.
  3517.      * @param {number} askedIndex the index to check.
  3518.      * @param {string} expectedSignature the signature to expect.
  3519.      * @return {boolean} true if the signature is here, false otherwise.
  3520.      */
  3521.     isSignature: function(askedIndex, expectedSignature) {
  3522.         var currentIndex = this.reader.index;
  3523.         this.reader.setIndex(askedIndex);
  3524.         var signature = this.reader.readString(4);
  3525.         var result = signature === expectedSignature;
  3526.         this.reader.setIndex(currentIndex);
  3527.         return result;
  3528.     },
  3529.     /**
  3530.      * Read the end of the central directory.
  3531.      */
  3532.     readBlockEndOfCentral: function() {
  3533.         this.diskNumber = this.reader.readInt(2);
  3534.         this.diskWithCentralDirStart = this.reader.readInt(2);
  3535.         this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  3536.         this.centralDirRecords = this.reader.readInt(2);
  3537.         this.centralDirSize = this.reader.readInt(4);
  3538.         this.centralDirOffset = this.reader.readInt(4);
  3539.  
  3540.         this.zipCommentLength = this.reader.readInt(2);
  3541.         // warning : the encoding depends of the system locale
  3542.         // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  3543.         // On a windows machine, this field is encoded with the localized windows code page.
  3544.         var zipComment = this.reader.readData(this.zipCommentLength);
  3545.         var decodeParamType = support.uint8array ? "uint8array" : "array";
  3546.         // To get consistent behavior with the generation part, we will assume that
  3547.         // this is utf8 encoded unless specified otherwise.
  3548.         var decodeContent = utils.transformTo(decodeParamType, zipComment);
  3549.         this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  3550.     },
  3551.     /**
  3552.      * Read the end of the Zip 64 central directory.
  3553.      * Not merged with the method readEndOfCentral :
  3554.      * The end of central can coexist with its Zip64 brother,
  3555.      * I don't want to read the wrong number of bytes !
  3556.      */
  3557.     readBlockZip64EndOfCentral: function() {
  3558.         this.zip64EndOfCentralSize = this.reader.readInt(8);
  3559.         this.reader.skip(4);
  3560.         // this.versionMadeBy = this.reader.readString(2);
  3561.         // this.versionNeeded = this.reader.readInt(2);
  3562.         this.diskNumber = this.reader.readInt(4);
  3563.         this.diskWithCentralDirStart = this.reader.readInt(4);
  3564.         this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  3565.         this.centralDirRecords = this.reader.readInt(8);
  3566.         this.centralDirSize = this.reader.readInt(8);
  3567.         this.centralDirOffset = this.reader.readInt(8);
  3568.  
  3569.         this.zip64ExtensibleData = {};
  3570.         var extraDataSize = this.zip64EndOfCentralSize - 44,
  3571.             index = 0,
  3572.             extraFieldId,
  3573.             extraFieldLength,
  3574.             extraFieldValue;
  3575.         while (index < extraDataSize) {
  3576.             extraFieldId = this.reader.readInt(2);
  3577.             extraFieldLength = this.reader.readInt(4);
  3578.             extraFieldValue = this.reader.readData(extraFieldLength);
  3579.             this.zip64ExtensibleData[extraFieldId] = {
  3580.                 id: extraFieldId,
  3581.                 length: extraFieldLength,
  3582.                 value: extraFieldValue
  3583.             };
  3584.         }
  3585.     },
  3586.     /**
  3587.      * Read the end of the Zip 64 central directory locator.
  3588.      */
  3589.     readBlockZip64EndOfCentralLocator: function() {
  3590.         this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  3591.         this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  3592.         this.disksCount = this.reader.readInt(4);
  3593.         if (this.disksCount > 1) {
  3594.             throw new Error("Multi-volumes zip are not supported");
  3595.         }
  3596.     },
  3597.     /**
  3598.      * Read the local files, based on the offset read in the central part.
  3599.      */
  3600.     readLocalFiles: function() {
  3601.         var i, file;
  3602.         for (i = 0; i < this.files.length; i++) {
  3603.             file = this.files[i];
  3604.             this.reader.setIndex(file.localHeaderOffset);
  3605.             this.checkSignature(sig.LOCAL_FILE_HEADER);
  3606.             file.readLocalPart(this.reader);
  3607.             file.handleUTF8();
  3608.             file.processAttributes();
  3609.         }
  3610.     },
  3611.     /**
  3612.      * Read the central directory.
  3613.      */
  3614.     readCentralDir: function() {
  3615.         var file;
  3616.  
  3617.         this.reader.setIndex(this.centralDirOffset);
  3618.         while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
  3619.             file = new ZipEntry({
  3620.                 zip64: this.zip64
  3621.             }, this.loadOptions);
  3622.             file.readCentralPart(this.reader);
  3623.             this.files.push(file);
  3624.         }
  3625.  
  3626.         if (this.centralDirRecords !== this.files.length) {
  3627.             if (this.centralDirRecords !== 0 && this.files.length === 0) {
  3628.                 // We expected some records but couldn't find ANY.
  3629.                 // This is really suspicious, as if something went wrong.
  3630.                 throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  3631.             } else {
  3632.                 // We found some records but not all.
  3633.                 // Something is wrong but we got something for the user: no error here.
  3634.                 // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  3635.             }
  3636.         }
  3637.     },
  3638.     /**
  3639.      * Read the end of central directory.
  3640.      */
  3641.     readEndOfCentral: function() {
  3642.         var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  3643.         if (offset < 0) {
  3644.             // Check if the content is a truncated zip or complete garbage.
  3645.             // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  3646.             // extractible zip for example) but it can give a good hint.
  3647.             // If an ajax request was used without responseType, we will also
  3648.             // get unreadable data.
  3649.             var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  3650.  
  3651.             if (isGarbage) {
  3652.                 throw new Error("Can't find end of central directory : is this a zip file ? " +
  3653.                                 "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
  3654.             } else {
  3655.                 throw new Error("Corrupted zip : can't find end of central directory");
  3656.             }
  3657.  
  3658.         }
  3659.         this.reader.setIndex(offset);
  3660.         var endOfCentralDirOffset = offset;
  3661.         this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  3662.         this.readBlockEndOfCentral();
  3663.  
  3664.  
  3665.         /* extract from the zip spec :
  3666.             4)  If one of the fields in the end of central directory
  3667.                 record is too small to hold required data, the field
  3668.                 should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  3669.                 ZIP64 format record should be created.
  3670.             5)  The end of central directory record and the
  3671.                 Zip64 end of central directory locator record must
  3672.                 reside on the same disk when splitting or spanning
  3673.                 an archive.
  3674.          */
  3675.         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) {
  3676.             this.zip64 = true;
  3677.  
  3678.             /*
  3679.             Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  3680.             the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  3681.             all numbers as 64-bit double precision IEEE 754 floating point numbers.
  3682.             So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  3683.             see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  3684.             and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  3685.             */
  3686.  
  3687.             // should look for a zip64 EOCD locator
  3688.             offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3689.             if (offset < 0) {
  3690.                 throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  3691.             }
  3692.             this.reader.setIndex(offset);
  3693.             this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3694.             this.readBlockZip64EndOfCentralLocator();
  3695.  
  3696.             // now the zip64 EOCD record
  3697.             if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  3698.                 // console.warn("ZIP64 end of central directory not where expected.");
  3699.                 this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3700.                 if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  3701.                     throw new Error("Corrupted zip : can't find the ZIP64 end of central directory");
  3702.                 }
  3703.             }
  3704.             this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  3705.             this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3706.             this.readBlockZip64EndOfCentral();
  3707.         }
  3708.  
  3709.         var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  3710.         if (this.zip64) {
  3711.             expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  3712.             expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  3713.         }
  3714.  
  3715.         var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  3716.  
  3717.         if (extraBytes > 0) {
  3718.             // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  3719.             if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  3720.                 // The offsets seem wrong, but we have something at the specified offset.
  3721.                 // So… we keep it.
  3722.             } else {
  3723.                 // the offset is wrong, update the "zero" of the reader
  3724.                 // this happens if data has been prepended (crx files for example)
  3725.                 this.reader.zero = extraBytes;
  3726.             }
  3727.         } else if (extraBytes < 0) {
  3728.             throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  3729.         }
  3730.     },
  3731.     prepareReader: function(data) {
  3732.         this.reader = readerFor(data);
  3733.     },
  3734.     /**
  3735.      * Read a zip file and create ZipEntries.
  3736.      * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  3737.      */
  3738.     load: function(data) {
  3739.         this.prepareReader(data);
  3740.         this.readEndOfCentral();
  3741.         this.readCentralDir();
  3742.         this.readLocalFiles();
  3743.     }
  3744. };
  3745. // }}} end of ZipEntries
  3746. module.exports = ZipEntries;
  3747.  
  3748. },{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
  3749. 'use strict';
  3750. var readerFor = require('./reader/readerFor');
  3751. var utils = require('./utils');
  3752. var CompressedObject = require('./compressedObject');
  3753. var crc32fn = require('./crc32');
  3754. var utf8 = require('./utf8');
  3755. var compressions = require('./compressions');
  3756. var support = require('./support');
  3757.  
  3758. var MADE_BY_DOS = 0x00;
  3759. var MADE_BY_UNIX = 0x03;
  3760.  
  3761. /**
  3762.  * Find a compression registered in JSZip.
  3763.  * @param {string} compressionMethod the method magic to find.
  3764.  * @return {Object|null} the JSZip compression object, null if none found.
  3765.  */
  3766. var findCompression = function(compressionMethod) {
  3767.     for (var method in compressions) {
  3768.         if (!compressions.hasOwnProperty(method)) {
  3769.             continue;
  3770.         }
  3771.         if (compressions[method].magic === compressionMethod) {
  3772.             return compressions[method];
  3773.         }
  3774.     }
  3775.     return null;
  3776. };
  3777.  
  3778. // class ZipEntry {{{
  3779. /**
  3780.  * An entry in the zip file.
  3781.  * @constructor
  3782.  * @param {Object} options Options of the current file.
  3783.  * @param {Object} loadOptions Options for loading the stream.
  3784.  */
  3785. function ZipEntry(options, loadOptions) {
  3786.     this.options = options;
  3787.     this.loadOptions = loadOptions;
  3788. }
  3789. ZipEntry.prototype = {
  3790.     /**
  3791.      * say if the file is encrypted.
  3792.      * @return {boolean} true if the file is encrypted, false otherwise.
  3793.      */
  3794.     isEncrypted: function() {
  3795.         // bit 1 is set
  3796.         return (this.bitFlag & 0x0001) === 0x0001;
  3797.     },
  3798.     /**
  3799.      * say if the file has utf-8 filename/comment.
  3800.      * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  3801.      */
  3802.     useUTF8: function() {
  3803.         // bit 11 is set
  3804.         return (this.bitFlag & 0x0800) === 0x0800;
  3805.     },
  3806.     /**
  3807.      * Read the local part of a zip file and add the info in this object.
  3808.      * @param {DataReader} reader the reader to use.
  3809.      */
  3810.     readLocalPart: function(reader) {
  3811.         var compression, localExtraFieldsLength;
  3812.  
  3813.         // we already know everything from the central dir !
  3814.         // If the central dir data are false, we are doomed.
  3815.         // On the bright side, the local part is scary  : zip64, data descriptors, both, etc.
  3816.         // The less data we get here, the more reliable this should be.
  3817.         // Let's skip the whole header and dash to the data !
  3818.         reader.skip(22);
  3819.         // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  3820.         // Strangely, the filename here is OK.
  3821.         // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  3822.         // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  3823.         // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  3824.         // the internet.
  3825.         //
  3826.         // I think I see the logic here : the central directory is used to display
  3827.         // content and the local directory is used to extract the files. Mixing / and \
  3828.         // may be used to display \ to windows users and use / when extracting the files.
  3829.         // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  3830.         this.fileNameLength = reader.readInt(2);
  3831.         localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  3832.         // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
  3833.         this.fileName = reader.readData(this.fileNameLength);
  3834.         reader.skip(localExtraFieldsLength);
  3835.  
  3836.         if (this.compressedSize === -1 || this.uncompressedSize === -1) {
  3837.             throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
  3838.         }
  3839.  
  3840.         compression = findCompression(this.compressionMethod);
  3841.         if (compression === null) { // no compression found
  3842.             throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  3843.         }
  3844.         this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
  3845.     },
  3846.  
  3847.     /**
  3848.      * Read the central part of a zip file and add the info in this object.
  3849.      * @param {DataReader} reader the reader to use.
  3850.      */
  3851.     readCentralPart: function(reader) {
  3852.         this.versionMadeBy = reader.readInt(2);
  3853.         reader.skip(2);
  3854.         // this.versionNeeded = reader.readInt(2);
  3855.         this.bitFlag = reader.readInt(2);
  3856.         this.compressionMethod = reader.readString(2);
  3857.         this.date = reader.readDate();
  3858.         this.crc32 = reader.readInt(4);
  3859.         this.compressedSize = reader.readInt(4);
  3860.         this.uncompressedSize = reader.readInt(4);
  3861.         var fileNameLength = reader.readInt(2);
  3862.         this.extraFieldsLength = reader.readInt(2);
  3863.         this.fileCommentLength = reader.readInt(2);
  3864.         this.diskNumberStart = reader.readInt(2);
  3865.         this.internalFileAttributes = reader.readInt(2);
  3866.         this.externalFileAttributes = reader.readInt(4);
  3867.         this.localHeaderOffset = reader.readInt(4);
  3868.  
  3869.         if (this.isEncrypted()) {
  3870.             throw new Error("Encrypted zip are not supported");
  3871.         }
  3872.  
  3873.         // will be read in the local part, see the comments there
  3874.         reader.skip(fileNameLength);
  3875.         this.readExtraFields(reader);
  3876.         this.parseZIP64ExtraField(reader);
  3877.         this.fileComment = reader.readData(this.fileCommentLength);
  3878.     },
  3879.  
  3880.     /**
  3881.      * Parse the external file attributes and get the unix/dos permissions.
  3882.      */
  3883.     processAttributes: function () {
  3884.         this.unixPermissions = null;
  3885.         this.dosPermissions = null;
  3886.         var madeBy = this.versionMadeBy >> 8;
  3887.  
  3888.         // Check if we have the DOS directory flag set.
  3889.         // We look for it in the DOS and UNIX permissions
  3890.         // but some unknown platform could set it as a compatibility flag.
  3891.         this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  3892.  
  3893.         if(madeBy === MADE_BY_DOS) {
  3894.             // first 6 bits (0 to 5)
  3895.             this.dosPermissions = this.externalFileAttributes & 0x3F;
  3896.         }
  3897.  
  3898.         if(madeBy === MADE_BY_UNIX) {
  3899.             this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  3900.             // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  3901.         }
  3902.  
  3903.         // fail safe : if the name ends with a / it probably means a folder
  3904.         if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  3905.             this.dir = true;
  3906.         }
  3907.     },
  3908.  
  3909.     /**
  3910.      * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  3911.      * @param {DataReader} reader the reader to use.
  3912.      */
  3913.     parseZIP64ExtraField: function(reader) {
  3914.  
  3915.         if (!this.extraFields[0x0001]) {
  3916.             return;
  3917.         }
  3918.  
  3919.         // should be something, preparing the extra reader
  3920.         var extraReader = readerFor(this.extraFields[0x0001].value);
  3921.  
  3922.         // I really hope that these 64bits integer can fit in 32 bits integer, because js
  3923.         // won't let us have more.
  3924.         if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  3925.             this.uncompressedSize = extraReader.readInt(8);
  3926.         }
  3927.         if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  3928.             this.compressedSize = extraReader.readInt(8);
  3929.         }
  3930.         if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  3931.             this.localHeaderOffset = extraReader.readInt(8);
  3932.         }
  3933.         if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  3934.             this.diskNumberStart = extraReader.readInt(4);
  3935.         }
  3936.     },
  3937.     /**
  3938.      * Read the central part of a zip file and add the info in this object.
  3939.      * @param {DataReader} reader the reader to use.
  3940.      */
  3941.     readExtraFields: function(reader) {
  3942.         var end = reader.index + this.extraFieldsLength,
  3943.             extraFieldId,
  3944.             extraFieldLength,
  3945.             extraFieldValue;
  3946.  
  3947.         if (!this.extraFields) {
  3948.             this.extraFields = {};
  3949.         }
  3950.  
  3951.         while (reader.index < end) {
  3952.             extraFieldId = reader.readInt(2);
  3953.             extraFieldLength = reader.readInt(2);
  3954.             extraFieldValue = reader.readData(extraFieldLength);
  3955.  
  3956.             this.extraFields[extraFieldId] = {
  3957.                 id: extraFieldId,
  3958.                 length: extraFieldLength,
  3959.                 value: extraFieldValue
  3960.             };
  3961.         }
  3962.     },
  3963.     /**
  3964.      * Apply an UTF8 transformation if needed.
  3965.      */
  3966.     handleUTF8: function() {
  3967.         var decodeParamType = support.uint8array ? "uint8array" : "array";
  3968.         if (this.useUTF8()) {
  3969.             this.fileNameStr = utf8.utf8decode(this.fileName);
  3970.             this.fileCommentStr = utf8.utf8decode(this.fileComment);
  3971.         } else {
  3972.             var upath = this.findExtraFieldUnicodePath();
  3973.             if (upath !== null) {
  3974.                 this.fileNameStr = upath;
  3975.             } else {
  3976.                 // ASCII text or unsupported code page
  3977.                 var fileNameByteArray =  utils.transformTo(decodeParamType, this.fileName);
  3978.                 this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  3979.             }
  3980.  
  3981.             var ucomment = this.findExtraFieldUnicodeComment();
  3982.             if (ucomment !== null) {
  3983.                 this.fileCommentStr = ucomment;
  3984.             } else {
  3985.                 // ASCII text or unsupported code page
  3986.                 var commentByteArray =  utils.transformTo(decodeParamType, this.fileComment);
  3987.                 this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  3988.             }
  3989.         }
  3990.     },
  3991.  
  3992.     /**
  3993.      * Find the unicode path declared in the extra field, if any.
  3994.      * @return {String} the unicode path, null otherwise.
  3995.      */
  3996.     findExtraFieldUnicodePath: function() {
  3997.         var upathField = this.extraFields[0x7075];
  3998.         if (upathField) {
  3999.             var extraReader = readerFor(upathField.value);
  4000.  
  4001.             // wrong version
  4002.             if (extraReader.readInt(1) !== 1) {
  4003.                 return null;
  4004.             }
  4005.  
  4006.             // the crc of the filename changed, this field is out of date.
  4007.             if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
  4008.                 return null;
  4009.             }
  4010.  
  4011.             return utf8.utf8decode(extraReader.readData(upathField.length - 5));
  4012.         }
  4013.         return null;
  4014.     },
  4015.  
  4016.     /**
  4017.      * Find the unicode comment declared in the extra field, if any.
  4018.      * @return {String} the unicode comment, null otherwise.
  4019.      */
  4020.     findExtraFieldUnicodeComment: function() {
  4021.         var ucommentField = this.extraFields[0x6375];
  4022.         if (ucommentField) {
  4023.             var extraReader = readerFor(ucommentField.value);
  4024.  
  4025.             // wrong version
  4026.             if (extraReader.readInt(1) !== 1) {
  4027.                 return null;
  4028.             }
  4029.  
  4030.             // the crc of the comment changed, this field is out of date.
  4031.             if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
  4032.                 return null;
  4033.             }
  4034.  
  4035.             return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
  4036.         }
  4037.         return null;
  4038.     }
  4039. };
  4040. module.exports = ZipEntry;
  4041.  
  4042. },{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
  4043. 'use strict';
  4044.  
  4045. var StreamHelper = require('./stream/StreamHelper');
  4046. var DataWorker = require('./stream/DataWorker');
  4047. var utf8 = require('./utf8');
  4048. var CompressedObject = require('./compressedObject');
  4049. var GenericWorker = require('./stream/GenericWorker');
  4050.  
  4051. /**
  4052.  * A simple object representing a file in the zip file.
  4053.  * @constructor
  4054.  * @param {string} name the name of the file
  4055.  * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  4056.  * @param {Object} options the options of the file
  4057.  */
  4058. var ZipObject = function(name, data, options) {
  4059.     this.name = name;
  4060.     this.dir = options.dir;
  4061.     this.date = options.date;
  4062.     this.comment = options.comment;
  4063.     this.unixPermissions = options.unixPermissions;
  4064.     this.dosPermissions = options.dosPermissions;
  4065.  
  4066.     this._data = data;
  4067.     this._dataBinary = options.binary;
  4068.     // keep only the compression
  4069.     this.options = {
  4070.         compression : options.compression,
  4071.         compressionOptions : options.compressionOptions
  4072.     };
  4073. };
  4074.  
  4075. ZipObject.prototype = {
  4076.     /**
  4077.      * Create an internal stream for the content of this object.
  4078.      * @param {String} type the type of each chunk.
  4079.      * @return StreamHelper the stream.
  4080.      */
  4081.     internalStream: function (type) {
  4082.         var outputType = type.toLowerCase();
  4083.         var askUnicodeString = outputType === "string" || outputType === "text";
  4084.         if (outputType === "binarystring" || outputType === "text") {
  4085.             outputType = "string";
  4086.         }
  4087.         var result = this._decompressWorker();
  4088.  
  4089.         var isUnicodeString = !this._dataBinary;
  4090.  
  4091.         if (isUnicodeString && !askUnicodeString) {
  4092.             result = result.pipe(new utf8.Utf8EncodeWorker());
  4093.         }
  4094.         if (!isUnicodeString && askUnicodeString) {
  4095.             result = result.pipe(new utf8.Utf8DecodeWorker());
  4096.         }
  4097.  
  4098.         return new StreamHelper(result, outputType, "");
  4099.     },
  4100.  
  4101.     /**
  4102.      * Prepare the content in the asked type.
  4103.      * @param {String} type the type of the result.
  4104.      * @param {Function} onUpdate a function to call on each internal update.
  4105.      * @return Promise the promise of the result.
  4106.      */
  4107.     async: function (type, onUpdate) {
  4108.         return this.internalStream(type).accumulate(onUpdate);
  4109.     },
  4110.  
  4111.     /**
  4112.      * Prepare the content as a nodejs stream.
  4113.      * @param {String} type the type of each chunk.
  4114.      * @param {Function} onUpdate a function to call on each internal update.
  4115.      * @return Stream the stream.
  4116.      */
  4117.     nodeStream: function (type, onUpdate) {
  4118.         return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
  4119.     },
  4120.  
  4121.     /**
  4122.      * Return a worker for the compressed content.
  4123.      * @private
  4124.      * @param {Object} compression the compression object to use.
  4125.      * @param {Object} compressionOptions the options to use when compressing.
  4126.      * @return Worker the worker.
  4127.      */
  4128.     _compressWorker: function (compression, compressionOptions) {
  4129.         if (
  4130.             this._data instanceof CompressedObject &&
  4131.             this._data.compression.magic === compression.magic
  4132.         ) {
  4133.             return this._data.getCompressedWorker();
  4134.         } else {
  4135.             var result = this._decompressWorker();
  4136.             if(!this._dataBinary) {
  4137.                 result = result.pipe(new utf8.Utf8EncodeWorker());
  4138.             }
  4139.             return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
  4140.         }
  4141.     },
  4142.     /**
  4143.      * Return a worker for the decompressed content.
  4144.      * @private
  4145.      * @return Worker the worker.
  4146.      */
  4147.     _decompressWorker : function () {
  4148.         if (this._data instanceof CompressedObject) {
  4149.             return this._data.getContentWorker();
  4150.         } else if (this._data instanceof GenericWorker) {
  4151.             return this._data;
  4152.         } else {
  4153.             return new DataWorker(this._data);
  4154.         }
  4155.     }
  4156. };
  4157.  
  4158. var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  4159. var removedFn = function () {
  4160.     throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  4161. };
  4162.  
  4163. for(var i = 0; i < removedMethods.length; i++) {
  4164.     ZipObject.prototype[removedMethods[i]] = removedFn;
  4165. }
  4166. module.exports = ZipObject;
  4167.  
  4168. },{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
  4169. require('../modules/web.immediate');
  4170. module.exports = require('../modules/_core').setImmediate;
  4171. },{"../modules/_core":40,"../modules/web.immediate":56}],37:[function(require,module,exports){
  4172. module.exports = function(it){
  4173.   if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  4174.   return it;
  4175. };
  4176. },{}],38:[function(require,module,exports){
  4177. var isObject = require('./_is-object');
  4178. module.exports = function(it){
  4179.   if(!isObject(it))throw TypeError(it + ' is not an object!');
  4180.   return it;
  4181. };
  4182. },{"./_is-object":51}],39:[function(require,module,exports){
  4183. var toString = {}.toString;
  4184.  
  4185. module.exports = function(it){
  4186.   return toString.call(it).slice(8, -1);
  4187. };
  4188. },{}],40:[function(require,module,exports){
  4189. var core = module.exports = {version: '2.3.0'};
  4190. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  4191. },{}],41:[function(require,module,exports){
  4192. // optional / simple context binding
  4193. var aFunction = require('./_a-function');
  4194. module.exports = function(fn, that, length){
  4195.   aFunction(fn);
  4196.   if(that === undefined)return fn;
  4197.   switch(length){
  4198.     case 1: return function(a){
  4199.       return fn.call(that, a);
  4200.     };
  4201.     case 2: return function(a, b){
  4202.       return fn.call(that, a, b);
  4203.     };
  4204.     case 3: return function(a, b, c){
  4205.       return fn.call(that, a, b, c);
  4206.     };
  4207.   }
  4208.   return function(/* ...args */){
  4209.     return fn.apply(that, arguments);
  4210.   };
  4211. };
  4212. },{"./_a-function":37}],42:[function(require,module,exports){
  4213. // Thank's IE8 for his funny defineProperty
  4214. module.exports = !require('./_fails')(function(){
  4215.   return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
  4216. });
  4217. },{"./_fails":45}],43:[function(require,module,exports){
  4218. var isObject = require('./_is-object')
  4219.   , document = require('./_global').document
  4220.   // in old IE typeof document.createElement is 'object'
  4221.   , is = isObject(document) && isObject(document.createElement);
  4222. module.exports = function(it){
  4223.   return is ? document.createElement(it) : {};
  4224. };
  4225. },{"./_global":46,"./_is-object":51}],44:[function(require,module,exports){
  4226. var global    = require('./_global')
  4227.   , core      = require('./_core')
  4228.   , ctx       = require('./_ctx')
  4229.   , hide      = require('./_hide')
  4230.   , PROTOTYPE = 'prototype';
  4231.  
  4232. var $export = function(type, name, source){
  4233.   var IS_FORCED = type & $export.F
  4234.     , IS_GLOBAL = type & $export.G
  4235.     , IS_STATIC = type & $export.S
  4236.     , IS_PROTO  = type & $export.P
  4237.     , IS_BIND   = type & $export.B
  4238.     , IS_WRAP   = type & $export.W
  4239.     , exports   = IS_GLOBAL ? core : core[name] || (core[name] = {})
  4240.     , expProto  = exports[PROTOTYPE]
  4241.     , target    = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  4242.     , key, own, out;
  4243.   if(IS_GLOBAL)source = name;
  4244.   for(key in source){
  4245.     // contains in native
  4246.     own = !IS_FORCED && target && target[key] !== undefined;
  4247.     if(own && key in exports)continue;
  4248.     // export native or passed
  4249.     out = own ? target[key] : source[key];
  4250.     // prevent global pollution for namespaces
  4251.     exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  4252.     // bind timers to global for call from export context
  4253.     : IS_BIND && own ? ctx(out, global)
  4254.     // wrap global constructors for prevent change them in library
  4255.     : IS_WRAP && target[key] == out ? (function(C){
  4256.       var F = function(a, b, c){
  4257.         if(this instanceof C){
  4258.           switch(arguments.length){
  4259.             case 0: return new C;
  4260.             case 1: return new C(a);
  4261.             case 2: return new C(a, b);
  4262.           } return new C(a, b, c);
  4263.         } return C.apply(this, arguments);
  4264.       };
  4265.       F[PROTOTYPE] = C[PROTOTYPE];
  4266.       return F;
  4267.     // make static versions for prototype methods
  4268.     })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  4269.     // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
  4270.     if(IS_PROTO){
  4271.       (exports.virtual || (exports.virtual = {}))[key] = out;
  4272.       // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
  4273.       if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
  4274.     }
  4275.   }
  4276. };
  4277. // type bitmap
  4278. $export.F = 1;   // forced
  4279. $export.G = 2;   // global
  4280. $export.S = 4;   // static
  4281. $export.P = 8;   // proto
  4282. $export.B = 16;  // bind
  4283. $export.W = 32;  // wrap
  4284. $export.U = 64;  // safe
  4285. $export.R = 128; // real proto method for `library`
  4286. module.exports = $export;
  4287. },{"./_core":40,"./_ctx":41,"./_global":46,"./_hide":47}],45:[function(require,module,exports){
  4288. module.exports = function(exec){
  4289.   try {
  4290.     return !!exec();
  4291.   } catch(e){
  4292.     return true;
  4293.   }
  4294. };
  4295. },{}],46:[function(require,module,exports){
  4296. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  4297. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  4298.   ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  4299. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  4300. },{}],47:[function(require,module,exports){
  4301. var dP         = require('./_object-dp')
  4302.   , createDesc = require('./_property-desc');
  4303. module.exports = require('./_descriptors') ? function(object, key, value){
  4304.   return dP.f(object, key, createDesc(1, value));
  4305. } : function(object, key, value){
  4306.   object[key] = value;
  4307.   return object;
  4308. };
  4309. },{"./_descriptors":42,"./_object-dp":52,"./_property-desc":53}],48:[function(require,module,exports){
  4310. module.exports = require('./_global').document && document.documentElement;
  4311. },{"./_global":46}],49:[function(require,module,exports){
  4312. module.exports = !require('./_descriptors') && !require('./_fails')(function(){
  4313.   return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
  4314. });
  4315. },{"./_descriptors":42,"./_dom-create":43,"./_fails":45}],50:[function(require,module,exports){
  4316. // fast apply, http://jsperf.lnkit.com/fast-apply/5
  4317. module.exports = function(fn, args, that){
  4318.   var un = that === undefined;
  4319.   switch(args.length){
  4320.     case 0: return un ? fn()
  4321.                       : fn.call(that);
  4322.     case 1: return un ? fn(args[0])
  4323.                       : fn.call(that, args[0]);
  4324.     case 2: return un ? fn(args[0], args[1])
  4325.                       : fn.call(that, args[0], args[1]);
  4326.     case 3: return un ? fn(args[0], args[1], args[2])
  4327.                       : fn.call(that, args[0], args[1], args[2]);
  4328.     case 4: return un ? fn(args[0], args[1], args[2], args[3])
  4329.                       : fn.call(that, args[0], args[1], args[2], args[3]);
  4330.   } return              fn.apply(that, args);
  4331. };
  4332. },{}],51:[function(require,module,exports){
  4333. module.exports = function(it){
  4334.   return typeof it === 'object' ? it !== null : typeof it === 'function';
  4335. };
  4336. },{}],52:[function(require,module,exports){
  4337. var anObject       = require('./_an-object')
  4338.   , IE8_DOM_DEFINE = require('./_ie8-dom-define')
  4339.   , toPrimitive    = require('./_to-primitive')
  4340.   , dP             = Object.defineProperty;
  4341.  
  4342. exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
  4343.   anObject(O);
  4344.   P = toPrimitive(P, true);
  4345.   anObject(Attributes);
  4346.   if(IE8_DOM_DEFINE)try {
  4347.     return dP(O, P, Attributes);
  4348.   } catch(e){ /* empty */ }
  4349.   if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
  4350.   if('value' in Attributes)O[P] = Attributes.value;
  4351.   return O;
  4352. };
  4353. },{"./_an-object":38,"./_descriptors":42,"./_ie8-dom-define":49,"./_to-primitive":55}],53:[function(require,module,exports){
  4354. module.exports = function(bitmap, value){
  4355.   return {
  4356.     enumerable  : !(bitmap & 1),
  4357.     configurable: !(bitmap & 2),
  4358.     writable    : !(bitmap & 4),
  4359.     value       : value
  4360.   };
  4361. };
  4362. },{}],54:[function(require,module,exports){
  4363. var ctx                = require('./_ctx')
  4364.   , invoke             = require('./_invoke')
  4365.   , html               = require('./_html')
  4366.   , cel                = require('./_dom-create')
  4367.   , global             = require('./_global')
  4368.   , process            = global.process
  4369.   , setTask            = global.setImmediate
  4370.   , clearTask          = global.clearImmediate
  4371.   , MessageChannel     = global.MessageChannel
  4372.   , counter            = 0
  4373.   , queue              = {}
  4374.   , ONREADYSTATECHANGE = 'onreadystatechange'
  4375.   , defer, channel, port;
  4376. var run = function(){
  4377.   var id = +this;
  4378.   if(queue.hasOwnProperty(id)){
  4379.     var fn = queue[id];
  4380.     delete queue[id];
  4381.     fn();
  4382.   }
  4383. };
  4384. var listener = function(event){
  4385.   run.call(event.data);
  4386. };
  4387. // Node.js 0.9+ & IE10+ has setImmediate, otherwise:
  4388. if(!setTask || !clearTask){
  4389.   setTask = function setImmediate(fn){
  4390.     var args = [], i = 1;
  4391.     while(arguments.length > i)args.push(arguments[i++]);
  4392.     queue[++counter] = function(){
  4393.       invoke(typeof fn == 'function' ? fn : Function(fn), args);
  4394.     };
  4395.     defer(counter);
  4396.     return counter;
  4397.   };
  4398.   clearTask = function clearImmediate(id){
  4399.     delete queue[id];
  4400.   };
  4401.   // Node.js 0.8-
  4402.   if(require('./_cof')(process) == 'process'){
  4403.     defer = function(id){
  4404.       process.nextTick(ctx(run, id, 1));
  4405.     };
  4406.   // Browsers with MessageChannel, includes WebWorkers
  4407.   } else if(MessageChannel){
  4408.     channel = new MessageChannel;
  4409.     port    = channel.port2;
  4410.     channel.port1.onmessage = listener;
  4411.     defer = ctx(port.postMessage, port, 1);
  4412.   // Browsers with postMessage, skip WebWorkers
  4413.   // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
  4414.   } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
  4415.     defer = function(id){
  4416.       global.postMessage(id + '', '*');
  4417.     };
  4418.     global.addEventListener('message', listener, false);
  4419.   // IE8-
  4420.   } else if(ONREADYSTATECHANGE in cel('script')){
  4421.     defer = function(id){
  4422.       html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
  4423.         html.removeChild(this);
  4424.         run.call(id);
  4425.       };
  4426.     };
  4427.   // Rest old browsers
  4428.   } else {
  4429.     defer = function(id){
  4430.       setTimeout(ctx(run, id, 1), 0);
  4431.     };
  4432.   }
  4433. }
  4434. module.exports = {
  4435.   set:   setTask,
  4436.   clear: clearTask
  4437. };
  4438. },{"./_cof":39,"./_ctx":41,"./_dom-create":43,"./_global":46,"./_html":48,"./_invoke":50}],55:[function(require,module,exports){
  4439. // 7.1.1 ToPrimitive(input [, PreferredType])
  4440. var isObject = require('./_is-object');
  4441. // instead of the ES6 spec version, we didn't implement @@toPrimitive case
  4442. // and the second argument - flag - preferred type is a string
  4443. module.exports = function(it, S){
  4444.   if(!isObject(it))return it;
  4445.   var fn, val;
  4446.   if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
  4447.   if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
  4448.   if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
  4449.   throw TypeError("Can't convert object to primitive value");
  4450. };
  4451. },{"./_is-object":51}],56:[function(require,module,exports){
  4452. var $export = require('./_export')
  4453.   , $task   = require('./_task');
  4454. $export($export.G + $export.B, {
  4455.   setImmediate:   $task.set,
  4456.   clearImmediate: $task.clear
  4457. });
  4458. },{"./_export":44,"./_task":54}],57:[function(require,module,exports){
  4459. (function (global){
  4460. 'use strict';
  4461. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  4462.  
  4463. var scheduleDrain;
  4464.  
  4465. {
  4466.   if (Mutation) {
  4467.     var called = 0;
  4468.     var observer = new Mutation(nextTick);
  4469.     var element = global.document.createTextNode('');
  4470.     observer.observe(element, {
  4471.       characterData: true
  4472.     });
  4473.     scheduleDrain = function () {
  4474.       element.data = (called = ++called % 2);
  4475.     };
  4476.   } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  4477.     var channel = new global.MessageChannel();
  4478.     channel.port1.onmessage = nextTick;
  4479.     scheduleDrain = function () {
  4480.       channel.port2.postMessage(0);
  4481.     };
  4482.   } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  4483.     scheduleDrain = function () {
  4484.  
  4485.       // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  4486.       // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  4487.       var scriptEl = global.document.createElement('script');
  4488.       scriptEl.onreadystatechange = function () {
  4489.         nextTick();
  4490.  
  4491.         scriptEl.onreadystatechange = null;
  4492.         scriptEl.parentNode.removeChild(scriptEl);
  4493.         scriptEl = null;
  4494.       };
  4495.       global.document.documentElement.appendChild(scriptEl);
  4496.     };
  4497.   } else {
  4498.     scheduleDrain = function () {
  4499.       setTimeout(nextTick, 0);
  4500.     };
  4501.   }
  4502. }
  4503.  
  4504. var draining;
  4505. var queue = [];
  4506. //named nextTick for less confusing stack traces
  4507. function nextTick() {
  4508.   draining = true;
  4509.   var i, oldQueue;
  4510.   var len = queue.length;
  4511.   while (len) {
  4512.     oldQueue = queue;
  4513.     queue = [];
  4514.     i = -1;
  4515.     while (++i < len) {
  4516.       oldQueue[i]();
  4517.     }
  4518.     len = queue.length;
  4519.   }
  4520.   draining = false;
  4521. }
  4522.  
  4523. module.exports = immediate;
  4524. function immediate(task) {
  4525.   if (queue.push(task) === 1 && !draining) {
  4526.     scheduleDrain();
  4527.   }
  4528. }
  4529.  
  4530. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4531. },{}],58:[function(require,module,exports){
  4532. 'use strict';
  4533. var immediate = require('immediate');
  4534.  
  4535. /* istanbul ignore next */
  4536. function INTERNAL() {}
  4537.  
  4538. var handlers = {};
  4539.  
  4540. var REJECTED = ['REJECTED'];
  4541. var FULFILLED = ['FULFILLED'];
  4542. var PENDING = ['PENDING'];
  4543.  
  4544. module.exports = Promise;
  4545.  
  4546. function Promise(resolver) {
  4547.   if (typeof resolver !== 'function') {
  4548.     throw new TypeError('resolver must be a function');
  4549.   }
  4550.   this.state = PENDING;
  4551.   this.queue = [];
  4552.   this.outcome = void 0;
  4553.   if (resolver !== INTERNAL) {
  4554.     safelyResolveThenable(this, resolver);
  4555.   }
  4556. }
  4557.  
  4558. Promise.prototype["catch"] = function (onRejected) {
  4559.   return this.then(null, onRejected);
  4560. };
  4561. Promise.prototype.then = function (onFulfilled, onRejected) {
  4562.   if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  4563.     typeof onRejected !== 'function' && this.state === REJECTED) {
  4564.     return this;
  4565.   }
  4566.   var promise = new this.constructor(INTERNAL);
  4567.   if (this.state !== PENDING) {
  4568.     var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  4569.     unwrap(promise, resolver, this.outcome);
  4570.   } else {
  4571.     this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  4572.   }
  4573.  
  4574.   return promise;
  4575. };
  4576. function QueueItem(promise, onFulfilled, onRejected) {
  4577.   this.promise = promise;
  4578.   if (typeof onFulfilled === 'function') {
  4579.     this.onFulfilled = onFulfilled;
  4580.     this.callFulfilled = this.otherCallFulfilled;
  4581.   }
  4582.   if (typeof onRejected === 'function') {
  4583.     this.onRejected = onRejected;
  4584.     this.callRejected = this.otherCallRejected;
  4585.   }
  4586. }
  4587. QueueItem.prototype.callFulfilled = function (value) {
  4588.   handlers.resolve(this.promise, value);
  4589. };
  4590. QueueItem.prototype.otherCallFulfilled = function (value) {
  4591.   unwrap(this.promise, this.onFulfilled, value);
  4592. };
  4593. QueueItem.prototype.callRejected = function (value) {
  4594.   handlers.reject(this.promise, value);
  4595. };
  4596. QueueItem.prototype.otherCallRejected = function (value) {
  4597.   unwrap(this.promise, this.onRejected, value);
  4598. };
  4599.  
  4600. function unwrap(promise, func, value) {
  4601.   immediate(function () {
  4602.     var returnValue;
  4603.     try {
  4604.       returnValue = func(value);
  4605.     } catch (e) {
  4606.       return handlers.reject(promise, e);
  4607.     }
  4608.     if (returnValue === promise) {
  4609.       handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  4610.     } else {
  4611.       handlers.resolve(promise, returnValue);
  4612.     }
  4613.   });
  4614. }
  4615.  
  4616. handlers.resolve = function (self, value) {
  4617.   var result = tryCatch(getThen, value);
  4618.   if (result.status === 'error') {
  4619.     return handlers.reject(self, result.value);
  4620.   }
  4621.   var thenable = result.value;
  4622.  
  4623.   if (thenable) {
  4624.     safelyResolveThenable(self, thenable);
  4625.   } else {
  4626.     self.state = FULFILLED;
  4627.     self.outcome = value;
  4628.     var i = -1;
  4629.     var len = self.queue.length;
  4630.     while (++i < len) {
  4631.       self.queue[i].callFulfilled(value);
  4632.     }
  4633.   }
  4634.   return self;
  4635. };
  4636. handlers.reject = function (self, error) {
  4637.   self.state = REJECTED;
  4638.   self.outcome = error;
  4639.   var i = -1;
  4640.   var len = self.queue.length;
  4641.   while (++i < len) {
  4642.     self.queue[i].callRejected(error);
  4643.   }
  4644.   return self;
  4645. };
  4646.  
  4647. function getThen(obj) {
  4648.   // Make sure we only access the accessor once as required by the spec
  4649.   var then = obj && obj.then;
  4650.   if (obj && typeof obj === 'object' && typeof then === 'function') {
  4651.     return function appyThen() {
  4652.       then.apply(obj, arguments);
  4653.     };
  4654.   }
  4655. }
  4656.  
  4657. function safelyResolveThenable(self, thenable) {
  4658.   // Either fulfill, reject or reject with error
  4659.   var called = false;
  4660.   function onError(value) {
  4661.     if (called) {
  4662.       return;
  4663.     }
  4664.     called = true;
  4665.     handlers.reject(self, value);
  4666.   }
  4667.  
  4668.   function onSuccess(value) {
  4669.     if (called) {
  4670.       return;
  4671.     }
  4672.     called = true;
  4673.     handlers.resolve(self, value);
  4674.   }
  4675.  
  4676.   function tryToUnwrap() {
  4677.     thenable(onSuccess, onError);
  4678.   }
  4679.  
  4680.   var result = tryCatch(tryToUnwrap);
  4681.   if (result.status === 'error') {
  4682.     onError(result.value);
  4683.   }
  4684. }
  4685.  
  4686. function tryCatch(func, value) {
  4687.   var out = {};
  4688.   try {
  4689.     out.value = func(value);
  4690.     out.status = 'success';
  4691.   } catch (e) {
  4692.     out.status = 'error';
  4693.     out.value = e;
  4694.   }
  4695.   return out;
  4696. }
  4697.  
  4698. Promise.resolve = resolve;
  4699. function resolve(value) {
  4700.   if (value instanceof this) {
  4701.     return value;
  4702.   }
  4703.   return handlers.resolve(new this(INTERNAL), value);
  4704. }
  4705.  
  4706. Promise.reject = reject;
  4707. function reject(reason) {
  4708.   var promise = new this(INTERNAL);
  4709.   return handlers.reject(promise, reason);
  4710. }
  4711.  
  4712. Promise.all = all;
  4713. function all(iterable) {
  4714.   var self = this;
  4715.   if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4716.     return this.reject(new TypeError('must be an array'));
  4717.   }
  4718.  
  4719.   var len = iterable.length;
  4720.   var called = false;
  4721.   if (!len) {
  4722.     return this.resolve([]);
  4723.   }
  4724.  
  4725.   var values = new Array(len);
  4726.   var resolved = 0;
  4727.   var i = -1;
  4728.   var promise = new this(INTERNAL);
  4729.  
  4730.   while (++i < len) {
  4731.     allResolver(iterable[i], i);
  4732.   }
  4733.   return promise;
  4734.   function allResolver(value, i) {
  4735.     self.resolve(value).then(resolveFromAll, function (error) {
  4736.       if (!called) {
  4737.         called = true;
  4738.         handlers.reject(promise, error);
  4739.       }
  4740.     });
  4741.     function resolveFromAll(outValue) {
  4742.       values[i] = outValue;
  4743.       if (++resolved === len && !called) {
  4744.         called = true;
  4745.         handlers.resolve(promise, values);
  4746.       }
  4747.     }
  4748.   }
  4749. }
  4750.  
  4751. Promise.race = race;
  4752. function race(iterable) {
  4753.   var self = this;
  4754.   if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4755.     return this.reject(new TypeError('must be an array'));
  4756.   }
  4757.  
  4758.   var len = iterable.length;
  4759.   var called = false;
  4760.   if (!len) {
  4761.     return this.resolve([]);
  4762.   }
  4763.  
  4764.   var i = -1;
  4765.   var promise = new this(INTERNAL);
  4766.  
  4767.   while (++i < len) {
  4768.     resolver(iterable[i]);
  4769.   }
  4770.   return promise;
  4771.   function resolver(value) {
  4772.     self.resolve(value).then(function (response) {
  4773.       if (!called) {
  4774.         called = true;
  4775.         handlers.resolve(promise, response);
  4776.       }
  4777.     }, function (error) {
  4778.       if (!called) {
  4779.         called = true;
  4780.         handlers.reject(promise, error);
  4781.       }
  4782.     });
  4783.   }
  4784. }
  4785.  
  4786. },{"immediate":57}],59:[function(require,module,exports){
  4787. // Top level file is just a mixin of submodules & constants
  4788. 'use strict';
  4789.  
  4790. var assign    = require('./lib/utils/common').assign;
  4791.  
  4792. var deflate   = require('./lib/deflate');
  4793. var inflate   = require('./lib/inflate');
  4794. var constants = require('./lib/zlib/constants');
  4795.  
  4796. var pako = {};
  4797.  
  4798. assign(pako, deflate, inflate, constants);
  4799.  
  4800. module.exports = pako;
  4801.  
  4802. },{"./lib/deflate":60,"./lib/inflate":61,"./lib/utils/common":62,"./lib/zlib/constants":65}],60:[function(require,module,exports){
  4803. 'use strict';
  4804.  
  4805.  
  4806. var zlib_deflate = require('./zlib/deflate');
  4807. var utils        = require('./utils/common');
  4808. var strings      = require('./utils/strings');
  4809. var msg          = require('./zlib/messages');
  4810. var ZStream      = require('./zlib/zstream');
  4811.  
  4812. var toString = Object.prototype.toString;
  4813.  
  4814. /* Public constants ==========================================================*/
  4815. /* ===========================================================================*/
  4816.  
  4817. var Z_NO_FLUSH      = 0;
  4818. var Z_FINISH        = 4;
  4819.  
  4820. var Z_OK            = 0;
  4821. var Z_STREAM_END    = 1;
  4822. var Z_SYNC_FLUSH    = 2;
  4823.  
  4824. var Z_DEFAULT_COMPRESSION = -1;
  4825.  
  4826. var Z_DEFAULT_STRATEGY    = 0;
  4827.  
  4828. var Z_DEFLATED  = 8;
  4829.  
  4830. /* ===========================================================================*/
  4831.  
  4832.  
  4833. /**
  4834.  * class Deflate
  4835.  *
  4836.  * Generic JS-style wrapper for zlib calls. If you don't need
  4837.  * streaming behaviour - use more simple functions: [[deflate]],
  4838.  * [[deflateRaw]] and [[gzip]].
  4839.  **/
  4840.  
  4841. /* internal
  4842.  * Deflate.chunks -> Array
  4843.  *
  4844.  * Chunks of output data, if [[Deflate#onData]] not overriden.
  4845.  **/
  4846.  
  4847. /**
  4848.  * Deflate.result -> Uint8Array|Array
  4849.  *
  4850.  * Compressed result, generated by default [[Deflate#onData]]
  4851.  * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  4852.  * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
  4853.  * push a chunk with explicit flush (call [[Deflate#push]] with
  4854.  * `Z_SYNC_FLUSH` param).
  4855.  **/
  4856.  
  4857. /**
  4858.  * Deflate.err -> Number
  4859.  *
  4860.  * Error code after deflate finished. 0 (Z_OK) on success.
  4861.  * You will not need it in real life, because deflate errors
  4862.  * are possible only on wrong options or bad `onData` / `onEnd`
  4863.  * custom handlers.
  4864.  **/
  4865.  
  4866. /**
  4867.  * Deflate.msg -> String
  4868.  *
  4869.  * Error message, if [[Deflate.err]] != 0
  4870.  **/
  4871.  
  4872.  
  4873. /**
  4874.  * new Deflate(options)
  4875.  * - options (Object): zlib deflate options.
  4876.  *
  4877.  * Creates new deflator instance with specified params. Throws exception
  4878.  * on bad params. Supported options:
  4879.  *
  4880.  * - `level`
  4881.  * - `windowBits`
  4882.  * - `memLevel`
  4883.  * - `strategy`
  4884.  * - `dictionary`
  4885.  *
  4886.  * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4887.  * for more information on these.
  4888.  *
  4889.  * Additional options, for internal needs:
  4890.  *
  4891.  * - `chunkSize` - size of generated data chunks (16K by default)
  4892.  * - `raw` (Boolean) - do raw deflate
  4893.  * - `gzip` (Boolean) - create gzip wrapper
  4894.  * - `to` (String) - if equal to 'string', then result will be "binary string"
  4895.  *    (each char code [0..255])
  4896.  * - `header` (Object) - custom header for gzip
  4897.  *   - `text` (Boolean) - true if compressed data believed to be text
  4898.  *   - `time` (Number) - modification time, unix timestamp
  4899.  *   - `os` (Number) - operation system code
  4900.  *   - `extra` (Array) - array of bytes with extra data (max 65536)
  4901.  *   - `name` (String) - file name (binary string)
  4902.  *   - `comment` (String) - comment (binary string)
  4903.  *   - `hcrc` (Boolean) - true if header crc should be added
  4904.  *
  4905.  * ##### Example:
  4906.  *
  4907.  * ```javascript
  4908.  * var pako = require('pako')
  4909.  *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  4910.  *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  4911.  *
  4912.  * var deflate = new pako.Deflate({ level: 3});
  4913.  *
  4914.  * deflate.push(chunk1, false);
  4915.  * deflate.push(chunk2, true);  // true -> last chunk
  4916.  *
  4917.  * if (deflate.err) { throw new Error(deflate.err); }
  4918.  *
  4919.  * console.log(deflate.result);
  4920.  * ```
  4921.  **/
  4922. function Deflate(options) {
  4923.   if (!(this instanceof Deflate)) return new Deflate(options);
  4924.  
  4925.   this.options = utils.assign({
  4926.     level: Z_DEFAULT_COMPRESSION,
  4927.     method: Z_DEFLATED,
  4928.     chunkSize: 16384,
  4929.     windowBits: 15,
  4930.     memLevel: 8,
  4931.     strategy: Z_DEFAULT_STRATEGY,
  4932.     to: ''
  4933.   }, options || {});
  4934.  
  4935.   var opt = this.options;
  4936.  
  4937.   if (opt.raw && (opt.windowBits > 0)) {
  4938.     opt.windowBits = -opt.windowBits;
  4939.   }
  4940.  
  4941.   else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  4942.     opt.windowBits += 16;
  4943.   }
  4944.  
  4945.   this.err    = 0;      // error code, if happens (0 = Z_OK)
  4946.   this.msg    = '';     // error message
  4947.   this.ended  = false;  // used to avoid multiple onEnd() calls
  4948.   this.chunks = [];     // chunks of compressed data
  4949.  
  4950.   this.strm = new ZStream();
  4951.   this.strm.avail_out = 0;
  4952.  
  4953.   var status = zlib_deflate.deflateInit2(
  4954.     this.strm,
  4955.     opt.level,
  4956.     opt.method,
  4957.     opt.windowBits,
  4958.     opt.memLevel,
  4959.     opt.strategy
  4960.   );
  4961.  
  4962.   if (status !== Z_OK) {
  4963.     throw new Error(msg[status]);
  4964.   }
  4965.  
  4966.   if (opt.header) {
  4967.     zlib_deflate.deflateSetHeader(this.strm, opt.header);
  4968.   }
  4969.  
  4970.   if (opt.dictionary) {
  4971.     var dict;
  4972.     // Convert data if needed
  4973.     if (typeof opt.dictionary === 'string') {
  4974.       // If we need to compress text, change encoding to utf8.
  4975.       dict = strings.string2buf(opt.dictionary);
  4976.     } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  4977.       dict = new Uint8Array(opt.dictionary);
  4978.     } else {
  4979.       dict = opt.dictionary;
  4980.     }
  4981.  
  4982.     status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  4983.  
  4984.     if (status !== Z_OK) {
  4985.       throw new Error(msg[status]);
  4986.     }
  4987.  
  4988.     this._dict_set = true;
  4989.   }
  4990. }
  4991.  
  4992. /**
  4993.  * Deflate#push(data[, mode]) -> Boolean
  4994.  * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  4995.  *   converted to utf8 byte sequence.
  4996.  * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  4997.  *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  4998.  *
  4999.  * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  5000.  * new compressed chunks. Returns `true` on success. The last data block must have
  5001.  * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5002.  * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5003.  * can use mode Z_SYNC_FLUSH, keeping the compression context.
  5004.  *
  5005.  * On fail call [[Deflate#onEnd]] with error code and return false.
  5006.  *
  5007.  * We strongly recommend to use `Uint8Array` on input for best speed (output
  5008.  * array format is detected automatically). Also, don't skip last param and always
  5009.  * use the same type in your code (boolean or number). That will improve JS speed.
  5010.  *
  5011.  * For regular `Array`-s make sure all elements are [0..255].
  5012.  *
  5013.  * ##### Example
  5014.  *
  5015.  * ```javascript
  5016.  * push(chunk, false); // push one of data chunks
  5017.  * ...
  5018.  * push(chunk, true);  // push last chunk
  5019.  * ```
  5020.  **/
  5021. Deflate.prototype.push = function (data, mode) {
  5022.   var strm = this.strm;
  5023.   var chunkSize = this.options.chunkSize;
  5024.   var status, _mode;
  5025.  
  5026.   if (this.ended) { return false; }
  5027.  
  5028.   _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  5029.  
  5030.   // Convert data if needed
  5031.   if (typeof data === 'string') {
  5032.     // If we need to compress text, change encoding to utf8.
  5033.     strm.input = strings.string2buf(data);
  5034.   } else if (toString.call(data) === '[object ArrayBuffer]') {
  5035.     strm.input = new Uint8Array(data);
  5036.   } else {
  5037.     strm.input = data;
  5038.   }
  5039.  
  5040.   strm.next_in = 0;
  5041.   strm.avail_in = strm.input.length;
  5042.  
  5043.   do {
  5044.     if (strm.avail_out === 0) {
  5045.       strm.output = new utils.Buf8(chunkSize);
  5046.       strm.next_out = 0;
  5047.       strm.avail_out = chunkSize;
  5048.     }
  5049.     status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */
  5050.  
  5051.     if (status !== Z_STREAM_END && status !== Z_OK) {
  5052.       this.onEnd(status);
  5053.       this.ended = true;
  5054.       return false;
  5055.     }
  5056.     if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  5057.       if (this.options.to === 'string') {
  5058.         this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  5059.       } else {
  5060.         this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5061.       }
  5062.     }
  5063.   } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  5064.  
  5065.   // Finalize on the last chunk.
  5066.   if (_mode === Z_FINISH) {
  5067.     status = zlib_deflate.deflateEnd(this.strm);
  5068.     this.onEnd(status);
  5069.     this.ended = true;
  5070.     return status === Z_OK;
  5071.   }
  5072.  
  5073.   // callback interim results if Z_SYNC_FLUSH.
  5074.   if (_mode === Z_SYNC_FLUSH) {
  5075.     this.onEnd(Z_OK);
  5076.     strm.avail_out = 0;
  5077.     return true;
  5078.   }
  5079.  
  5080.   return true;
  5081. };
  5082.  
  5083.  
  5084. /**
  5085.  * Deflate#onData(chunk) -> Void
  5086.  * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5087.  *   on js engine support. When string output requested, each chunk
  5088.  *   will be string.
  5089.  *
  5090.  * By default, stores data blocks in `chunks[]` property and glue
  5091.  * those in `onEnd`. Override this handler, if you need another behaviour.
  5092.  **/
  5093. Deflate.prototype.onData = function (chunk) {
  5094.   this.chunks.push(chunk);
  5095. };
  5096.  
  5097.  
  5098. /**
  5099.  * Deflate#onEnd(status) -> Void
  5100.  * - status (Number): deflate status. 0 (Z_OK) on success,
  5101.  *   other if not.
  5102.  *
  5103.  * Called once after you tell deflate that the input stream is
  5104.  * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5105.  * or if an error happened. By default - join collected chunks,
  5106.  * free memory and fill `results` / `err` properties.
  5107.  **/
  5108. Deflate.prototype.onEnd = function (status) {
  5109.   // On success - join
  5110.   if (status === Z_OK) {
  5111.     if (this.options.to === 'string') {
  5112.       this.result = this.chunks.join('');
  5113.     } else {
  5114.       this.result = utils.flattenChunks(this.chunks);
  5115.     }
  5116.   }
  5117.   this.chunks = [];
  5118.   this.err = status;
  5119.   this.msg = this.strm.msg;
  5120. };
  5121.  
  5122.  
  5123. /**
  5124.  * deflate(data[, options]) -> Uint8Array|Array|String
  5125.  * - data (Uint8Array|Array|String): input data to compress.
  5126.  * - options (Object): zlib deflate options.
  5127.  *
  5128.  * Compress `data` with deflate algorithm and `options`.
  5129.  *
  5130.  * Supported options are:
  5131.  *
  5132.  * - level
  5133.  * - windowBits
  5134.  * - memLevel
  5135.  * - strategy
  5136.  * - dictionary
  5137.  *
  5138.  * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5139.  * for more information on these.
  5140.  *
  5141.  * Sugar (options):
  5142.  *
  5143.  * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5144.  *   negative windowBits implicitly.
  5145.  * - `to` (String) - if equal to 'string', then result will be "binary string"
  5146.  *    (each char code [0..255])
  5147.  *
  5148.  * ##### Example:
  5149.  *
  5150.  * ```javascript
  5151.  * var pako = require('pako')
  5152.  *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  5153.  *
  5154.  * console.log(pako.deflate(data));
  5155.  * ```
  5156.  **/
  5157. function deflate(input, options) {
  5158.   var deflator = new Deflate(options);
  5159.  
  5160.   deflator.push(input, true);
  5161.  
  5162.   // That will never happens, if you don't cheat with options :)
  5163.   if (deflator.err) { throw deflator.msg; }
  5164.  
  5165.   return deflator.result;
  5166. }
  5167.  
  5168.  
  5169. /**
  5170.  * deflateRaw(data[, options]) -> Uint8Array|Array|String
  5171.  * - data (Uint8Array|Array|String): input data to compress.
  5172.  * - options (Object): zlib deflate options.
  5173.  *
  5174.  * The same as [[deflate]], but creates raw data, without wrapper
  5175.  * (header and adler32 crc).
  5176.  **/
  5177. function deflateRaw(input, options) {
  5178.   options = options || {};
  5179.   options.raw = true;
  5180.   return deflate(input, options);
  5181. }
  5182.  
  5183.  
  5184. /**
  5185.  * gzip(data[, options]) -> Uint8Array|Array|String
  5186.  * - data (Uint8Array|Array|String): input data to compress.
  5187.  * - options (Object): zlib deflate options.
  5188.  *
  5189.  * The same as [[deflate]], but create gzip wrapper instead of
  5190.  * deflate one.
  5191.  **/
  5192. function gzip(input, options) {
  5193.   options = options || {};
  5194.   options.gzip = true;
  5195.   return deflate(input, options);
  5196. }
  5197.  
  5198.  
  5199. exports.Deflate = Deflate;
  5200. exports.deflate = deflate;
  5201. exports.deflateRaw = deflateRaw;
  5202. exports.gzip = gzip;
  5203.  
  5204. },{"./utils/common":62,"./utils/strings":63,"./zlib/deflate":67,"./zlib/messages":72,"./zlib/zstream":74}],61:[function(require,module,exports){
  5205. 'use strict';
  5206.  
  5207.  
  5208. var zlib_inflate = require('./zlib/inflate');
  5209. var utils        = require('./utils/common');
  5210. var strings      = require('./utils/strings');
  5211. var c            = require('./zlib/constants');
  5212. var msg          = require('./zlib/messages');
  5213. var ZStream      = require('./zlib/zstream');
  5214. var GZheader     = require('./zlib/gzheader');
  5215.  
  5216. var toString = Object.prototype.toString;
  5217.  
  5218. /**
  5219.  * class Inflate
  5220.  *
  5221.  * Generic JS-style wrapper for zlib calls. If you don't need
  5222.  * streaming behaviour - use more simple functions: [[inflate]]
  5223.  * and [[inflateRaw]].
  5224.  **/
  5225.  
  5226. /* internal
  5227.  * inflate.chunks -> Array
  5228.  *
  5229.  * Chunks of output data, if [[Inflate#onData]] not overriden.
  5230.  **/
  5231.  
  5232. /**
  5233.  * Inflate.result -> Uint8Array|Array|String
  5234.  *
  5235.  * Uncompressed result, generated by default [[Inflate#onData]]
  5236.  * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  5237.  * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  5238.  * push a chunk with explicit flush (call [[Inflate#push]] with
  5239.  * `Z_SYNC_FLUSH` param).
  5240.  **/
  5241.  
  5242. /**
  5243.  * Inflate.err -> Number
  5244.  *
  5245.  * Error code after inflate finished. 0 (Z_OK) on success.
  5246.  * Should be checked if broken data possible.
  5247.  **/
  5248.  
  5249. /**
  5250.  * Inflate.msg -> String
  5251.  *
  5252.  * Error message, if [[Inflate.err]] != 0
  5253.  **/
  5254.  
  5255.  
  5256. /**
  5257.  * new Inflate(options)
  5258.  * - options (Object): zlib inflate options.
  5259.  *
  5260.  * Creates new inflator instance with specified params. Throws exception
  5261.  * on bad params. Supported options:
  5262.  *
  5263.  * - `windowBits`
  5264.  * - `dictionary`
  5265.  *
  5266.  * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5267.  * for more information on these.
  5268.  *
  5269.  * Additional options, for internal needs:
  5270.  *
  5271.  * - `chunkSize` - size of generated data chunks (16K by default)
  5272.  * - `raw` (Boolean) - do raw inflate
  5273.  * - `to` (String) - if equal to 'string', then result will be converted
  5274.  *   from utf8 to utf16 (javascript) string. When string output requested,
  5275.  *   chunk length can differ from `chunkSize`, depending on content.
  5276.  *
  5277.  * By default, when no options set, autodetect deflate/gzip data format via
  5278.  * wrapper header.
  5279.  *
  5280.  * ##### Example:
  5281.  *
  5282.  * ```javascript
  5283.  * var pako = require('pako')
  5284.  *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  5285.  *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  5286.  *
  5287.  * var inflate = new pako.Inflate({ level: 3});
  5288.  *
  5289.  * inflate.push(chunk1, false);
  5290.  * inflate.push(chunk2, true);  // true -> last chunk
  5291.  *
  5292.  * if (inflate.err) { throw new Error(inflate.err); }
  5293.  *
  5294.  * console.log(inflate.result);
  5295.  * ```
  5296.  **/
  5297. function Inflate(options) {
  5298.   if (!(this instanceof Inflate)) return new Inflate(options);
  5299.  
  5300.   this.options = utils.assign({
  5301.     chunkSize: 16384,
  5302.     windowBits: 0,
  5303.     to: ''
  5304.   }, options || {});
  5305.  
  5306.   var opt = this.options;
  5307.  
  5308.   // Force window size for `raw` data, if not set directly,
  5309.   // because we have no header for autodetect.
  5310.   if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  5311.     opt.windowBits = -opt.windowBits;
  5312.     if (opt.windowBits === 0) { opt.windowBits = -15; }
  5313.   }
  5314.  
  5315.   // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  5316.   if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  5317.       !(options && options.windowBits)) {
  5318.     opt.windowBits += 32;
  5319.   }
  5320.  
  5321.   // Gzip header has no info about windows size, we can do autodetect only
  5322.   // for deflate. So, if window size not set, force it to max when gzip possible
  5323.   if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  5324.     // bit 3 (16) -> gzipped data
  5325.     // bit 4 (32) -> autodetect gzip/deflate
  5326.     if ((opt.windowBits & 15) === 0) {
  5327.       opt.windowBits |= 15;
  5328.     }
  5329.   }
  5330.  
  5331.   this.err    = 0;      // error code, if happens (0 = Z_OK)
  5332.   this.msg    = '';     // error message
  5333.   this.ended  = false;  // used to avoid multiple onEnd() calls
  5334.   this.chunks = [];     // chunks of compressed data
  5335.  
  5336.   this.strm   = new ZStream();
  5337.   this.strm.avail_out = 0;
  5338.  
  5339.   var status  = zlib_inflate.inflateInit2(
  5340.     this.strm,
  5341.     opt.windowBits
  5342.   );
  5343.  
  5344.   if (status !== c.Z_OK) {
  5345.     throw new Error(msg[status]);
  5346.   }
  5347.  
  5348.   this.header = new GZheader();
  5349.  
  5350.   zlib_inflate.inflateGetHeader(this.strm, this.header);
  5351. }
  5352.  
  5353. /**
  5354.  * Inflate#push(data[, mode]) -> Boolean
  5355.  * - data (Uint8Array|Array|ArrayBuffer|String): input data
  5356.  * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  5357.  *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  5358.  *
  5359.  * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  5360.  * new output chunks. Returns `true` on success. The last data block must have
  5361.  * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  5362.  * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  5363.  * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  5364.  *
  5365.  * On fail call [[Inflate#onEnd]] with error code and return false.
  5366.  *
  5367.  * We strongly recommend to use `Uint8Array` on input for best speed (output
  5368.  * format is detected automatically). Also, don't skip last param and always
  5369.  * use the same type in your code (boolean or number). That will improve JS speed.
  5370.  *
  5371.  * For regular `Array`-s make sure all elements are [0..255].
  5372.  *
  5373.  * ##### Example
  5374.  *
  5375.  * ```javascript
  5376.  * push(chunk, false); // push one of data chunks
  5377.  * ...
  5378.  * push(chunk, true);  // push last chunk
  5379.  * ```
  5380.  **/
  5381. Inflate.prototype.push = function (data, mode) {
  5382.   var strm = this.strm;
  5383.   var chunkSize = this.options.chunkSize;
  5384.   var dictionary = this.options.dictionary;
  5385.   var status, _mode;
  5386.   var next_out_utf8, tail, utf8str;
  5387.   var dict;
  5388.  
  5389.   // Flag to properly process Z_BUF_ERROR on testing inflate call
  5390.   // when we check that all output data was flushed.
  5391.   var allowBufError = false;
  5392.  
  5393.   if (this.ended) { return false; }
  5394.   _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  5395.  
  5396.   // Convert data if needed
  5397.   if (typeof data === 'string') {
  5398.     // Only binary strings can be decompressed on practice
  5399.     strm.input = strings.binstring2buf(data);
  5400.   } else if (toString.call(data) === '[object ArrayBuffer]') {
  5401.     strm.input = new Uint8Array(data);
  5402.   } else {
  5403.     strm.input = data;
  5404.   }
  5405.  
  5406.   strm.next_in = 0;
  5407.   strm.avail_in = strm.input.length;
  5408.  
  5409.   do {
  5410.     if (strm.avail_out === 0) {
  5411.       strm.output = new utils.Buf8(chunkSize);
  5412.       strm.next_out = 0;
  5413.       strm.avail_out = chunkSize;
  5414.     }
  5415.  
  5416.     status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */
  5417.  
  5418.     if (status === c.Z_NEED_DICT && dictionary) {
  5419.       // Convert data if needed
  5420.       if (typeof dictionary === 'string') {
  5421.         dict = strings.string2buf(dictionary);
  5422.       } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  5423.         dict = new Uint8Array(dictionary);
  5424.       } else {
  5425.         dict = dictionary;
  5426.       }
  5427.  
  5428.       status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  5429.  
  5430.     }
  5431.  
  5432.     if (status === c.Z_BUF_ERROR && allowBufError === true) {
  5433.       status = c.Z_OK;
  5434.       allowBufError = false;
  5435.     }
  5436.  
  5437.     if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  5438.       this.onEnd(status);
  5439.       this.ended = true;
  5440.       return false;
  5441.     }
  5442.  
  5443.     if (strm.next_out) {
  5444.       if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  5445.  
  5446.         if (this.options.to === 'string') {
  5447.  
  5448.           next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  5449.  
  5450.           tail = strm.next_out - next_out_utf8;
  5451.           utf8str = strings.buf2string(strm.output, next_out_utf8);
  5452.  
  5453.           // move tail
  5454.           strm.next_out = tail;
  5455.           strm.avail_out = chunkSize - tail;
  5456.           if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  5457.  
  5458.           this.onData(utf8str);
  5459.  
  5460.         } else {
  5461.           this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  5462.         }
  5463.       }
  5464.     }
  5465.  
  5466.     // When no more input data, we should check that internal inflate buffers
  5467.     // are flushed. The only way to do it when avail_out = 0 - run one more
  5468.     // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  5469.     // Here we set flag to process this error properly.
  5470.     //
  5471.     // NOTE. Deflate does not return error in this case and does not needs such
  5472.     // logic.
  5473.     if (strm.avail_in === 0 && strm.avail_out === 0) {
  5474.       allowBufError = true;
  5475.     }
  5476.  
  5477.   } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  5478.  
  5479.   if (status === c.Z_STREAM_END) {
  5480.     _mode = c.Z_FINISH;
  5481.   }
  5482.  
  5483.   // Finalize on the last chunk.
  5484.   if (_mode === c.Z_FINISH) {
  5485.     status = zlib_inflate.inflateEnd(this.strm);
  5486.     this.onEnd(status);
  5487.     this.ended = true;
  5488.     return status === c.Z_OK;
  5489.   }
  5490.  
  5491.   // callback interim results if Z_SYNC_FLUSH.
  5492.   if (_mode === c.Z_SYNC_FLUSH) {
  5493.     this.onEnd(c.Z_OK);
  5494.     strm.avail_out = 0;
  5495.     return true;
  5496.   }
  5497.  
  5498.   return true;
  5499. };
  5500.  
  5501.  
  5502. /**
  5503.  * Inflate#onData(chunk) -> Void
  5504.  * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  5505.  *   on js engine support. When string output requested, each chunk
  5506.  *   will be string.
  5507.  *
  5508.  * By default, stores data blocks in `chunks[]` property and glue
  5509.  * those in `onEnd`. Override this handler, if you need another behaviour.
  5510.  **/
  5511. Inflate.prototype.onData = function (chunk) {
  5512.   this.chunks.push(chunk);
  5513. };
  5514.  
  5515.  
  5516. /**
  5517.  * Inflate#onEnd(status) -> Void
  5518.  * - status (Number): inflate status. 0 (Z_OK) on success,
  5519.  *   other if not.
  5520.  *
  5521.  * Called either after you tell inflate that the input stream is
  5522.  * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  5523.  * or if an error happened. By default - join collected chunks,
  5524.  * free memory and fill `results` / `err` properties.
  5525.  **/
  5526. Inflate.prototype.onEnd = function (status) {
  5527.   // On success - join
  5528.   if (status === c.Z_OK) {
  5529.     if (this.options.to === 'string') {
  5530.       // Glue & convert here, until we teach pako to send
  5531.       // utf8 alligned strings to onData
  5532.       this.result = this.chunks.join('');
  5533.     } else {
  5534.       this.result = utils.flattenChunks(this.chunks);
  5535.     }
  5536.   }
  5537.   this.chunks = [];
  5538.   this.err = status;
  5539.   this.msg = this.strm.msg;
  5540. };
  5541.  
  5542.  
  5543. /**
  5544.  * inflate(data[, options]) -> Uint8Array|Array|String
  5545.  * - data (Uint8Array|Array|String): input data to decompress.
  5546.  * - options (Object): zlib inflate options.
  5547.  *
  5548.  * Decompress `data` with inflate/ungzip and `options`. Autodetect
  5549.  * format via wrapper header by default. That's why we don't provide
  5550.  * separate `ungzip` method.
  5551.  *
  5552.  * Supported options are:
  5553.  *
  5554.  * - windowBits
  5555.  *
  5556.  * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  5557.  * for more information.
  5558.  *
  5559.  * Sugar (options):
  5560.  *
  5561.  * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  5562.  *   negative windowBits implicitly.
  5563.  * - `to` (String) - if equal to 'string', then result will be converted
  5564.  *   from utf8 to utf16 (javascript) string. When string output requested,
  5565.  *   chunk length can differ from `chunkSize`, depending on content.
  5566.  *
  5567.  *
  5568.  * ##### Example:
  5569.  *
  5570.  * ```javascript
  5571.  * var pako = require('pako')
  5572.  *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  5573.  *   , output;
  5574.  *
  5575.  * try {
  5576.  *   output = pako.inflate(input);
  5577.  * } catch (err)
  5578.  *   console.log(err);
  5579.  * }
  5580.  * ```
  5581.  **/
  5582. function inflate(input, options) {
  5583.   var inflator = new Inflate(options);
  5584.  
  5585.   inflator.push(input, true);
  5586.  
  5587.   // That will never happens, if you don't cheat with options :)
  5588.   if (inflator.err) { throw inflator.msg; }
  5589.  
  5590.   return inflator.result;
  5591. }
  5592.  
  5593.  
  5594. /**
  5595.  * inflateRaw(data[, options]) -> Uint8Array|Array|String
  5596.  * - data (Uint8Array|Array|String): input data to decompress.
  5597.  * - options (Object): zlib inflate options.
  5598.  *
  5599.  * The same as [[inflate]], but creates raw data, without wrapper
  5600.  * (header and adler32 crc).
  5601.  **/
  5602. function inflateRaw(input, options) {
  5603.   options = options || {};
  5604.   options.raw = true;
  5605.   return inflate(input, options);
  5606. }
  5607.  
  5608.  
  5609. /**
  5610.  * ungzip(data[, options]) -> Uint8Array|Array|String
  5611.  * - data (Uint8Array|Array|String): input data to decompress.
  5612.  * - options (Object): zlib inflate options.
  5613.  *
  5614.  * Just shortcut to [[inflate]], because it autodetects format
  5615.  * by header.content. Done for convenience.
  5616.  **/
  5617.  
  5618.  
  5619. exports.Inflate = Inflate;
  5620. exports.inflate = inflate;
  5621. exports.inflateRaw = inflateRaw;
  5622. exports.ungzip  = inflate;
  5623.  
  5624. },{"./utils/common":62,"./utils/strings":63,"./zlib/constants":65,"./zlib/gzheader":68,"./zlib/inflate":70,"./zlib/messages":72,"./zlib/zstream":74}],62:[function(require,module,exports){
  5625. 'use strict';
  5626.  
  5627.  
  5628. var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
  5629.                 (typeof Uint16Array !== 'undefined') &&
  5630.                 (typeof Int32Array !== 'undefined');
  5631.  
  5632.  
  5633. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  5634.   var sources = Array.prototype.slice.call(arguments, 1);
  5635.   while (sources.length) {
  5636.     var source = sources.shift();
  5637.     if (!source) { continue; }
  5638.  
  5639.     if (typeof source !== 'object') {
  5640.       throw new TypeError(source + 'must be non-object');
  5641.     }
  5642.  
  5643.     for (var p in source) {
  5644.       if (source.hasOwnProperty(p)) {
  5645.         obj[p] = source[p];
  5646.       }
  5647.     }
  5648.   }
  5649.  
  5650.   return obj;
  5651. };
  5652.  
  5653.  
  5654. // reduce buffer size, avoiding mem copy
  5655. exports.shrinkBuf = function (buf, size) {
  5656.   if (buf.length === size) { return buf; }
  5657.   if (buf.subarray) { return buf.subarray(0, size); }
  5658.   buf.length = size;
  5659.   return buf;
  5660. };
  5661.  
  5662.  
  5663. var fnTyped = {
  5664.   arraySet: function (dest, src, src_offs, len, dest_offs) {
  5665.     if (src.subarray && dest.subarray) {
  5666.       dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  5667.       return;
  5668.     }
  5669.     // Fallback to ordinary array
  5670.     for (var i = 0; i < len; i++) {
  5671.       dest[dest_offs + i] = src[src_offs + i];
  5672.     }
  5673.   },
  5674.   // Join array of chunks to single array.
  5675.   flattenChunks: function (chunks) {
  5676.     var i, l, len, pos, chunk, result;
  5677.  
  5678.     // calculate data length
  5679.     len = 0;
  5680.     for (i = 0, l = chunks.length; i < l; i++) {
  5681.       len += chunks[i].length;
  5682.     }
  5683.  
  5684.     // join chunks
  5685.     result = new Uint8Array(len);
  5686.     pos = 0;
  5687.     for (i = 0, l = chunks.length; i < l; i++) {
  5688.       chunk = chunks[i];
  5689.       result.set(chunk, pos);
  5690.       pos += chunk.length;
  5691.     }
  5692.  
  5693.     return result;
  5694.   }
  5695. };
  5696.  
  5697. var fnUntyped = {
  5698.   arraySet: function (dest, src, src_offs, len, dest_offs) {
  5699.     for (var i = 0; i < len; i++) {
  5700.       dest[dest_offs + i] = src[src_offs + i];
  5701.     }
  5702.   },
  5703.   // Join array of chunks to single array.
  5704.   flattenChunks: function (chunks) {
  5705.     return [].concat.apply([], chunks);
  5706.   }
  5707. };
  5708.  
  5709.  
  5710. // Enable/Disable typed arrays use, for testing
  5711. //
  5712. exports.setTyped = function (on) {
  5713.   if (on) {
  5714.     exports.Buf8  = Uint8Array;
  5715.     exports.Buf16 = Uint16Array;
  5716.     exports.Buf32 = Int32Array;
  5717.     exports.assign(exports, fnTyped);
  5718.   } else {
  5719.     exports.Buf8  = Array;
  5720.     exports.Buf16 = Array;
  5721.     exports.Buf32 = Array;
  5722.     exports.assign(exports, fnUntyped);
  5723.   }
  5724. };
  5725.  
  5726. exports.setTyped(TYPED_OK);
  5727.  
  5728. },{}],63:[function(require,module,exports){
  5729. // String encode/decode helpers
  5730. 'use strict';
  5731.  
  5732.  
  5733. var utils = require('./common');
  5734.  
  5735.  
  5736. // Quick check if we can use fast array to bin string conversion
  5737. //
  5738. // - apply(Array) can fail on Android 2.2
  5739. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  5740. //
  5741. var STR_APPLY_OK = true;
  5742. var STR_APPLY_UIA_OK = true;
  5743.  
  5744. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  5745. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  5746.  
  5747.  
  5748. // Table with utf8 lengths (calculated by first byte of sequence)
  5749. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  5750. // because max possible codepoint is 0x10ffff
  5751. var _utf8len = new utils.Buf8(256);
  5752. for (var q = 0; q < 256; q++) {
  5753.   _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  5754. }
  5755. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  5756.  
  5757.  
  5758. // convert string to array (typed, when possible)
  5759. exports.string2buf = function (str) {
  5760.   var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  5761.  
  5762.   // count binary size
  5763.   for (m_pos = 0; m_pos < str_len; m_pos++) {
  5764.     c = str.charCodeAt(m_pos);
  5765.     if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5766.       c2 = str.charCodeAt(m_pos + 1);
  5767.       if ((c2 & 0xfc00) === 0xdc00) {
  5768.         c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5769.         m_pos++;
  5770.       }
  5771.     }
  5772.     buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  5773.   }
  5774.  
  5775.   // allocate buffer
  5776.   buf = new utils.Buf8(buf_len);
  5777.  
  5778.   // convert
  5779.   for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  5780.     c = str.charCodeAt(m_pos);
  5781.     if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  5782.       c2 = str.charCodeAt(m_pos + 1);
  5783.       if ((c2 & 0xfc00) === 0xdc00) {
  5784.         c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  5785.         m_pos++;
  5786.       }
  5787.     }
  5788.     if (c < 0x80) {
  5789.       /* one byte */
  5790.       buf[i++] = c;
  5791.     } else if (c < 0x800) {
  5792.       /* two bytes */
  5793.       buf[i++] = 0xC0 | (c >>> 6);
  5794.       buf[i++] = 0x80 | (c & 0x3f);
  5795.     } else if (c < 0x10000) {
  5796.       /* three bytes */
  5797.       buf[i++] = 0xE0 | (c >>> 12);
  5798.       buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5799.       buf[i++] = 0x80 | (c & 0x3f);
  5800.     } else {
  5801.       /* four bytes */
  5802.       buf[i++] = 0xf0 | (c >>> 18);
  5803.       buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  5804.       buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5805.       buf[i++] = 0x80 | (c & 0x3f);
  5806.     }
  5807.   }
  5808.  
  5809.   return buf;
  5810. };
  5811.  
  5812. // Helper (used in 2 places)
  5813. function buf2binstring(buf, len) {
  5814.   // use fallback for big arrays to avoid stack overflow
  5815.   if (len < 65537) {
  5816.     if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  5817.       return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  5818.     }
  5819.   }
  5820.  
  5821.   var result = '';
  5822.   for (var i = 0; i < len; i++) {
  5823.     result += String.fromCharCode(buf[i]);
  5824.   }
  5825.   return result;
  5826. }
  5827.  
  5828.  
  5829. // Convert byte array to binary string
  5830. exports.buf2binstring = function (buf) {
  5831.   return buf2binstring(buf, buf.length);
  5832. };
  5833.  
  5834.  
  5835. // Convert binary string (typed, when possible)
  5836. exports.binstring2buf = function (str) {
  5837.   var buf = new utils.Buf8(str.length);
  5838.   for (var i = 0, len = buf.length; i < len; i++) {
  5839.     buf[i] = str.charCodeAt(i);
  5840.   }
  5841.   return buf;
  5842. };
  5843.  
  5844.  
  5845. // convert array to string
  5846. exports.buf2string = function (buf, max) {
  5847.   var i, out, c, c_len;
  5848.   var len = max || buf.length;
  5849.  
  5850.   // Reserve max possible length (2 words per char)
  5851.   // NB: by unknown reasons, Array is significantly faster for
  5852.   //     String.fromCharCode.apply than Uint16Array.
  5853.   var utf16buf = new Array(len * 2);
  5854.  
  5855.   for (out = 0, i = 0; i < len;) {
  5856.     c = buf[i++];
  5857.     // quick process ascii
  5858.     if (c < 0x80) { utf16buf[out++] = c; continue; }
  5859.  
  5860.     c_len = _utf8len[c];
  5861.     // skip 5 & 6 byte codes
  5862.     if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  5863.  
  5864.     // apply mask on first byte
  5865.     c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  5866.     // join the rest
  5867.     while (c_len > 1 && i < len) {
  5868.       c = (c << 6) | (buf[i++] & 0x3f);
  5869.       c_len--;
  5870.     }
  5871.  
  5872.     // terminated by end of string?
  5873.     if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  5874.  
  5875.     if (c < 0x10000) {
  5876.       utf16buf[out++] = c;
  5877.     } else {
  5878.       c -= 0x10000;
  5879.       utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  5880.       utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  5881.     }
  5882.   }
  5883.  
  5884.   return buf2binstring(utf16buf, out);
  5885. };
  5886.  
  5887.  
  5888. // Calculate max possible position in utf8 buffer,
  5889. // that will not break sequence. If that's not possible
  5890. // - (very small limits) return max size as is.
  5891. //
  5892. // buf[] - utf8 bytes array
  5893. // max   - length limit (mandatory);
  5894. exports.utf8border = function (buf, max) {
  5895.   var pos;
  5896.  
  5897.   max = max || buf.length;
  5898.   if (max > buf.length) { max = buf.length; }
  5899.  
  5900.   // go back from last position, until start of sequence found
  5901.   pos = max - 1;
  5902.   while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  5903.  
  5904.   // Fuckup - very small and broken sequence,
  5905.   // return max, because we should return something anyway.
  5906.   if (pos < 0) { return max; }
  5907.  
  5908.   // If we came to start of buffer - that means vuffer is too small,
  5909.   // return max too.
  5910.   if (pos === 0) { return max; }
  5911.  
  5912.   return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  5913. };
  5914.  
  5915. },{"./common":62}],64:[function(require,module,exports){
  5916. 'use strict';
  5917.  
  5918. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  5919. // It doesn't worth to make additional optimizationa as in original.
  5920. // Small size is preferable.
  5921.  
  5922. function adler32(adler, buf, len, pos) {
  5923.   var s1 = (adler & 0xffff) |0,
  5924.       s2 = ((adler >>> 16) & 0xffff) |0,
  5925.       n = 0;
  5926.  
  5927.   while (len !== 0) {
  5928.     // Set limit ~ twice less than 5552, to keep
  5929.     // s2 in 31-bits, because we force signed ints.
  5930.     // in other case %= will fail.
  5931.     n = len > 2000 ? 2000 : len;
  5932.     len -= n;
  5933.  
  5934.     do {
  5935.       s1 = (s1 + buf[pos++]) |0;
  5936.       s2 = (s2 + s1) |0;
  5937.     } while (--n);
  5938.  
  5939.     s1 %= 65521;
  5940.     s2 %= 65521;
  5941.   }
  5942.  
  5943.   return (s1 | (s2 << 16)) |0;
  5944. }
  5945.  
  5946.  
  5947. module.exports = adler32;
  5948.  
  5949. },{}],65:[function(require,module,exports){
  5950. 'use strict';
  5951.  
  5952.  
  5953. module.exports = {
  5954.  
  5955.   /* Allowed flush values; see deflate() and inflate() below for details */
  5956.   Z_NO_FLUSH:         0,
  5957.   Z_PARTIAL_FLUSH:    1,
  5958.   Z_SYNC_FLUSH:       2,
  5959.   Z_FULL_FLUSH:       3,
  5960.   Z_FINISH:           4,
  5961.   Z_BLOCK:            5,
  5962.   Z_TREES:            6,
  5963.  
  5964.   /* Return codes for the compression/decompression functions. Negative values
  5965.   * are errors, positive values are used for special but normal events.
  5966.   */
  5967.   Z_OK:               0,
  5968.   Z_STREAM_END:       1,
  5969.   Z_NEED_DICT:        2,
  5970.   Z_ERRNO:           -1,
  5971.   Z_STREAM_ERROR:    -2,
  5972.   Z_DATA_ERROR:      -3,
  5973.   //Z_MEM_ERROR:     -4,
  5974.   Z_BUF_ERROR:       -5,
  5975.   //Z_VERSION_ERROR: -6,
  5976.  
  5977.   /* compression levels */
  5978.   Z_NO_COMPRESSION:         0,
  5979.   Z_BEST_SPEED:             1,
  5980.   Z_BEST_COMPRESSION:       9,
  5981.   Z_DEFAULT_COMPRESSION:   -1,
  5982.  
  5983.  
  5984.   Z_FILTERED:               1,
  5985.   Z_HUFFMAN_ONLY:           2,
  5986.   Z_RLE:                    3,
  5987.   Z_FIXED:                  4,
  5988.   Z_DEFAULT_STRATEGY:       0,
  5989.  
  5990.   /* Possible values of the data_type field (though see inflate()) */
  5991.   Z_BINARY:                 0,
  5992.   Z_TEXT:                   1,
  5993.   //Z_ASCII:                1, // = Z_TEXT (deprecated)
  5994.   Z_UNKNOWN:                2,
  5995.  
  5996.   /* The deflate compression method */
  5997.   Z_DEFLATED:               8
  5998.   //Z_NULL:                 null // Use -1 or null inline, depending on var type
  5999. };
  6000.  
  6001. },{}],66:[function(require,module,exports){
  6002. 'use strict';
  6003.  
  6004. // Note: we can't get significant speed boost here.
  6005. // So write code to minimize size - no pregenerated tables
  6006. // and array tools dependencies.
  6007.  
  6008.  
  6009. // Use ordinary array, since untyped makes no boost here
  6010. function makeTable() {
  6011.   var c, table = [];
  6012.  
  6013.   for (var n = 0; n < 256; n++) {
  6014.     c = n;
  6015.     for (var k = 0; k < 8; k++) {
  6016.       c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  6017.     }
  6018.     table[n] = c;
  6019.   }
  6020.  
  6021.   return table;
  6022. }
  6023.  
  6024. // Create table on load. Just 255 signed longs. Not a problem.
  6025. var crcTable = makeTable();
  6026.  
  6027.  
  6028. function crc32(crc, buf, len, pos) {
  6029.   var t = crcTable,
  6030.       end = pos + len;
  6031.  
  6032.   crc ^= -1;
  6033.  
  6034.   for (var i = pos; i < end; i++) {
  6035.     crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  6036.   }
  6037.  
  6038.   return (crc ^ (-1)); // >>> 0;
  6039. }
  6040.  
  6041.  
  6042. module.exports = crc32;
  6043.  
  6044. },{}],67:[function(require,module,exports){
  6045. 'use strict';
  6046.  
  6047. var utils   = require('../utils/common');
  6048. var trees   = require('./trees');
  6049. var adler32 = require('./adler32');
  6050. var crc32   = require('./crc32');
  6051. var msg     = require('./messages');
  6052.  
  6053. /* Public constants ==========================================================*/
  6054. /* ===========================================================================*/
  6055.  
  6056.  
  6057. /* Allowed flush values; see deflate() and inflate() below for details */
  6058. var Z_NO_FLUSH      = 0;
  6059. var Z_PARTIAL_FLUSH = 1;
  6060. //var Z_SYNC_FLUSH    = 2;
  6061. var Z_FULL_FLUSH    = 3;
  6062. var Z_FINISH        = 4;
  6063. var Z_BLOCK         = 5;
  6064. //var Z_TREES         = 6;
  6065.  
  6066.  
  6067. /* Return codes for the compression/decompression functions. Negative values
  6068.  * are errors, positive values are used for special but normal events.
  6069.  */
  6070. var Z_OK            = 0;
  6071. var Z_STREAM_END    = 1;
  6072. //var Z_NEED_DICT     = 2;
  6073. //var Z_ERRNO         = -1;
  6074. var Z_STREAM_ERROR  = -2;
  6075. var Z_DATA_ERROR    = -3;
  6076. //var Z_MEM_ERROR     = -4;
  6077. var Z_BUF_ERROR     = -5;
  6078. //var Z_VERSION_ERROR = -6;
  6079.  
  6080.  
  6081. /* compression levels */
  6082. //var Z_NO_COMPRESSION      = 0;
  6083. //var Z_BEST_SPEED          = 1;
  6084. //var Z_BEST_COMPRESSION    = 9;
  6085. var Z_DEFAULT_COMPRESSION = -1;
  6086.  
  6087.  
  6088. var Z_FILTERED            = 1;
  6089. var Z_HUFFMAN_ONLY        = 2;
  6090. var Z_RLE                 = 3;
  6091. var Z_FIXED               = 4;
  6092. var Z_DEFAULT_STRATEGY    = 0;
  6093.  
  6094. /* Possible values of the data_type field (though see inflate()) */
  6095. //var Z_BINARY              = 0;
  6096. //var Z_TEXT                = 1;
  6097. //var Z_ASCII               = 1; // = Z_TEXT
  6098. var Z_UNKNOWN             = 2;
  6099.  
  6100.  
  6101. /* The deflate compression method */
  6102. var Z_DEFLATED  = 8;
  6103.  
  6104. /*============================================================================*/
  6105.  
  6106.  
  6107. var MAX_MEM_LEVEL = 9;
  6108. /* Maximum value for memLevel in deflateInit2 */
  6109. var MAX_WBITS = 15;
  6110. /* 32K LZ77 window */
  6111. var DEF_MEM_LEVEL = 8;
  6112.  
  6113.  
  6114. var LENGTH_CODES  = 29;
  6115. /* number of length codes, not counting the special END_BLOCK code */
  6116. var LITERALS      = 256;
  6117. /* number of literal bytes 0..255 */
  6118. var L_CODES       = LITERALS + 1 + LENGTH_CODES;
  6119. /* number of Literal or Length codes, including the END_BLOCK code */
  6120. var D_CODES       = 30;
  6121. /* number of distance codes */
  6122. var BL_CODES      = 19;
  6123. /* number of codes used to transfer the bit lengths */
  6124. var HEAP_SIZE     = 2 * L_CODES + 1;
  6125. /* maximum heap size */
  6126. var MAX_BITS  = 15;
  6127. /* All codes must not exceed MAX_BITS bits */
  6128.  
  6129. var MIN_MATCH = 3;
  6130. var MAX_MATCH = 258;
  6131. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  6132.  
  6133. var PRESET_DICT = 0x20;
  6134.  
  6135. var INIT_STATE = 42;
  6136. var EXTRA_STATE = 69;
  6137. var NAME_STATE = 73;
  6138. var COMMENT_STATE = 91;
  6139. var HCRC_STATE = 103;
  6140. var BUSY_STATE = 113;
  6141. var FINISH_STATE = 666;
  6142.  
  6143. var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
  6144. var BS_BLOCK_DONE     = 2; /* block flush performed */
  6145. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  6146. var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
  6147.  
  6148. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  6149.  
  6150. function err(strm, errorCode) {
  6151.   strm.msg = msg[errorCode];
  6152.   return errorCode;
  6153. }
  6154.  
  6155. function rank(f) {
  6156.   return ((f) << 1) - ((f) > 4 ? 9 : 0);
  6157. }
  6158.  
  6159. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  6160.  
  6161.  
  6162. /* =========================================================================
  6163.  * Flush as much pending output as possible. All deflate() output goes
  6164.  * through this function so some applications may wish to modify it
  6165.  * to avoid allocating a large strm->output buffer and copying into it.
  6166.  * (See also read_buf()).
  6167.  */
  6168. function flush_pending(strm) {
  6169.   var s = strm.state;
  6170.  
  6171.   //_tr_flush_bits(s);
  6172.   var len = s.pending;
  6173.   if (len > strm.avail_out) {
  6174.     len = strm.avail_out;
  6175.   }
  6176.   if (len === 0) { return; }
  6177.  
  6178.   utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  6179.   strm.next_out += len;
  6180.   s.pending_out += len;
  6181.   strm.total_out += len;
  6182.   strm.avail_out -= len;
  6183.   s.pending -= len;
  6184.   if (s.pending === 0) {
  6185.     s.pending_out = 0;
  6186.   }
  6187. }
  6188.  
  6189.  
  6190. function flush_block_only(s, last) {
  6191.   trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  6192.   s.block_start = s.strstart;
  6193.   flush_pending(s.strm);
  6194. }
  6195.  
  6196.  
  6197. function put_byte(s, b) {
  6198.   s.pending_buf[s.pending++] = b;
  6199. }
  6200.  
  6201.  
  6202. /* =========================================================================
  6203.  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  6204.  * IN assertion: the stream state is correct and there is enough room in
  6205.  * pending_buf.
  6206.  */
  6207. function putShortMSB(s, b) {
  6208. //  put_byte(s, (Byte)(b >> 8));
  6209. //  put_byte(s, (Byte)(b & 0xff));
  6210.   s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  6211.   s.pending_buf[s.pending++] = b & 0xff;
  6212. }
  6213.  
  6214.  
  6215. /* ===========================================================================
  6216.  * Read a new buffer from the current input stream, update the adler32
  6217.  * and total number of bytes read.  All deflate() input goes through
  6218.  * this function so some applications may wish to modify it to avoid
  6219.  * allocating a large strm->input buffer and copying from it.
  6220.  * (See also flush_pending()).
  6221.  */
  6222. function read_buf(strm, buf, start, size) {
  6223.   var len = strm.avail_in;
  6224.  
  6225.   if (len > size) { len = size; }
  6226.   if (len === 0) { return 0; }
  6227.  
  6228.   strm.avail_in -= len;
  6229.  
  6230.   // zmemcpy(buf, strm->next_in, len);
  6231.   utils.arraySet(buf, strm.input, strm.next_in, len, start);
  6232.   if (strm.state.wrap === 1) {
  6233.     strm.adler = adler32(strm.adler, buf, len, start);
  6234.   }
  6235.  
  6236.   else if (strm.state.wrap === 2) {
  6237.     strm.adler = crc32(strm.adler, buf, len, start);
  6238.   }
  6239.  
  6240.   strm.next_in += len;
  6241.   strm.total_in += len;
  6242.  
  6243.   return len;
  6244. }
  6245.  
  6246.  
  6247. /* ===========================================================================
  6248.  * Set match_start to the longest match starting at the given string and
  6249.  * return its length. Matches shorter or equal to prev_length are discarded,
  6250.  * in which case the result is equal to prev_length and match_start is
  6251.  * garbage.
  6252.  * IN assertions: cur_match is the head of the hash chain for the current
  6253.  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  6254.  * OUT assertion: the match length is not greater than s->lookahead.
  6255.  */
  6256. function longest_match(s, cur_match) {
  6257.   var chain_length = s.max_chain_length;      /* max hash chain length */
  6258.   var scan = s.strstart; /* current string */
  6259.   var match;                       /* matched string */
  6260.   var len;                           /* length of current match */
  6261.   var best_len = s.prev_length;              /* best match length so far */
  6262.   var nice_match = s.nice_match;             /* stop if match long enough */
  6263.   var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  6264.       s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  6265.  
  6266.   var _win = s.window; // shortcut
  6267.  
  6268.   var wmask = s.w_mask;
  6269.   var prev  = s.prev;
  6270.  
  6271.   /* Stop when cur_match becomes <= limit. To simplify the code,
  6272.    * we prevent matches with the string of window index 0.
  6273.    */
  6274.  
  6275.   var strend = s.strstart + MAX_MATCH;
  6276.   var scan_end1  = _win[scan + best_len - 1];
  6277.   var scan_end   = _win[scan + best_len];
  6278.  
  6279.   /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  6280.    * It is easy to get rid of this optimization if necessary.
  6281.    */
  6282.   // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  6283.  
  6284.   /* Do not waste too much time if we already have a good match: */
  6285.   if (s.prev_length >= s.good_match) {
  6286.     chain_length >>= 2;
  6287.   }
  6288.   /* Do not look for matches beyond the end of the input. This is necessary
  6289.    * to make deflate deterministic.
  6290.    */
  6291.   if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  6292.  
  6293.   // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  6294.  
  6295.   do {
  6296.     // Assert(cur_match < s->strstart, "no future");
  6297.     match = cur_match;
  6298.  
  6299.     /* Skip to next match if the match length cannot increase
  6300.      * or if the match length is less than 2.  Note that the checks below
  6301.      * for insufficient lookahead only occur occasionally for performance
  6302.      * reasons.  Therefore uninitialized memory will be accessed, and
  6303.      * conditional jumps will be made that depend on those values.
  6304.      * However the length of the match is limited to the lookahead, so
  6305.      * the output of deflate is not affected by the uninitialized values.
  6306.      */
  6307.  
  6308.     if (_win[match + best_len]     !== scan_end  ||
  6309.         _win[match + best_len - 1] !== scan_end1 ||
  6310.         _win[match]                !== _win[scan] ||
  6311.         _win[++match]              !== _win[scan + 1]) {
  6312.       continue;
  6313.     }
  6314.  
  6315.     /* The check at best_len-1 can be removed because it will be made
  6316.      * again later. (This heuristic is not always a win.)
  6317.      * It is not necessary to compare scan[2] and match[2] since they
  6318.      * are always equal when the other bytes match, given that
  6319.      * the hash keys are equal and that HASH_BITS >= 8.
  6320.      */
  6321.     scan += 2;
  6322.     match++;
  6323.     // Assert(*scan == *match, "match[2]?");
  6324.  
  6325.     /* We check for insufficient lookahead only every 8th comparison;
  6326.      * the 256th check will be made at strstart+258.
  6327.      */
  6328.     do {
  6329.       /*jshint noempty:false*/
  6330.     } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6331.              _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6332.              _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6333.              _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  6334.              scan < strend);
  6335.  
  6336.     // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  6337.  
  6338.     len = MAX_MATCH - (strend - scan);
  6339.     scan = strend - MAX_MATCH;
  6340.  
  6341.     if (len > best_len) {
  6342.       s.match_start = cur_match;
  6343.       best_len = len;
  6344.       if (len >= nice_match) {
  6345.         break;
  6346.       }
  6347.       scan_end1  = _win[scan + best_len - 1];
  6348.       scan_end   = _win[scan + best_len];
  6349.     }
  6350.   } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  6351.  
  6352.   if (best_len <= s.lookahead) {
  6353.     return best_len;
  6354.   }
  6355.   return s.lookahead;
  6356. }
  6357.  
  6358.  
  6359. /* ===========================================================================
  6360.  * Fill the window when the lookahead becomes insufficient.
  6361.  * Updates strstart and lookahead.
  6362.  *
  6363.  * IN assertion: lookahead < MIN_LOOKAHEAD
  6364.  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  6365.  *    At least one byte has been read, or avail_in == 0; reads are
  6366.  *    performed for at least two bytes (required for the zip translate_eol
  6367.  *    option -- not supported here).
  6368.  */
  6369. function fill_window(s) {
  6370.   var _w_size = s.w_size;
  6371.   var p, n, m, more, str;
  6372.  
  6373.   //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  6374.  
  6375.   do {
  6376.     more = s.window_size - s.lookahead - s.strstart;
  6377.  
  6378.     // JS ints have 32 bit, block below not needed
  6379.     /* Deal with !@#$% 64K limit: */
  6380.     //if (sizeof(int) <= 2) {
  6381.     //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  6382.     //        more = wsize;
  6383.     //
  6384.     //  } else if (more == (unsigned)(-1)) {
  6385.     //        /* Very unlikely, but possible on 16 bit machine if
  6386.     //         * strstart == 0 && lookahead == 1 (input done a byte at time)
  6387.     //         */
  6388.     //        more--;
  6389.     //    }
  6390.     //}
  6391.  
  6392.  
  6393.     /* If the window is almost full and there is insufficient lookahead,
  6394.      * move the upper half to the lower one to make room in the upper half.
  6395.      */
  6396.     if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  6397.  
  6398.       utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  6399.       s.match_start -= _w_size;
  6400.       s.strstart -= _w_size;
  6401.       /* we now have strstart >= MAX_DIST */
  6402.       s.block_start -= _w_size;
  6403.  
  6404.       /* Slide the hash table (could be avoided with 32 bit values
  6405.        at the expense of memory usage). We slide even when level == 0
  6406.        to keep the hash table consistent if we switch back to level > 0
  6407.        later. (Using level 0 permanently is not an optimal usage of
  6408.        zlib, so we don't care about this pathological case.)
  6409.        */
  6410.  
  6411.       n = s.hash_size;
  6412.       p = n;
  6413.       do {
  6414.         m = s.head[--p];
  6415.         s.head[p] = (m >= _w_size ? m - _w_size : 0);
  6416.       } while (--n);
  6417.  
  6418.       n = _w_size;
  6419.       p = n;
  6420.       do {
  6421.         m = s.prev[--p];
  6422.         s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  6423.         /* If n is not on any hash chain, prev[n] is garbage but
  6424.          * its value will never be used.
  6425.          */
  6426.       } while (--n);
  6427.  
  6428.       more += _w_size;
  6429.     }
  6430.     if (s.strm.avail_in === 0) {
  6431.       break;
  6432.     }
  6433.  
  6434.     /* If there was no sliding:
  6435.      *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  6436.      *    more == window_size - lookahead - strstart
  6437.      * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  6438.      * => more >= window_size - 2*WSIZE + 2
  6439.      * In the BIG_MEM or MMAP case (not yet supported),
  6440.      *   window_size == input_size + MIN_LOOKAHEAD  &&
  6441.      *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  6442.      * Otherwise, window_size == 2*WSIZE so more >= 2.
  6443.      * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  6444.      */
  6445.     //Assert(more >= 2, "more < 2");
  6446.     n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  6447.     s.lookahead += n;
  6448.  
  6449.     /* Initialize the hash value now that we have some input: */
  6450.     if (s.lookahead + s.insert >= MIN_MATCH) {
  6451.       str = s.strstart - s.insert;
  6452.       s.ins_h = s.window[str];
  6453.  
  6454.       /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  6455.       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  6456. //#if MIN_MATCH != 3
  6457. //        Call update_hash() MIN_MATCH-3 more times
  6458. //#endif
  6459.       while (s.insert) {
  6460.         /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6461.         s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6462.  
  6463.         s.prev[str & s.w_mask] = s.head[s.ins_h];
  6464.         s.head[s.ins_h] = str;
  6465.         str++;
  6466.         s.insert--;
  6467.         if (s.lookahead + s.insert < MIN_MATCH) {
  6468.           break;
  6469.         }
  6470.       }
  6471.     }
  6472.     /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  6473.      * but this is not important since only literal bytes will be emitted.
  6474.      */
  6475.  
  6476.   } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  6477.  
  6478.   /* If the WIN_INIT bytes after the end of the current data have never been
  6479.    * written, then zero those bytes in order to avoid memory check reports of
  6480.    * the use of uninitialized (or uninitialised as Julian writes) bytes by
  6481.    * the longest match routines.  Update the high water mark for the next
  6482.    * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
  6483.    * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  6484.    */
  6485. //  if (s.high_water < s.window_size) {
  6486. //    var curr = s.strstart + s.lookahead;
  6487. //    var init = 0;
  6488. //
  6489. //    if (s.high_water < curr) {
  6490. //      /* Previous high water mark below current data -- zero WIN_INIT
  6491. //       * bytes or up to end of window, whichever is less.
  6492. //       */
  6493. //      init = s.window_size - curr;
  6494. //      if (init > WIN_INIT)
  6495. //        init = WIN_INIT;
  6496. //      zmemzero(s->window + curr, (unsigned)init);
  6497. //      s->high_water = curr + init;
  6498. //    }
  6499. //    else if (s->high_water < (ulg)curr + WIN_INIT) {
  6500. //      /* High water mark at or above current data, but below current data
  6501. //       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  6502. //       * to end of window, whichever is less.
  6503. //       */
  6504. //      init = (ulg)curr + WIN_INIT - s->high_water;
  6505. //      if (init > s->window_size - s->high_water)
  6506. //        init = s->window_size - s->high_water;
  6507. //      zmemzero(s->window + s->high_water, (unsigned)init);
  6508. //      s->high_water += init;
  6509. //    }
  6510. //  }
  6511. //
  6512. //  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  6513. //    "not enough room for search");
  6514. }
  6515.  
  6516. /* ===========================================================================
  6517.  * Copy without compression as much as possible from the input stream, return
  6518.  * the current block state.
  6519.  * This function does not insert new strings in the dictionary since
  6520.  * uncompressible data is probably not useful. This function is used
  6521.  * only for the level=0 compression option.
  6522.  * NOTE: this function should be optimized to avoid extra copying from
  6523.  * window to pending_buf.
  6524.  */
  6525. function deflate_stored(s, flush) {
  6526.   /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  6527.    * to pending_buf_size, and each stored block has a 5 byte header:
  6528.    */
  6529.   var max_block_size = 0xffff;
  6530.  
  6531.   if (max_block_size > s.pending_buf_size - 5) {
  6532.     max_block_size = s.pending_buf_size - 5;
  6533.   }
  6534.  
  6535.   /* Copy as much as possible from input to output: */
  6536.   for (;;) {
  6537.     /* Fill the window as much as possible: */
  6538.     if (s.lookahead <= 1) {
  6539.  
  6540.       //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  6541.       //  s->block_start >= (long)s->w_size, "slide too late");
  6542. //      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  6543. //        s.block_start >= s.w_size)) {
  6544. //        throw  new Error("slide too late");
  6545. //      }
  6546.  
  6547.       fill_window(s);
  6548.       if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  6549.         return BS_NEED_MORE;
  6550.       }
  6551.  
  6552.       if (s.lookahead === 0) {
  6553.         break;
  6554.       }
  6555.       /* flush the current block */
  6556.     }
  6557.     //Assert(s->block_start >= 0L, "block gone");
  6558. //    if (s.block_start < 0) throw new Error("block gone");
  6559.  
  6560.     s.strstart += s.lookahead;
  6561.     s.lookahead = 0;
  6562.  
  6563.     /* Emit a stored block if pending_buf will be full: */
  6564.     var max_start = s.block_start + max_block_size;
  6565.  
  6566.     if (s.strstart === 0 || s.strstart >= max_start) {
  6567.       /* strstart == 0 is possible when wraparound on 16-bit machine */
  6568.       s.lookahead = s.strstart - max_start;
  6569.       s.strstart = max_start;
  6570.       /*** FLUSH_BLOCK(s, 0); ***/
  6571.       flush_block_only(s, false);
  6572.       if (s.strm.avail_out === 0) {
  6573.         return BS_NEED_MORE;
  6574.       }
  6575.       /***/
  6576.  
  6577.  
  6578.     }
  6579.     /* Flush if we may have to slide, otherwise block_start may become
  6580.      * negative and the data will be gone:
  6581.      */
  6582.     if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  6583.       /*** FLUSH_BLOCK(s, 0); ***/
  6584.       flush_block_only(s, false);
  6585.       if (s.strm.avail_out === 0) {
  6586.         return BS_NEED_MORE;
  6587.       }
  6588.       /***/
  6589.     }
  6590.   }
  6591.  
  6592.   s.insert = 0;
  6593.  
  6594.   if (flush === Z_FINISH) {
  6595.     /*** FLUSH_BLOCK(s, 1); ***/
  6596.     flush_block_only(s, true);
  6597.     if (s.strm.avail_out === 0) {
  6598.       return BS_FINISH_STARTED;
  6599.     }
  6600.     /***/
  6601.     return BS_FINISH_DONE;
  6602.   }
  6603.  
  6604.   if (s.strstart > s.block_start) {
  6605.     /*** FLUSH_BLOCK(s, 0); ***/
  6606.     flush_block_only(s, false);
  6607.     if (s.strm.avail_out === 0) {
  6608.       return BS_NEED_MORE;
  6609.     }
  6610.     /***/
  6611.   }
  6612.  
  6613.   return BS_NEED_MORE;
  6614. }
  6615.  
  6616. /* ===========================================================================
  6617.  * Compress as much as possible from the input stream, return the current
  6618.  * block state.
  6619.  * This function does not perform lazy evaluation of matches and inserts
  6620.  * new strings in the dictionary only for unmatched strings or for short
  6621.  * matches. It is used only for the fast compression options.
  6622.  */
  6623. function deflate_fast(s, flush) {
  6624.   var hash_head;        /* head of the hash chain */
  6625.   var bflush;           /* set if current block must be flushed */
  6626.  
  6627.   for (;;) {
  6628.     /* Make sure that we always have enough lookahead, except
  6629.      * at the end of the input file. We need MAX_MATCH bytes
  6630.      * for the next match, plus MIN_MATCH bytes to insert the
  6631.      * string following the next match.
  6632.      */
  6633.     if (s.lookahead < MIN_LOOKAHEAD) {
  6634.       fill_window(s);
  6635.       if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6636.         return BS_NEED_MORE;
  6637.       }
  6638.       if (s.lookahead === 0) {
  6639.         break; /* flush the current block */
  6640.       }
  6641.     }
  6642.  
  6643.     /* Insert the string window[strstart .. strstart+2] in the
  6644.      * dictionary, and set hash_head to the head of the hash chain:
  6645.      */
  6646.     hash_head = 0/*NIL*/;
  6647.     if (s.lookahead >= MIN_MATCH) {
  6648.       /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6649.       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6650.       hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6651.       s.head[s.ins_h] = s.strstart;
  6652.       /***/
  6653.     }
  6654.  
  6655.     /* Find the longest match, discarding those <= prev_length.
  6656.      * At this point we have always match_length < MIN_MATCH
  6657.      */
  6658.     if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  6659.       /* To simplify the code, we prevent matches with the string
  6660.        * of window index 0 (in particular we have to avoid a match
  6661.        * of the string with itself at the start of the input file).
  6662.        */
  6663.       s.match_length = longest_match(s, hash_head);
  6664.       /* longest_match() sets match_start */
  6665.     }
  6666.     if (s.match_length >= MIN_MATCH) {
  6667.       // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  6668.  
  6669.       /*** _tr_tally_dist(s, s.strstart - s.match_start,
  6670.                      s.match_length - MIN_MATCH, bflush); ***/
  6671.       bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  6672.  
  6673.       s.lookahead -= s.match_length;
  6674.  
  6675.       /* Insert new strings in the hash table only if the match length
  6676.        * is not too large. This saves time but degrades compression.
  6677.        */
  6678.       if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  6679.         s.match_length--; /* string at strstart already in table */
  6680.         do {
  6681.           s.strstart++;
  6682.           /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6683.           s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6684.           hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6685.           s.head[s.ins_h] = s.strstart;
  6686.           /***/
  6687.           /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  6688.            * always MIN_MATCH bytes ahead.
  6689.            */
  6690.         } while (--s.match_length !== 0);
  6691.         s.strstart++;
  6692.       } else
  6693.       {
  6694.         s.strstart += s.match_length;
  6695.         s.match_length = 0;
  6696.         s.ins_h = s.window[s.strstart];
  6697.         /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  6698.         s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  6699.  
  6700. //#if MIN_MATCH != 3
  6701. //                Call UPDATE_HASH() MIN_MATCH-3 more times
  6702. //#endif
  6703.         /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  6704.          * matter since it will be recomputed at next deflate call.
  6705.          */
  6706.       }
  6707.     } else {
  6708.       /* No match, output a literal byte */
  6709.       //Tracevv((stderr,"%c", s.window[s.strstart]));
  6710.       /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6711.       bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6712.  
  6713.       s.lookahead--;
  6714.       s.strstart++;
  6715.     }
  6716.     if (bflush) {
  6717.       /*** FLUSH_BLOCK(s, 0); ***/
  6718.       flush_block_only(s, false);
  6719.       if (s.strm.avail_out === 0) {
  6720.         return BS_NEED_MORE;
  6721.       }
  6722.       /***/
  6723.     }
  6724.   }
  6725.   s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  6726.   if (flush === Z_FINISH) {
  6727.     /*** FLUSH_BLOCK(s, 1); ***/
  6728.     flush_block_only(s, true);
  6729.     if (s.strm.avail_out === 0) {
  6730.       return BS_FINISH_STARTED;
  6731.     }
  6732.     /***/
  6733.     return BS_FINISH_DONE;
  6734.   }
  6735.   if (s.last_lit) {
  6736.     /*** FLUSH_BLOCK(s, 0); ***/
  6737.     flush_block_only(s, false);
  6738.     if (s.strm.avail_out === 0) {
  6739.       return BS_NEED_MORE;
  6740.     }
  6741.     /***/
  6742.   }
  6743.   return BS_BLOCK_DONE;
  6744. }
  6745.  
  6746. /* ===========================================================================
  6747.  * Same as above, but achieves better compression. We use a lazy
  6748.  * evaluation for matches: a match is finally adopted only if there is
  6749.  * no better match at the next window position.
  6750.  */
  6751. function deflate_slow(s, flush) {
  6752.   var hash_head;          /* head of hash chain */
  6753.   var bflush;              /* set if current block must be flushed */
  6754.  
  6755.   var max_insert;
  6756.  
  6757.   /* Process the input block. */
  6758.   for (;;) {
  6759.     /* Make sure that we always have enough lookahead, except
  6760.      * at the end of the input file. We need MAX_MATCH bytes
  6761.      * for the next match, plus MIN_MATCH bytes to insert the
  6762.      * string following the next match.
  6763.      */
  6764.     if (s.lookahead < MIN_LOOKAHEAD) {
  6765.       fill_window(s);
  6766.       if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  6767.         return BS_NEED_MORE;
  6768.       }
  6769.       if (s.lookahead === 0) { break; } /* flush the current block */
  6770.     }
  6771.  
  6772.     /* Insert the string window[strstart .. strstart+2] in the
  6773.      * dictionary, and set hash_head to the head of the hash chain:
  6774.      */
  6775.     hash_head = 0/*NIL*/;
  6776.     if (s.lookahead >= MIN_MATCH) {
  6777.       /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6778.       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6779.       hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6780.       s.head[s.ins_h] = s.strstart;
  6781.       /***/
  6782.     }
  6783.  
  6784.     /* Find the longest match, discarding those <= prev_length.
  6785.      */
  6786.     s.prev_length = s.match_length;
  6787.     s.prev_match = s.match_start;
  6788.     s.match_length = MIN_MATCH - 1;
  6789.  
  6790.     if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  6791.         s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  6792.       /* To simplify the code, we prevent matches with the string
  6793.        * of window index 0 (in particular we have to avoid a match
  6794.        * of the string with itself at the start of the input file).
  6795.        */
  6796.       s.match_length = longest_match(s, hash_head);
  6797.       /* longest_match() sets match_start */
  6798.  
  6799.       if (s.match_length <= 5 &&
  6800.          (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  6801.  
  6802.         /* If prev_match is also MIN_MATCH, match_start is garbage
  6803.          * but we will ignore the current match anyway.
  6804.          */
  6805.         s.match_length = MIN_MATCH - 1;
  6806.       }
  6807.     }
  6808.     /* If there was a match at the previous step and the current
  6809.      * match is not better, output the previous match:
  6810.      */
  6811.     if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  6812.       max_insert = s.strstart + s.lookahead - MIN_MATCH;
  6813.       /* Do not insert strings in hash table beyond this. */
  6814.  
  6815.       //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  6816.  
  6817.       /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  6818.                      s.prev_length - MIN_MATCH, bflush);***/
  6819.       bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  6820.       /* Insert in hash table all strings up to the end of the match.
  6821.        * strstart-1 and strstart are already inserted. If there is not
  6822.        * enough lookahead, the last two strings are not inserted in
  6823.        * the hash table.
  6824.        */
  6825.       s.lookahead -= s.prev_length - 1;
  6826.       s.prev_length -= 2;
  6827.       do {
  6828.         if (++s.strstart <= max_insert) {
  6829.           /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  6830.           s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  6831.           hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  6832.           s.head[s.ins_h] = s.strstart;
  6833.           /***/
  6834.         }
  6835.       } while (--s.prev_length !== 0);
  6836.       s.match_available = 0;
  6837.       s.match_length = MIN_MATCH - 1;
  6838.       s.strstart++;
  6839.  
  6840.       if (bflush) {
  6841.         /*** FLUSH_BLOCK(s, 0); ***/
  6842.         flush_block_only(s, false);
  6843.         if (s.strm.avail_out === 0) {
  6844.           return BS_NEED_MORE;
  6845.         }
  6846.         /***/
  6847.       }
  6848.  
  6849.     } else if (s.match_available) {
  6850.       /* If there was no match at the previous position, output a
  6851.        * single literal. If there was a match but the current match
  6852.        * is longer, truncate the previous match to a single literal.
  6853.        */
  6854.       //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6855.       /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6856.       bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6857.  
  6858.       if (bflush) {
  6859.         /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  6860.         flush_block_only(s, false);
  6861.         /***/
  6862.       }
  6863.       s.strstart++;
  6864.       s.lookahead--;
  6865.       if (s.strm.avail_out === 0) {
  6866.         return BS_NEED_MORE;
  6867.       }
  6868.     } else {
  6869.       /* There is no previous match to compare with, wait for
  6870.        * the next step to decide.
  6871.        */
  6872.       s.match_available = 1;
  6873.       s.strstart++;
  6874.       s.lookahead--;
  6875.     }
  6876.   }
  6877.   //Assert (flush != Z_NO_FLUSH, "no flush?");
  6878.   if (s.match_available) {
  6879.     //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  6880.     /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  6881.     bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  6882.  
  6883.     s.match_available = 0;
  6884.   }
  6885.   s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  6886.   if (flush === Z_FINISH) {
  6887.     /*** FLUSH_BLOCK(s, 1); ***/
  6888.     flush_block_only(s, true);
  6889.     if (s.strm.avail_out === 0) {
  6890.       return BS_FINISH_STARTED;
  6891.     }
  6892.     /***/
  6893.     return BS_FINISH_DONE;
  6894.   }
  6895.   if (s.last_lit) {
  6896.     /*** FLUSH_BLOCK(s, 0); ***/
  6897.     flush_block_only(s, false);
  6898.     if (s.strm.avail_out === 0) {
  6899.       return BS_NEED_MORE;
  6900.     }
  6901.     /***/
  6902.   }
  6903.  
  6904.   return BS_BLOCK_DONE;
  6905. }
  6906.  
  6907.  
  6908. /* ===========================================================================
  6909.  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  6910.  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
  6911.  * deflate switches away from Z_RLE.)
  6912.  */
  6913. function deflate_rle(s, flush) {
  6914.   var bflush;            /* set if current block must be flushed */
  6915.   var prev;              /* byte at distance one to match */
  6916.   var scan, strend;      /* scan goes up to strend for length of run */
  6917.  
  6918.   var _win = s.window;
  6919.  
  6920.   for (;;) {
  6921.     /* Make sure that we always have enough lookahead, except
  6922.      * at the end of the input file. We need MAX_MATCH bytes
  6923.      * for the longest run, plus one for the unrolled loop.
  6924.      */
  6925.     if (s.lookahead <= MAX_MATCH) {
  6926.       fill_window(s);
  6927.       if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  6928.         return BS_NEED_MORE;
  6929.       }
  6930.       if (s.lookahead === 0) { break; } /* flush the current block */
  6931.     }
  6932.  
  6933.     /* See how many times the previous byte repeats */
  6934.     s.match_length = 0;
  6935.     if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  6936.       scan = s.strstart - 1;
  6937.       prev = _win[scan];
  6938.       if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  6939.         strend = s.strstart + MAX_MATCH;
  6940.         do {
  6941.           /*jshint noempty:false*/
  6942.         } while (prev === _win[++scan] && prev === _win[++scan] &&
  6943.                  prev === _win[++scan] && prev === _win[++scan] &&
  6944.                  prev === _win[++scan] && prev === _win[++scan] &&
  6945.                  prev === _win[++scan] && prev === _win[++scan] &&
  6946.                  scan < strend);
  6947.         s.match_length = MAX_MATCH - (strend - scan);
  6948.         if (s.match_length > s.lookahead) {
  6949.           s.match_length = s.lookahead;
  6950.         }
  6951.       }
  6952.       //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  6953.     }
  6954.  
  6955.     /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  6956.     if (s.match_length >= MIN_MATCH) {
  6957.       //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  6958.  
  6959.       /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  6960.       bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  6961.  
  6962.       s.lookahead -= s.match_length;
  6963.       s.strstart += s.match_length;
  6964.       s.match_length = 0;
  6965.     } else {
  6966.       /* No match, output a literal byte */
  6967.       //Tracevv((stderr,"%c", s->window[s->strstart]));
  6968.       /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6969.       bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6970.  
  6971.       s.lookahead--;
  6972.       s.strstart++;
  6973.     }
  6974.     if (bflush) {
  6975.       /*** FLUSH_BLOCK(s, 0); ***/
  6976.       flush_block_only(s, false);
  6977.       if (s.strm.avail_out === 0) {
  6978.         return BS_NEED_MORE;
  6979.       }
  6980.       /***/
  6981.     }
  6982.   }
  6983.   s.insert = 0;
  6984.   if (flush === Z_FINISH) {
  6985.     /*** FLUSH_BLOCK(s, 1); ***/
  6986.     flush_block_only(s, true);
  6987.     if (s.strm.avail_out === 0) {
  6988.       return BS_FINISH_STARTED;
  6989.     }
  6990.     /***/
  6991.     return BS_FINISH_DONE;
  6992.   }
  6993.   if (s.last_lit) {
  6994.     /*** FLUSH_BLOCK(s, 0); ***/
  6995.     flush_block_only(s, false);
  6996.     if (s.strm.avail_out === 0) {
  6997.       return BS_NEED_MORE;
  6998.     }
  6999.     /***/
  7000.   }
  7001.   return BS_BLOCK_DONE;
  7002. }
  7003.  
  7004. /* ===========================================================================
  7005.  * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
  7006.  * (It will be regenerated if this run of deflate switches away from Huffman.)
  7007.  */
  7008. function deflate_huff(s, flush) {
  7009.   var bflush;             /* set if current block must be flushed */
  7010.  
  7011.   for (;;) {
  7012.     /* Make sure that we have a literal to write. */
  7013.     if (s.lookahead === 0) {
  7014.       fill_window(s);
  7015.       if (s.lookahead === 0) {
  7016.         if (flush === Z_NO_FLUSH) {
  7017.           return BS_NEED_MORE;
  7018.         }
  7019.         break;      /* flush the current block */
  7020.       }
  7021.     }
  7022.  
  7023.     /* Output a literal byte */
  7024.     s.match_length = 0;
  7025.     //Tracevv((stderr,"%c", s->window[s->strstart]));
  7026.     /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  7027.     bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  7028.     s.lookahead--;
  7029.     s.strstart++;
  7030.     if (bflush) {
  7031.       /*** FLUSH_BLOCK(s, 0); ***/
  7032.       flush_block_only(s, false);
  7033.       if (s.strm.avail_out === 0) {
  7034.         return BS_NEED_MORE;
  7035.       }
  7036.       /***/
  7037.     }
  7038.   }
  7039.   s.insert = 0;
  7040.   if (flush === Z_FINISH) {
  7041.     /*** FLUSH_BLOCK(s, 1); ***/
  7042.     flush_block_only(s, true);
  7043.     if (s.strm.avail_out === 0) {
  7044.       return BS_FINISH_STARTED;
  7045.     }
  7046.     /***/
  7047.     return BS_FINISH_DONE;
  7048.   }
  7049.   if (s.last_lit) {
  7050.     /*** FLUSH_BLOCK(s, 0); ***/
  7051.     flush_block_only(s, false);
  7052.     if (s.strm.avail_out === 0) {
  7053.       return BS_NEED_MORE;
  7054.     }
  7055.     /***/
  7056.   }
  7057.   return BS_BLOCK_DONE;
  7058. }
  7059.  
  7060. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  7061.  * the desired pack level (0..9). The values given below have been tuned to
  7062.  * exclude worst case performance for pathological files. Better values may be
  7063.  * found for specific files.
  7064.  */
  7065. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  7066.   this.good_length = good_length;
  7067.   this.max_lazy = max_lazy;
  7068.   this.nice_length = nice_length;
  7069.   this.max_chain = max_chain;
  7070.   this.func = func;
  7071. }
  7072.  
  7073. var configuration_table;
  7074.  
  7075. configuration_table = [
  7076.   /*      good lazy nice chain */
  7077.   new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
  7078.   new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
  7079.   new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
  7080.   new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
  7081.  
  7082.   new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
  7083.   new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
  7084.   new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
  7085.   new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
  7086.   new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
  7087.   new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
  7088. ];
  7089.  
  7090.  
  7091. /* ===========================================================================
  7092.  * Initialize the "longest match" routines for a new zlib stream
  7093.  */
  7094. function lm_init(s) {
  7095.   s.window_size = 2 * s.w_size;
  7096.  
  7097.   /*** CLEAR_HASH(s); ***/
  7098.   zero(s.head); // Fill with NIL (= 0);
  7099.  
  7100.   /* Set the default configuration parameters:
  7101.    */
  7102.   s.max_lazy_match = configuration_table[s.level].max_lazy;
  7103.   s.good_match = configuration_table[s.level].good_length;
  7104.   s.nice_match = configuration_table[s.level].nice_length;
  7105.   s.max_chain_length = configuration_table[s.level].max_chain;
  7106.  
  7107.   s.strstart = 0;
  7108.   s.block_start = 0;
  7109.   s.lookahead = 0;
  7110.   s.insert = 0;
  7111.   s.match_length = s.prev_length = MIN_MATCH - 1;
  7112.   s.match_available = 0;
  7113.   s.ins_h = 0;
  7114. }
  7115.  
  7116.  
  7117. function DeflateState() {
  7118.   this.strm = null;            /* pointer back to this zlib stream */
  7119.   this.status = 0;            /* as the name implies */
  7120.   this.pending_buf = null;      /* output still pending */
  7121.   this.pending_buf_size = 0;  /* size of pending_buf */
  7122.   this.pending_out = 0;       /* next pending byte to output to the stream */
  7123.   this.pending = 0;           /* nb of bytes in the pending buffer */
  7124.   this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
  7125.   this.gzhead = null;         /* gzip header information to write */
  7126.   this.gzindex = 0;           /* where in extra, name, or comment */
  7127.   this.method = Z_DEFLATED; /* can only be DEFLATED */
  7128.   this.last_flush = -1;   /* value of flush param for previous deflate call */
  7129.  
  7130.   this.w_size = 0;  /* LZ77 window size (32K by default) */
  7131.   this.w_bits = 0;  /* log2(w_size)  (8..16) */
  7132.   this.w_mask = 0;  /* w_size - 1 */
  7133.  
  7134.   this.window = null;
  7135.   /* Sliding window. Input bytes are read into the second half of the window,
  7136.    * and move to the first half later to keep a dictionary of at least wSize
  7137.    * bytes. With this organization, matches are limited to a distance of
  7138.    * wSize-MAX_MATCH bytes, but this ensures that IO is always
  7139.    * performed with a length multiple of the block size.
  7140.    */
  7141.  
  7142.   this.window_size = 0;
  7143.   /* Actual size of window: 2*wSize, except when the user input buffer
  7144.    * is directly used as sliding window.
  7145.    */
  7146.  
  7147.   this.prev = null;
  7148.   /* Link to older string with same hash index. To limit the size of this
  7149.    * array to 64K, this link is maintained only for the last 32K strings.
  7150.    * An index in this array is thus a window index modulo 32K.
  7151.    */
  7152.  
  7153.   this.head = null;   /* Heads of the hash chains or NIL. */
  7154.  
  7155.   this.ins_h = 0;       /* hash index of string to be inserted */
  7156.   this.hash_size = 0;   /* number of elements in hash table */
  7157.   this.hash_bits = 0;   /* log2(hash_size) */
  7158.   this.hash_mask = 0;   /* hash_size-1 */
  7159.  
  7160.   this.hash_shift = 0;
  7161.   /* Number of bits by which ins_h must be shifted at each input
  7162.    * step. It must be such that after MIN_MATCH steps, the oldest
  7163.    * byte no longer takes part in the hash key, that is:
  7164.    *   hash_shift * MIN_MATCH >= hash_bits
  7165.    */
  7166.  
  7167.   this.block_start = 0;
  7168.   /* Window position at the beginning of the current output block. Gets
  7169.    * negative when the window is moved backwards.
  7170.    */
  7171.  
  7172.   this.match_length = 0;      /* length of best match */
  7173.   this.prev_match = 0;        /* previous match */
  7174.   this.match_available = 0;   /* set if previous match exists */
  7175.   this.strstart = 0;          /* start of string to insert */
  7176.   this.match_start = 0;       /* start of matching string */
  7177.   this.lookahead = 0;         /* number of valid bytes ahead in window */
  7178.  
  7179.   this.prev_length = 0;
  7180.   /* Length of the best match at previous step. Matches not greater than this
  7181.    * are discarded. This is used in the lazy match evaluation.
  7182.    */
  7183.  
  7184.   this.max_chain_length = 0;
  7185.   /* To speed up deflation, hash chains are never searched beyond this
  7186.    * length.  A higher limit improves compression ratio but degrades the
  7187.    * speed.
  7188.    */
  7189.  
  7190.   this.max_lazy_match = 0;
  7191.   /* Attempt to find a better match only when the current match is strictly
  7192.    * smaller than this value. This mechanism is used only for compression
  7193.    * levels >= 4.
  7194.    */
  7195.   // That's alias to max_lazy_match, don't use directly
  7196.   //this.max_insert_length = 0;
  7197.   /* Insert new strings in the hash table only if the match length is not
  7198.    * greater than this length. This saves time but degrades compression.
  7199.    * max_insert_length is used only for compression levels <= 3.
  7200.    */
  7201.  
  7202.   this.level = 0;     /* compression level (1..9) */
  7203.   this.strategy = 0;  /* favor or force Huffman coding*/
  7204.  
  7205.   this.good_match = 0;
  7206.   /* Use a faster search when the previous match is longer than this */
  7207.  
  7208.   this.nice_match = 0; /* Stop searching when current match exceeds this */
  7209.  
  7210.               /* used by trees.c: */
  7211.  
  7212.   /* Didn't use ct_data typedef below to suppress compiler warning */
  7213.  
  7214.   // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
  7215.   // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  7216.   // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
  7217.  
  7218.   // Use flat array of DOUBLE size, with interleaved fata,
  7219.   // because JS does not support effective
  7220.   this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
  7221.   this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
  7222.   this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
  7223.   zero(this.dyn_ltree);
  7224.   zero(this.dyn_dtree);
  7225.   zero(this.bl_tree);
  7226.  
  7227.   this.l_desc   = null;         /* desc. for literal tree */
  7228.   this.d_desc   = null;         /* desc. for distance tree */
  7229.   this.bl_desc  = null;         /* desc. for bit length tree */
  7230.  
  7231.   //ush bl_count[MAX_BITS+1];
  7232.   this.bl_count = new utils.Buf16(MAX_BITS + 1);
  7233.   /* number of codes at each bit length for an optimal tree */
  7234.  
  7235.   //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
  7236.   this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
  7237.   zero(this.heap);
  7238.  
  7239.   this.heap_len = 0;               /* number of elements in the heap */
  7240.   this.heap_max = 0;               /* element of largest frequency */
  7241.   /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  7242.    * The same heap array is used to build all trees.
  7243.    */
  7244.  
  7245.   this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  7246.   zero(this.depth);
  7247.   /* Depth of each subtree used as tie breaker for trees of equal frequency
  7248.    */
  7249.  
  7250.   this.l_buf = 0;          /* buffer index for literals or lengths */
  7251.  
  7252.   this.lit_bufsize = 0;
  7253.   /* Size of match buffer for literals/lengths.  There are 4 reasons for
  7254.    * limiting lit_bufsize to 64K:
  7255.    *   - frequencies can be kept in 16 bit counters
  7256.    *   - if compression is not successful for the first block, all input
  7257.    *     data is still in the window so we can still emit a stored block even
  7258.    *     when input comes from standard input.  (This can also be done for
  7259.    *     all blocks if lit_bufsize is not greater than 32K.)
  7260.    *   - if compression is not successful for a file smaller than 64K, we can
  7261.    *     even emit a stored file instead of a stored block (saving 5 bytes).
  7262.    *     This is applicable only for zip (not gzip or zlib).
  7263.    *   - creating new Huffman trees less frequently may not provide fast
  7264.    *     adaptation to changes in the input data statistics. (Take for
  7265.    *     example a binary file with poorly compressible code followed by
  7266.    *     a highly compressible string table.) Smaller buffer sizes give
  7267.    *     fast adaptation but have of course the overhead of transmitting
  7268.    *     trees more frequently.
  7269.    *   - I can't count above 4
  7270.    */
  7271.  
  7272.   this.last_lit = 0;      /* running index in l_buf */
  7273.  
  7274.   this.d_buf = 0;
  7275.   /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  7276.    * the same number of elements. To use different lengths, an extra flag
  7277.    * array would be necessary.
  7278.    */
  7279.  
  7280.   this.opt_len = 0;       /* bit length of current block with optimal trees */
  7281.   this.static_len = 0;    /* bit length of current block with static trees */
  7282.   this.matches = 0;       /* number of string matches in current block */
  7283.   this.insert = 0;        /* bytes at end of window left to insert */
  7284.  
  7285.  
  7286.   this.bi_buf = 0;
  7287.   /* Output buffer. bits are inserted starting at the bottom (least
  7288.    * significant bits).
  7289.    */
  7290.   this.bi_valid = 0;
  7291.   /* Number of valid bits in bi_buf.  All bits above the last valid bit
  7292.    * are always zero.
  7293.    */
  7294.  
  7295.   // Used for window memory init. We safely ignore it for JS. That makes
  7296.   // sense only for pointers and memory check tools.
  7297.   //this.high_water = 0;
  7298.   /* High water mark offset in window for initialized bytes -- bytes above
  7299.    * this are set to zero in order to avoid memory check warnings when
  7300.    * longest match routines access bytes past the input.  This is then
  7301.    * updated to the new high water mark.
  7302.    */
  7303. }
  7304.  
  7305.  
  7306. function deflateResetKeep(strm) {
  7307.   var s;
  7308.  
  7309.   if (!strm || !strm.state) {
  7310.     return err(strm, Z_STREAM_ERROR);
  7311.   }
  7312.  
  7313.   strm.total_in = strm.total_out = 0;
  7314.   strm.data_type = Z_UNKNOWN;
  7315.  
  7316.   s = strm.state;
  7317.   s.pending = 0;
  7318.   s.pending_out = 0;
  7319.  
  7320.   if (s.wrap < 0) {
  7321.     s.wrap = -s.wrap;
  7322.     /* was made negative by deflate(..., Z_FINISH); */
  7323.   }
  7324.   s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  7325.   strm.adler = (s.wrap === 2) ?
  7326.     0  // crc32(0, Z_NULL, 0)
  7327.   :
  7328.     1; // adler32(0, Z_NULL, 0)
  7329.   s.last_flush = Z_NO_FLUSH;
  7330.   trees._tr_init(s);
  7331.   return Z_OK;
  7332. }
  7333.  
  7334.  
  7335. function deflateReset(strm) {
  7336.   var ret = deflateResetKeep(strm);
  7337.   if (ret === Z_OK) {
  7338.     lm_init(strm.state);
  7339.   }
  7340.   return ret;
  7341. }
  7342.  
  7343.  
  7344. function deflateSetHeader(strm, head) {
  7345.   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7346.   if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  7347.   strm.state.gzhead = head;
  7348.   return Z_OK;
  7349. }
  7350.  
  7351.  
  7352. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  7353.   if (!strm) { // === Z_NULL
  7354.     return Z_STREAM_ERROR;
  7355.   }
  7356.   var wrap = 1;
  7357.  
  7358.   if (level === Z_DEFAULT_COMPRESSION) {
  7359.     level = 6;
  7360.   }
  7361.  
  7362.   if (windowBits < 0) { /* suppress zlib wrapper */
  7363.     wrap = 0;
  7364.     windowBits = -windowBits;
  7365.   }
  7366.  
  7367.   else if (windowBits > 15) {
  7368.     wrap = 2;           /* write gzip wrapper instead */
  7369.     windowBits -= 16;
  7370.   }
  7371.  
  7372.  
  7373.   if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  7374.     windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  7375.     strategy < 0 || strategy > Z_FIXED) {
  7376.     return err(strm, Z_STREAM_ERROR);
  7377.   }
  7378.  
  7379.  
  7380.   if (windowBits === 8) {
  7381.     windowBits = 9;
  7382.   }
  7383.   /* until 256-byte window bug fixed */
  7384.  
  7385.   var s = new DeflateState();
  7386.  
  7387.   strm.state = s;
  7388.   s.strm = strm;
  7389.  
  7390.   s.wrap = wrap;
  7391.   s.gzhead = null;
  7392.   s.w_bits = windowBits;
  7393.   s.w_size = 1 << s.w_bits;
  7394.   s.w_mask = s.w_size - 1;
  7395.  
  7396.   s.hash_bits = memLevel + 7;
  7397.   s.hash_size = 1 << s.hash_bits;
  7398.   s.hash_mask = s.hash_size - 1;
  7399.   s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  7400.  
  7401.   s.window = new utils.Buf8(s.w_size * 2);
  7402.   s.head = new utils.Buf16(s.hash_size);
  7403.   s.prev = new utils.Buf16(s.w_size);
  7404.  
  7405.   // Don't need mem init magic for JS.
  7406.   //s.high_water = 0;  /* nothing written to s->window yet */
  7407.  
  7408.   s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  7409.  
  7410.   s.pending_buf_size = s.lit_bufsize * 4;
  7411.  
  7412.   //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  7413.   //s->pending_buf = (uchf *) overlay;
  7414.   s.pending_buf = new utils.Buf8(s.pending_buf_size);
  7415.  
  7416.   // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  7417.   //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  7418.   s.d_buf = 1 * s.lit_bufsize;
  7419.  
  7420.   //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  7421.   s.l_buf = (1 + 2) * s.lit_bufsize;
  7422.  
  7423.   s.level = level;
  7424.   s.strategy = strategy;
  7425.   s.method = method;
  7426.  
  7427.   return deflateReset(strm);
  7428. }
  7429.  
  7430. function deflateInit(strm, level) {
  7431.   return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  7432. }
  7433.  
  7434.  
  7435. function deflate(strm, flush) {
  7436.   var old_flush, s;
  7437.   var beg, val; // for gzip header write only
  7438.  
  7439.   if (!strm || !strm.state ||
  7440.     flush > Z_BLOCK || flush < 0) {
  7441.     return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  7442.   }
  7443.  
  7444.   s = strm.state;
  7445.  
  7446.   if (!strm.output ||
  7447.       (!strm.input && strm.avail_in !== 0) ||
  7448.       (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  7449.     return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  7450.   }
  7451.  
  7452.   s.strm = strm; /* just in case */
  7453.   old_flush = s.last_flush;
  7454.   s.last_flush = flush;
  7455.  
  7456.   /* Write the header */
  7457.   if (s.status === INIT_STATE) {
  7458.  
  7459.     if (s.wrap === 2) { // GZIP header
  7460.       strm.adler = 0;  //crc32(0L, Z_NULL, 0);
  7461.       put_byte(s, 31);
  7462.       put_byte(s, 139);
  7463.       put_byte(s, 8);
  7464.       if (!s.gzhead) { // s->gzhead == Z_NULL
  7465.         put_byte(s, 0);
  7466.         put_byte(s, 0);
  7467.         put_byte(s, 0);
  7468.         put_byte(s, 0);
  7469.         put_byte(s, 0);
  7470.         put_byte(s, s.level === 9 ? 2 :
  7471.                     (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7472.                      4 : 0));
  7473.         put_byte(s, OS_CODE);
  7474.         s.status = BUSY_STATE;
  7475.       }
  7476.       else {
  7477.         put_byte(s, (s.gzhead.text ? 1 : 0) +
  7478.                     (s.gzhead.hcrc ? 2 : 0) +
  7479.                     (!s.gzhead.extra ? 0 : 4) +
  7480.                     (!s.gzhead.name ? 0 : 8) +
  7481.                     (!s.gzhead.comment ? 0 : 16)
  7482.                 );
  7483.         put_byte(s, s.gzhead.time & 0xff);
  7484.         put_byte(s, (s.gzhead.time >> 8) & 0xff);
  7485.         put_byte(s, (s.gzhead.time >> 16) & 0xff);
  7486.         put_byte(s, (s.gzhead.time >> 24) & 0xff);
  7487.         put_byte(s, s.level === 9 ? 2 :
  7488.                     (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  7489.                      4 : 0));
  7490.         put_byte(s, s.gzhead.os & 0xff);
  7491.         if (s.gzhead.extra && s.gzhead.extra.length) {
  7492.           put_byte(s, s.gzhead.extra.length & 0xff);
  7493.           put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  7494.         }
  7495.         if (s.gzhead.hcrc) {
  7496.           strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  7497.         }
  7498.         s.gzindex = 0;
  7499.         s.status = EXTRA_STATE;
  7500.       }
  7501.     }
  7502.     else // DEFLATE header
  7503.     {
  7504.       var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  7505.       var level_flags = -1;
  7506.  
  7507.       if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  7508.         level_flags = 0;
  7509.       } else if (s.level < 6) {
  7510.         level_flags = 1;
  7511.       } else if (s.level === 6) {
  7512.         level_flags = 2;
  7513.       } else {
  7514.         level_flags = 3;
  7515.       }
  7516.       header |= (level_flags << 6);
  7517.       if (s.strstart !== 0) { header |= PRESET_DICT; }
  7518.       header += 31 - (header % 31);
  7519.  
  7520.       s.status = BUSY_STATE;
  7521.       putShortMSB(s, header);
  7522.  
  7523.       /* Save the adler32 of the preset dictionary: */
  7524.       if (s.strstart !== 0) {
  7525.         putShortMSB(s, strm.adler >>> 16);
  7526.         putShortMSB(s, strm.adler & 0xffff);
  7527.       }
  7528.       strm.adler = 1; // adler32(0L, Z_NULL, 0);
  7529.     }
  7530.   }
  7531.  
  7532. //#ifdef GZIP
  7533.   if (s.status === EXTRA_STATE) {
  7534.     if (s.gzhead.extra/* != Z_NULL*/) {
  7535.       beg = s.pending;  /* start of bytes to update crc */
  7536.  
  7537.       while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  7538.         if (s.pending === s.pending_buf_size) {
  7539.           if (s.gzhead.hcrc && s.pending > beg) {
  7540.             strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7541.           }
  7542.           flush_pending(strm);
  7543.           beg = s.pending;
  7544.           if (s.pending === s.pending_buf_size) {
  7545.             break;
  7546.           }
  7547.         }
  7548.         put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  7549.         s.gzindex++;
  7550.       }
  7551.       if (s.gzhead.hcrc && s.pending > beg) {
  7552.         strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7553.       }
  7554.       if (s.gzindex === s.gzhead.extra.length) {
  7555.         s.gzindex = 0;
  7556.         s.status = NAME_STATE;
  7557.       }
  7558.     }
  7559.     else {
  7560.       s.status = NAME_STATE;
  7561.     }
  7562.   }
  7563.   if (s.status === NAME_STATE) {
  7564.     if (s.gzhead.name/* != Z_NULL*/) {
  7565.       beg = s.pending;  /* start of bytes to update crc */
  7566.       //int val;
  7567.  
  7568.       do {
  7569.         if (s.pending === s.pending_buf_size) {
  7570.           if (s.gzhead.hcrc && s.pending > beg) {
  7571.             strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7572.           }
  7573.           flush_pending(strm);
  7574.           beg = s.pending;
  7575.           if (s.pending === s.pending_buf_size) {
  7576.             val = 1;
  7577.             break;
  7578.           }
  7579.         }
  7580.         // JS specific: little magic to add zero terminator to end of string
  7581.         if (s.gzindex < s.gzhead.name.length) {
  7582.           val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  7583.         } else {
  7584.           val = 0;
  7585.         }
  7586.         put_byte(s, val);
  7587.       } while (val !== 0);
  7588.  
  7589.       if (s.gzhead.hcrc && s.pending > beg) {
  7590.         strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7591.       }
  7592.       if (val === 0) {
  7593.         s.gzindex = 0;
  7594.         s.status = COMMENT_STATE;
  7595.       }
  7596.     }
  7597.     else {
  7598.       s.status = COMMENT_STATE;
  7599.     }
  7600.   }
  7601.   if (s.status === COMMENT_STATE) {
  7602.     if (s.gzhead.comment/* != Z_NULL*/) {
  7603.       beg = s.pending;  /* start of bytes to update crc */
  7604.       //int val;
  7605.  
  7606.       do {
  7607.         if (s.pending === s.pending_buf_size) {
  7608.           if (s.gzhead.hcrc && s.pending > beg) {
  7609.             strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7610.           }
  7611.           flush_pending(strm);
  7612.           beg = s.pending;
  7613.           if (s.pending === s.pending_buf_size) {
  7614.             val = 1;
  7615.             break;
  7616.           }
  7617.         }
  7618.         // JS specific: little magic to add zero terminator to end of string
  7619.         if (s.gzindex < s.gzhead.comment.length) {
  7620.           val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  7621.         } else {
  7622.           val = 0;
  7623.         }
  7624.         put_byte(s, val);
  7625.       } while (val !== 0);
  7626.  
  7627.       if (s.gzhead.hcrc && s.pending > beg) {
  7628.         strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  7629.       }
  7630.       if (val === 0) {
  7631.         s.status = HCRC_STATE;
  7632.       }
  7633.     }
  7634.     else {
  7635.       s.status = HCRC_STATE;
  7636.     }
  7637.   }
  7638.   if (s.status === HCRC_STATE) {
  7639.     if (s.gzhead.hcrc) {
  7640.       if (s.pending + 2 > s.pending_buf_size) {
  7641.         flush_pending(strm);
  7642.       }
  7643.       if (s.pending + 2 <= s.pending_buf_size) {
  7644.         put_byte(s, strm.adler & 0xff);
  7645.         put_byte(s, (strm.adler >> 8) & 0xff);
  7646.         strm.adler = 0; //crc32(0L, Z_NULL, 0);
  7647.         s.status = BUSY_STATE;
  7648.       }
  7649.     }
  7650.     else {
  7651.       s.status = BUSY_STATE;
  7652.     }
  7653.   }
  7654. //#endif
  7655.  
  7656.   /* Flush as much pending output as possible */
  7657.   if (s.pending !== 0) {
  7658.     flush_pending(strm);
  7659.     if (strm.avail_out === 0) {
  7660.       /* Since avail_out is 0, deflate will be called again with
  7661.        * more output space, but possibly with both pending and
  7662.        * avail_in equal to zero. There won't be anything to do,
  7663.        * but this is not an error situation so make sure we
  7664.        * return OK instead of BUF_ERROR at next call of deflate:
  7665.        */
  7666.       s.last_flush = -1;
  7667.       return Z_OK;
  7668.     }
  7669.  
  7670.     /* Make sure there is something to do and avoid duplicate consecutive
  7671.      * flushes. For repeated and useless calls with Z_FINISH, we keep
  7672.      * returning Z_STREAM_END instead of Z_BUF_ERROR.
  7673.      */
  7674.   } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  7675.     flush !== Z_FINISH) {
  7676.     return err(strm, Z_BUF_ERROR);
  7677.   }
  7678.  
  7679.   /* User must not provide more input after the first FINISH: */
  7680.   if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  7681.     return err(strm, Z_BUF_ERROR);
  7682.   }
  7683.  
  7684.   /* Start a new block or continue the current one.
  7685.    */
  7686.   if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  7687.     (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  7688.     var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  7689.       (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  7690.         configuration_table[s.level].func(s, flush));
  7691.  
  7692.     if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  7693.       s.status = FINISH_STATE;
  7694.     }
  7695.     if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  7696.       if (strm.avail_out === 0) {
  7697.         s.last_flush = -1;
  7698.         /* avoid BUF_ERROR next call, see above */
  7699.       }
  7700.       return Z_OK;
  7701.       /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  7702.        * of deflate should use the same flush parameter to make sure
  7703.        * that the flush is complete. So we don't have to output an
  7704.        * empty block here, this will be done at next call. This also
  7705.        * ensures that for a very small output buffer, we emit at most
  7706.        * one empty block.
  7707.        */
  7708.     }
  7709.     if (bstate === BS_BLOCK_DONE) {
  7710.       if (flush === Z_PARTIAL_FLUSH) {
  7711.         trees._tr_align(s);
  7712.       }
  7713.       else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  7714.  
  7715.         trees._tr_stored_block(s, 0, 0, false);
  7716.         /* For a full flush, this empty block will be recognized
  7717.          * as a special marker by inflate_sync().
  7718.          */
  7719.         if (flush === Z_FULL_FLUSH) {
  7720.           /*** CLEAR_HASH(s); ***/             /* forget history */
  7721.           zero(s.head); // Fill with NIL (= 0);
  7722.  
  7723.           if (s.lookahead === 0) {
  7724.             s.strstart = 0;
  7725.             s.block_start = 0;
  7726.             s.insert = 0;
  7727.           }
  7728.         }
  7729.       }
  7730.       flush_pending(strm);
  7731.       if (strm.avail_out === 0) {
  7732.         s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  7733.         return Z_OK;
  7734.       }
  7735.     }
  7736.   }
  7737.   //Assert(strm->avail_out > 0, "bug2");
  7738.   //if (strm.avail_out <= 0) { throw new Error("bug2");}
  7739.  
  7740.   if (flush !== Z_FINISH) { return Z_OK; }
  7741.   if (s.wrap <= 0) { return Z_STREAM_END; }
  7742.  
  7743.   /* Write the trailer */
  7744.   if (s.wrap === 2) {
  7745.     put_byte(s, strm.adler & 0xff);
  7746.     put_byte(s, (strm.adler >> 8) & 0xff);
  7747.     put_byte(s, (strm.adler >> 16) & 0xff);
  7748.     put_byte(s, (strm.adler >> 24) & 0xff);
  7749.     put_byte(s, strm.total_in & 0xff);
  7750.     put_byte(s, (strm.total_in >> 8) & 0xff);
  7751.     put_byte(s, (strm.total_in >> 16) & 0xff);
  7752.     put_byte(s, (strm.total_in >> 24) & 0xff);
  7753.   }
  7754.   else
  7755.   {
  7756.     putShortMSB(s, strm.adler >>> 16);
  7757.     putShortMSB(s, strm.adler & 0xffff);
  7758.   }
  7759.  
  7760.   flush_pending(strm);
  7761.   /* If avail_out is zero, the application will call deflate again
  7762.    * to flush the rest.
  7763.    */
  7764.   if (s.wrap > 0) { s.wrap = -s.wrap; }
  7765.   /* write the trailer only once! */
  7766.   return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  7767. }
  7768.  
  7769. function deflateEnd(strm) {
  7770.   var status;
  7771.  
  7772.   if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7773.     return Z_STREAM_ERROR;
  7774.   }
  7775.  
  7776.   status = strm.state.status;
  7777.   if (status !== INIT_STATE &&
  7778.     status !== EXTRA_STATE &&
  7779.     status !== NAME_STATE &&
  7780.     status !== COMMENT_STATE &&
  7781.     status !== HCRC_STATE &&
  7782.     status !== BUSY_STATE &&
  7783.     status !== FINISH_STATE
  7784.   ) {
  7785.     return err(strm, Z_STREAM_ERROR);
  7786.   }
  7787.  
  7788.   strm.state = null;
  7789.  
  7790.   return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  7791. }
  7792.  
  7793.  
  7794. /* =========================================================================
  7795.  * Initializes the compression dictionary from the given byte
  7796.  * sequence without producing any compressed output.
  7797.  */
  7798. function deflateSetDictionary(strm, dictionary) {
  7799.   var dictLength = dictionary.length;
  7800.  
  7801.   var s;
  7802.   var str, n;
  7803.   var wrap;
  7804.   var avail;
  7805.   var next;
  7806.   var input;
  7807.   var tmpDict;
  7808.  
  7809.   if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  7810.     return Z_STREAM_ERROR;
  7811.   }
  7812.  
  7813.   s = strm.state;
  7814.   wrap = s.wrap;
  7815.  
  7816.   if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  7817.     return Z_STREAM_ERROR;
  7818.   }
  7819.  
  7820.   /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  7821.   if (wrap === 1) {
  7822.     /* adler32(strm->adler, dictionary, dictLength); */
  7823.     strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  7824.   }
  7825.  
  7826.   s.wrap = 0;   /* avoid computing Adler-32 in read_buf */
  7827.  
  7828.   /* if dictionary would fill window, just replace the history */
  7829.   if (dictLength >= s.w_size) {
  7830.     if (wrap === 0) {            /* already empty otherwise */
  7831.       /*** CLEAR_HASH(s); ***/
  7832.       zero(s.head); // Fill with NIL (= 0);
  7833.       s.strstart = 0;
  7834.       s.block_start = 0;
  7835.       s.insert = 0;
  7836.     }
  7837.     /* use the tail */
  7838.     // dictionary = dictionary.slice(dictLength - s.w_size);
  7839.     tmpDict = new utils.Buf8(s.w_size);
  7840.     utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  7841.     dictionary = tmpDict;
  7842.     dictLength = s.w_size;
  7843.   }
  7844.   /* insert dictionary into window and hash */
  7845.   avail = strm.avail_in;
  7846.   next = strm.next_in;
  7847.   input = strm.input;
  7848.   strm.avail_in = dictLength;
  7849.   strm.next_in = 0;
  7850.   strm.input = dictionary;
  7851.   fill_window(s);
  7852.   while (s.lookahead >= MIN_MATCH) {
  7853.     str = s.strstart;
  7854.     n = s.lookahead - (MIN_MATCH - 1);
  7855.     do {
  7856.       /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  7857.       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  7858.  
  7859.       s.prev[str & s.w_mask] = s.head[s.ins_h];
  7860.  
  7861.       s.head[s.ins_h] = str;
  7862.       str++;
  7863.     } while (--n);
  7864.     s.strstart = str;
  7865.     s.lookahead = MIN_MATCH - 1;
  7866.     fill_window(s);
  7867.   }
  7868.   s.strstart += s.lookahead;
  7869.   s.block_start = s.strstart;
  7870.   s.insert = s.lookahead;
  7871.   s.lookahead = 0;
  7872.   s.match_length = s.prev_length = MIN_MATCH - 1;
  7873.   s.match_available = 0;
  7874.   strm.next_in = next;
  7875.   strm.input = input;
  7876.   strm.avail_in = avail;
  7877.   s.wrap = wrap;
  7878.   return Z_OK;
  7879. }
  7880.  
  7881.  
  7882. exports.deflateInit = deflateInit;
  7883. exports.deflateInit2 = deflateInit2;
  7884. exports.deflateReset = deflateReset;
  7885. exports.deflateResetKeep = deflateResetKeep;
  7886. exports.deflateSetHeader = deflateSetHeader;
  7887. exports.deflate = deflate;
  7888. exports.deflateEnd = deflateEnd;
  7889. exports.deflateSetDictionary = deflateSetDictionary;
  7890. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  7891.  
  7892. /* Not implemented
  7893. exports.deflateBound = deflateBound;
  7894. exports.deflateCopy = deflateCopy;
  7895. exports.deflateParams = deflateParams;
  7896. exports.deflatePending = deflatePending;
  7897. exports.deflatePrime = deflatePrime;
  7898. exports.deflateTune = deflateTune;
  7899. */
  7900.  
  7901. },{"../utils/common":62,"./adler32":64,"./crc32":66,"./messages":72,"./trees":73}],68:[function(require,module,exports){
  7902. 'use strict';
  7903.  
  7904.  
  7905. function GZheader() {
  7906.   /* true if compressed data believed to be text */
  7907.   this.text       = 0;
  7908.   /* modification time */
  7909.   this.time       = 0;
  7910.   /* extra flags (not used when writing a gzip file) */
  7911.   this.xflags     = 0;
  7912.   /* operating system */
  7913.   this.os         = 0;
  7914.   /* pointer to extra field or Z_NULL if none */
  7915.   this.extra      = null;
  7916.   /* extra field length (valid if extra != Z_NULL) */
  7917.   this.extra_len  = 0; // Actually, we don't need it in JS,
  7918.                        // but leave for few code modifications
  7919.  
  7920.   //
  7921.   // Setup limits is not necessary because in js we should not preallocate memory
  7922.   // for inflate use constant limit in 65536 bytes
  7923.   //
  7924.  
  7925.   /* space at extra (only when reading header) */
  7926.   // this.extra_max  = 0;
  7927.   /* pointer to zero-terminated file name or Z_NULL */
  7928.   this.name       = '';
  7929.   /* space at name (only when reading header) */
  7930.   // this.name_max   = 0;
  7931.   /* pointer to zero-terminated comment or Z_NULL */
  7932.   this.comment    = '';
  7933.   /* space at comment (only when reading header) */
  7934.   // this.comm_max   = 0;
  7935.   /* true if there was or will be a header crc */
  7936.   this.hcrc       = 0;
  7937.   /* true when done reading gzip header (not used when writing a gzip file) */
  7938.   this.done       = false;
  7939. }
  7940.  
  7941. module.exports = GZheader;
  7942.  
  7943. },{}],69:[function(require,module,exports){
  7944. 'use strict';
  7945.  
  7946. // See state defs from inflate.js
  7947. var BAD = 30;       /* got a data error -- remain here until reset */
  7948. var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
  7949.  
  7950. /*
  7951.    Decode literal, length, and distance codes and write out the resulting
  7952.    literal and match bytes until either not enough input or output is
  7953.    available, an end-of-block is encountered, or a data error is encountered.
  7954.    When large enough input and output buffers are supplied to inflate(), for
  7955.    example, a 16K input buffer and a 64K output buffer, more than 95% of the
  7956.    inflate execution time is spent in this routine.
  7957.  
  7958.    Entry assumptions:
  7959.  
  7960.         state.mode === LEN
  7961.         strm.avail_in >= 6
  7962.         strm.avail_out >= 258
  7963.         start >= strm.avail_out
  7964.         state.bits < 8
  7965.  
  7966.    On return, state.mode is one of:
  7967.  
  7968.         LEN -- ran out of enough output space or enough available input
  7969.         TYPE -- reached end of block code, inflate() to interpret next block
  7970.         BAD -- error in block data
  7971.  
  7972.    Notes:
  7973.  
  7974.     - The maximum input bits used by a length/distance pair is 15 bits for the
  7975.       length code, 5 bits for the length extra, 15 bits for the distance code,
  7976.       and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
  7977.       Therefore if strm.avail_in >= 6, then there is enough input to avoid
  7978.       checking for available input while decoding.
  7979.  
  7980.     - The maximum bytes that a single length/distance pair can output is 258
  7981.       bytes, which is the maximum length that can be coded.  inflate_fast()
  7982.       requires strm.avail_out >= 258 for each loop to avoid checking for
  7983.       output space.
  7984.  */
  7985. module.exports = function inflate_fast(strm, start) {
  7986.   var state;
  7987.   var _in;                    /* local strm.input */
  7988.   var last;                   /* have enough input while in < last */
  7989.   var _out;                   /* local strm.output */
  7990.   var beg;                    /* inflate()'s initial strm.output */
  7991.   var end;                    /* while out < end, enough space available */
  7992. //#ifdef INFLATE_STRICT
  7993.   var dmax;                   /* maximum distance from zlib header */
  7994. //#endif
  7995.   var wsize;                  /* window size or zero if not using window */
  7996.   var whave;                  /* valid bytes in the window */
  7997.   var wnext;                  /* window write index */
  7998.   // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  7999.   var s_window;               /* allocated sliding window, if wsize != 0 */
  8000.   var hold;                   /* local strm.hold */
  8001.   var bits;                   /* local strm.bits */
  8002.   var lcode;                  /* local strm.lencode */
  8003.   var dcode;                  /* local strm.distcode */
  8004.   var lmask;                  /* mask for first level of length codes */
  8005.   var dmask;                  /* mask for first level of distance codes */
  8006.   var here;                   /* retrieved table entry */
  8007.   var op;                     /* code bits, operation, extra bits, or */
  8008.                               /*  window position, window bytes to copy */
  8009.   var len;                    /* match length, unused bytes */
  8010.   var dist;                   /* match distance */
  8011.   var from;                   /* where to copy match from */
  8012.   var from_source;
  8013.  
  8014.  
  8015.   var input, output; // JS specific, because we have no pointers
  8016.  
  8017.   /* copy state to local variables */
  8018.   state = strm.state;
  8019.   //here = state.here;
  8020.   _in = strm.next_in;
  8021.   input = strm.input;
  8022.   last = _in + (strm.avail_in - 5);
  8023.   _out = strm.next_out;
  8024.   output = strm.output;
  8025.   beg = _out - (start - strm.avail_out);
  8026.   end = _out + (strm.avail_out - 257);
  8027. //#ifdef INFLATE_STRICT
  8028.   dmax = state.dmax;
  8029. //#endif
  8030.   wsize = state.wsize;
  8031.   whave = state.whave;
  8032.   wnext = state.wnext;
  8033.   s_window = state.window;
  8034.   hold = state.hold;
  8035.   bits = state.bits;
  8036.   lcode = state.lencode;
  8037.   dcode = state.distcode;
  8038.   lmask = (1 << state.lenbits) - 1;
  8039.   dmask = (1 << state.distbits) - 1;
  8040.  
  8041.  
  8042.   /* decode literals and length/distances until end-of-block or not enough
  8043.      input data or output space */
  8044.  
  8045.   top:
  8046.   do {
  8047.     if (bits < 15) {
  8048.       hold += input[_in++] << bits;
  8049.       bits += 8;
  8050.       hold += input[_in++] << bits;
  8051.       bits += 8;
  8052.     }
  8053.  
  8054.     here = lcode[hold & lmask];
  8055.  
  8056.     dolen:
  8057.     for (;;) { // Goto emulation
  8058.       op = here >>> 24/*here.bits*/;
  8059.       hold >>>= op;
  8060.       bits -= op;
  8061.       op = (here >>> 16) & 0xff/*here.op*/;
  8062.       if (op === 0) {                          /* literal */
  8063.         //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8064.         //        "inflate:         literal '%c'\n" :
  8065.         //        "inflate:         literal 0x%02x\n", here.val));
  8066.         output[_out++] = here & 0xffff/*here.val*/;
  8067.       }
  8068.       else if (op & 16) {                     /* length base */
  8069.         len = here & 0xffff/*here.val*/;
  8070.         op &= 15;                           /* number of extra bits */
  8071.         if (op) {
  8072.           if (bits < op) {
  8073.             hold += input[_in++] << bits;
  8074.             bits += 8;
  8075.           }
  8076.           len += hold & ((1 << op) - 1);
  8077.           hold >>>= op;
  8078.           bits -= op;
  8079.         }
  8080.         //Tracevv((stderr, "inflate:         length %u\n", len));
  8081.         if (bits < 15) {
  8082.           hold += input[_in++] << bits;
  8083.           bits += 8;
  8084.           hold += input[_in++] << bits;
  8085.           bits += 8;
  8086.         }
  8087.         here = dcode[hold & dmask];
  8088.  
  8089.         dodist:
  8090.         for (;;) { // goto emulation
  8091.           op = here >>> 24/*here.bits*/;
  8092.           hold >>>= op;
  8093.           bits -= op;
  8094.           op = (here >>> 16) & 0xff/*here.op*/;
  8095.  
  8096.           if (op & 16) {                      /* distance base */
  8097.             dist = here & 0xffff/*here.val*/;
  8098.             op &= 15;                       /* number of extra bits */
  8099.             if (bits < op) {
  8100.               hold += input[_in++] << bits;
  8101.               bits += 8;
  8102.               if (bits < op) {
  8103.                 hold += input[_in++] << bits;
  8104.                 bits += 8;
  8105.               }
  8106.             }
  8107.             dist += hold & ((1 << op) - 1);
  8108. //#ifdef INFLATE_STRICT
  8109.             if (dist > dmax) {
  8110.               strm.msg = 'invalid distance too far back';
  8111.               state.mode = BAD;
  8112.               break top;
  8113.             }
  8114. //#endif
  8115.             hold >>>= op;
  8116.             bits -= op;
  8117.             //Tracevv((stderr, "inflate:         distance %u\n", dist));
  8118.             op = _out - beg;                /* max distance in output */
  8119.             if (dist > op) {                /* see if copy from window */
  8120.               op = dist - op;               /* distance back in window */
  8121.               if (op > whave) {
  8122.                 if (state.sane) {
  8123.                   strm.msg = 'invalid distance too far back';
  8124.                   state.mode = BAD;
  8125.                   break top;
  8126.                 }
  8127.  
  8128. // (!) This block is disabled in zlib defailts,
  8129. // don't enable it for binary compatibility
  8130. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8131. //                if (len <= op - whave) {
  8132. //                  do {
  8133. //                    output[_out++] = 0;
  8134. //                  } while (--len);
  8135. //                  continue top;
  8136. //                }
  8137. //                len -= op - whave;
  8138. //                do {
  8139. //                  output[_out++] = 0;
  8140. //                } while (--op > whave);
  8141. //                if (op === 0) {
  8142. //                  from = _out - dist;
  8143. //                  do {
  8144. //                    output[_out++] = output[from++];
  8145. //                  } while (--len);
  8146. //                  continue top;
  8147. //                }
  8148. //#endif
  8149.               }
  8150.               from = 0; // window index
  8151.               from_source = s_window;
  8152.               if (wnext === 0) {           /* very common case */
  8153.                 from += wsize - op;
  8154.                 if (op < len) {         /* some from window */
  8155.                   len -= op;
  8156.                   do {
  8157.                     output[_out++] = s_window[from++];
  8158.                   } while (--op);
  8159.                   from = _out - dist;  /* rest from output */
  8160.                   from_source = output;
  8161.                 }
  8162.               }
  8163.               else if (wnext < op) {      /* wrap around window */
  8164.                 from += wsize + wnext - op;
  8165.                 op -= wnext;
  8166.                 if (op < len) {         /* some from end of window */
  8167.                   len -= op;
  8168.                   do {
  8169.                     output[_out++] = s_window[from++];
  8170.                   } while (--op);
  8171.                   from = 0;
  8172.                   if (wnext < len) {  /* some from start of window */
  8173.                     op = wnext;
  8174.                     len -= op;
  8175.                     do {
  8176.                       output[_out++] = s_window[from++];
  8177.                     } while (--op);
  8178.                     from = _out - dist;      /* rest from output */
  8179.                     from_source = output;
  8180.                   }
  8181.                 }
  8182.               }
  8183.               else {                      /* contiguous in window */
  8184.                 from += wnext - op;
  8185.                 if (op < len) {         /* some from window */
  8186.                   len -= op;
  8187.                   do {
  8188.                     output[_out++] = s_window[from++];
  8189.                   } while (--op);
  8190.                   from = _out - dist;  /* rest from output */
  8191.                   from_source = output;
  8192.                 }
  8193.               }
  8194.               while (len > 2) {
  8195.                 output[_out++] = from_source[from++];
  8196.                 output[_out++] = from_source[from++];
  8197.                 output[_out++] = from_source[from++];
  8198.                 len -= 3;
  8199.               }
  8200.               if (len) {
  8201.                 output[_out++] = from_source[from++];
  8202.                 if (len > 1) {
  8203.                   output[_out++] = from_source[from++];
  8204.                 }
  8205.               }
  8206.             }
  8207.             else {
  8208.               from = _out - dist;          /* copy direct from output */
  8209.               do {                        /* minimum length is three */
  8210.                 output[_out++] = output[from++];
  8211.                 output[_out++] = output[from++];
  8212.                 output[_out++] = output[from++];
  8213.                 len -= 3;
  8214.               } while (len > 2);
  8215.               if (len) {
  8216.                 output[_out++] = output[from++];
  8217.                 if (len > 1) {
  8218.                   output[_out++] = output[from++];
  8219.                 }
  8220.               }
  8221.             }
  8222.           }
  8223.           else if ((op & 64) === 0) {          /* 2nd level distance code */
  8224.             here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8225.             continue dodist;
  8226.           }
  8227.           else {
  8228.             strm.msg = 'invalid distance code';
  8229.             state.mode = BAD;
  8230.             break top;
  8231.           }
  8232.  
  8233.           break; // need to emulate goto via "continue"
  8234.         }
  8235.       }
  8236.       else if ((op & 64) === 0) {              /* 2nd level length code */
  8237.         here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  8238.         continue dolen;
  8239.       }
  8240.       else if (op & 32) {                     /* end-of-block */
  8241.         //Tracevv((stderr, "inflate:         end of block\n"));
  8242.         state.mode = TYPE;
  8243.         break top;
  8244.       }
  8245.       else {
  8246.         strm.msg = 'invalid literal/length code';
  8247.         state.mode = BAD;
  8248.         break top;
  8249.       }
  8250.  
  8251.       break; // need to emulate goto via "continue"
  8252.     }
  8253.   } while (_in < last && _out < end);
  8254.  
  8255.   /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  8256.   len = bits >> 3;
  8257.   _in -= len;
  8258.   bits -= len << 3;
  8259.   hold &= (1 << bits) - 1;
  8260.  
  8261.   /* update state and return */
  8262.   strm.next_in = _in;
  8263.   strm.next_out = _out;
  8264.   strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  8265.   strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  8266.   state.hold = hold;
  8267.   state.bits = bits;
  8268.   return;
  8269. };
  8270.  
  8271. },{}],70:[function(require,module,exports){
  8272. 'use strict';
  8273.  
  8274.  
  8275. var utils         = require('../utils/common');
  8276. var adler32       = require('./adler32');
  8277. var crc32         = require('./crc32');
  8278. var inflate_fast  = require('./inffast');
  8279. var inflate_table = require('./inftrees');
  8280.  
  8281. var CODES = 0;
  8282. var LENS = 1;
  8283. var DISTS = 2;
  8284.  
  8285. /* Public constants ==========================================================*/
  8286. /* ===========================================================================*/
  8287.  
  8288.  
  8289. /* Allowed flush values; see deflate() and inflate() below for details */
  8290. //var Z_NO_FLUSH      = 0;
  8291. //var Z_PARTIAL_FLUSH = 1;
  8292. //var Z_SYNC_FLUSH    = 2;
  8293. //var Z_FULL_FLUSH    = 3;
  8294. var Z_FINISH        = 4;
  8295. var Z_BLOCK         = 5;
  8296. var Z_TREES         = 6;
  8297.  
  8298.  
  8299. /* Return codes for the compression/decompression functions. Negative values
  8300.  * are errors, positive values are used for special but normal events.
  8301.  */
  8302. var Z_OK            = 0;
  8303. var Z_STREAM_END    = 1;
  8304. var Z_NEED_DICT     = 2;
  8305. //var Z_ERRNO         = -1;
  8306. var Z_STREAM_ERROR  = -2;
  8307. var Z_DATA_ERROR    = -3;
  8308. var Z_MEM_ERROR     = -4;
  8309. var Z_BUF_ERROR     = -5;
  8310. //var Z_VERSION_ERROR = -6;
  8311.  
  8312. /* The deflate compression method */
  8313. var Z_DEFLATED  = 8;
  8314.  
  8315.  
  8316. /* STATES ====================================================================*/
  8317. /* ===========================================================================*/
  8318.  
  8319.  
  8320. var    HEAD = 1;       /* i: waiting for magic header */
  8321. var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
  8322. var    TIME = 3;       /* i: waiting for modification time (gzip) */
  8323. var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
  8324. var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
  8325. var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
  8326. var    NAME = 7;       /* i: waiting for end of file name (gzip) */
  8327. var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
  8328. var    HCRC = 9;       /* i: waiting for header crc (gzip) */
  8329. var    DICTID = 10;    /* i: waiting for dictionary check value */
  8330. var    DICT = 11;      /* waiting for inflateSetDictionary() call */
  8331. var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
  8332. var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
  8333. var        STORED = 14;    /* i: waiting for stored size (length and complement) */
  8334. var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
  8335. var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
  8336. var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
  8337. var        LENLENS = 18;   /* i: waiting for code length code lengths */
  8338. var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
  8339. var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
  8340. var            LEN = 21;       /* i: waiting for length/lit/eob code */
  8341. var            LENEXT = 22;    /* i: waiting for length extra bits */
  8342. var            DIST = 23;      /* i: waiting for distance code */
  8343. var            DISTEXT = 24;   /* i: waiting for distance extra bits */
  8344. var            MATCH = 25;     /* o: waiting for output space to copy string */
  8345. var            LIT = 26;       /* o: waiting for output space to write literal */
  8346. var    CHECK = 27;     /* i: waiting for 32-bit check value */
  8347. var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
  8348. var    DONE = 29;      /* finished check, done -- remain here until reset */
  8349. var    BAD = 30;       /* got a data error -- remain here until reset */
  8350. var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
  8351. var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
  8352.  
  8353. /* ===========================================================================*/
  8354.  
  8355.  
  8356.  
  8357. var ENOUGH_LENS = 852;
  8358. var ENOUGH_DISTS = 592;
  8359. //var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
  8360.  
  8361. var MAX_WBITS = 15;
  8362. /* 32K LZ77 window */
  8363. var DEF_WBITS = MAX_WBITS;
  8364.  
  8365.  
  8366. function zswap32(q) {
  8367.   return  (((q >>> 24) & 0xff) +
  8368.           ((q >>> 8) & 0xff00) +
  8369.           ((q & 0xff00) << 8) +
  8370.           ((q & 0xff) << 24));
  8371. }
  8372.  
  8373.  
  8374. function InflateState() {
  8375.   this.mode = 0;             /* current inflate mode */
  8376.   this.last = false;          /* true if processing last block */
  8377.   this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
  8378.   this.havedict = false;      /* true if dictionary provided */
  8379.   this.flags = 0;             /* gzip header method and flags (0 if zlib) */
  8380.   this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
  8381.   this.check = 0;             /* protected copy of check value */
  8382.   this.total = 0;             /* protected copy of output count */
  8383.   // TODO: may be {}
  8384.   this.head = null;           /* where to save gzip header information */
  8385.  
  8386.   /* sliding window */
  8387.   this.wbits = 0;             /* log base 2 of requested window size */
  8388.   this.wsize = 0;             /* window size or zero if not using window */
  8389.   this.whave = 0;             /* valid bytes in the window */
  8390.   this.wnext = 0;             /* window write index */
  8391.   this.window = null;         /* allocated sliding window, if needed */
  8392.  
  8393.   /* bit accumulator */
  8394.   this.hold = 0;              /* input bit accumulator */
  8395.   this.bits = 0;              /* number of bits in "in" */
  8396.  
  8397.   /* for string and stored block copying */
  8398.   this.length = 0;            /* literal or length of data to copy */
  8399.   this.offset = 0;            /* distance back to copy string from */
  8400.  
  8401.   /* for table and code decoding */
  8402.   this.extra = 0;             /* extra bits needed */
  8403.  
  8404.   /* fixed and dynamic code tables */
  8405.   this.lencode = null;          /* starting table for length/literal codes */
  8406.   this.distcode = null;         /* starting table for distance codes */
  8407.   this.lenbits = 0;           /* index bits for lencode */
  8408.   this.distbits = 0;          /* index bits for distcode */
  8409.  
  8410.   /* dynamic table building */
  8411.   this.ncode = 0;             /* number of code length code lengths */
  8412.   this.nlen = 0;              /* number of length code lengths */
  8413.   this.ndist = 0;             /* number of distance code lengths */
  8414.   this.have = 0;              /* number of code lengths in lens[] */
  8415.   this.next = null;              /* next available space in codes[] */
  8416.  
  8417.   this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  8418.   this.work = new utils.Buf16(288); /* work area for code table building */
  8419.  
  8420.   /*
  8421.    because we don't have pointers in js, we use lencode and distcode directly
  8422.    as buffers so we don't need codes
  8423.   */
  8424.   //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
  8425.   this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
  8426.   this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
  8427.   this.sane = 0;                   /* if false, allow invalid distance too far */
  8428.   this.back = 0;                   /* bits back of last unprocessed length/lit */
  8429.   this.was = 0;                    /* initial length of match */
  8430. }
  8431.  
  8432. function inflateResetKeep(strm) {
  8433.   var state;
  8434.  
  8435.   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8436.   state = strm.state;
  8437.   strm.total_in = strm.total_out = state.total = 0;
  8438.   strm.msg = ''; /*Z_NULL*/
  8439.   if (state.wrap) {       /* to support ill-conceived Java test suite */
  8440.     strm.adler = state.wrap & 1;
  8441.   }
  8442.   state.mode = HEAD;
  8443.   state.last = 0;
  8444.   state.havedict = 0;
  8445.   state.dmax = 32768;
  8446.   state.head = null/*Z_NULL*/;
  8447.   state.hold = 0;
  8448.   state.bits = 0;
  8449.   //state.lencode = state.distcode = state.next = state.codes;
  8450.   state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  8451.   state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  8452.  
  8453.   state.sane = 1;
  8454.   state.back = -1;
  8455.   //Tracev((stderr, "inflate: reset\n"));
  8456.   return Z_OK;
  8457. }
  8458.  
  8459. function inflateReset(strm) {
  8460.   var state;
  8461.  
  8462.   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8463.   state = strm.state;
  8464.   state.wsize = 0;
  8465.   state.whave = 0;
  8466.   state.wnext = 0;
  8467.   return inflateResetKeep(strm);
  8468.  
  8469. }
  8470.  
  8471. function inflateReset2(strm, windowBits) {
  8472.   var wrap;
  8473.   var state;
  8474.  
  8475.   /* get the state */
  8476.   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8477.   state = strm.state;
  8478.  
  8479.   /* extract wrap request from windowBits parameter */
  8480.   if (windowBits < 0) {
  8481.     wrap = 0;
  8482.     windowBits = -windowBits;
  8483.   }
  8484.   else {
  8485.     wrap = (windowBits >> 4) + 1;
  8486.     if (windowBits < 48) {
  8487.       windowBits &= 15;
  8488.     }
  8489.   }
  8490.  
  8491.   /* set number of window bits, free window if different */
  8492.   if (windowBits && (windowBits < 8 || windowBits > 15)) {
  8493.     return Z_STREAM_ERROR;
  8494.   }
  8495.   if (state.window !== null && state.wbits !== windowBits) {
  8496.     state.window = null;
  8497.   }
  8498.  
  8499.   /* update state and reset the rest of it */
  8500.   state.wrap = wrap;
  8501.   state.wbits = windowBits;
  8502.   return inflateReset(strm);
  8503. }
  8504.  
  8505. function inflateInit2(strm, windowBits) {
  8506.   var ret;
  8507.   var state;
  8508.  
  8509.   if (!strm) { return Z_STREAM_ERROR; }
  8510.   //strm.msg = Z_NULL;                 /* in case we return an error */
  8511.  
  8512.   state = new InflateState();
  8513.  
  8514.   //if (state === Z_NULL) return Z_MEM_ERROR;
  8515.   //Tracev((stderr, "inflate: allocated\n"));
  8516.   strm.state = state;
  8517.   state.window = null/*Z_NULL*/;
  8518.   ret = inflateReset2(strm, windowBits);
  8519.   if (ret !== Z_OK) {
  8520.     strm.state = null/*Z_NULL*/;
  8521.   }
  8522.   return ret;
  8523. }
  8524.  
  8525. function inflateInit(strm) {
  8526.   return inflateInit2(strm, DEF_WBITS);
  8527. }
  8528.  
  8529.  
  8530. /*
  8531.  Return state with length and distance decoding tables and index sizes set to
  8532.  fixed code decoding.  Normally this returns fixed tables from inffixed.h.
  8533.  If BUILDFIXED is defined, then instead this routine builds the tables the
  8534.  first time it's called, and returns those tables the first time and
  8535.  thereafter.  This reduces the size of the code by about 2K bytes, in
  8536.  exchange for a little execution time.  However, BUILDFIXED should not be
  8537.  used for threaded applications, since the rewriting of the tables and virgin
  8538.  may not be thread-safe.
  8539.  */
  8540. var virgin = true;
  8541.  
  8542. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  8543.  
  8544. function fixedtables(state) {
  8545.   /* build fixed huffman tables if first call (may not be thread safe) */
  8546.   if (virgin) {
  8547.     var sym;
  8548.  
  8549.     lenfix = new utils.Buf32(512);
  8550.     distfix = new utils.Buf32(32);
  8551.  
  8552.     /* literal/length table */
  8553.     sym = 0;
  8554.     while (sym < 144) { state.lens[sym++] = 8; }
  8555.     while (sym < 256) { state.lens[sym++] = 9; }
  8556.     while (sym < 280) { state.lens[sym++] = 7; }
  8557.     while (sym < 288) { state.lens[sym++] = 8; }
  8558.  
  8559.     inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });
  8560.  
  8561.     /* distance table */
  8562.     sym = 0;
  8563.     while (sym < 32) { state.lens[sym++] = 5; }
  8564.  
  8565.     inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });
  8566.  
  8567.     /* do this just once */
  8568.     virgin = false;
  8569.   }
  8570.  
  8571.   state.lencode = lenfix;
  8572.   state.lenbits = 9;
  8573.   state.distcode = distfix;
  8574.   state.distbits = 5;
  8575. }
  8576.  
  8577.  
  8578. /*
  8579.  Update the window with the last wsize (normally 32K) bytes written before
  8580.  returning.  If window does not exist yet, create it.  This is only called
  8581.  when a window is already in use, or when output has been written during this
  8582.  inflate call, but the end of the deflate stream has not been reached yet.
  8583.  It is also called to create a window for dictionary data when a dictionary
  8584.  is loaded.
  8585.  
  8586.  Providing output buffers larger than 32K to inflate() should provide a speed
  8587.  advantage, since only the last 32K of output is copied to the sliding window
  8588.  upon return from inflate(), and since all distances after the first 32K of
  8589.  output will fall in the output data, making match copies simpler and faster.
  8590.  The advantage may be dependent on the size of the processor's data caches.
  8591.  */
  8592. function updatewindow(strm, src, end, copy) {
  8593.   var dist;
  8594.   var state = strm.state;
  8595.  
  8596.   /* if it hasn't been done already, allocate space for the window */
  8597.   if (state.window === null) {
  8598.     state.wsize = 1 << state.wbits;
  8599.     state.wnext = 0;
  8600.     state.whave = 0;
  8601.  
  8602.     state.window = new utils.Buf8(state.wsize);
  8603.   }
  8604.  
  8605.   /* copy state->wsize or less output bytes into the circular window */
  8606.   if (copy >= state.wsize) {
  8607.     utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  8608.     state.wnext = 0;
  8609.     state.whave = state.wsize;
  8610.   }
  8611.   else {
  8612.     dist = state.wsize - state.wnext;
  8613.     if (dist > copy) {
  8614.       dist = copy;
  8615.     }
  8616.     //zmemcpy(state->window + state->wnext, end - copy, dist);
  8617.     utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  8618.     copy -= dist;
  8619.     if (copy) {
  8620.       //zmemcpy(state->window, end - copy, copy);
  8621.       utils.arraySet(state.window, src, end - copy, copy, 0);
  8622.       state.wnext = copy;
  8623.       state.whave = state.wsize;
  8624.     }
  8625.     else {
  8626.       state.wnext += dist;
  8627.       if (state.wnext === state.wsize) { state.wnext = 0; }
  8628.       if (state.whave < state.wsize) { state.whave += dist; }
  8629.     }
  8630.   }
  8631.   return 0;
  8632. }
  8633.  
  8634. function inflate(strm, flush) {
  8635.   var state;
  8636.   var input, output;          // input/output buffers
  8637.   var next;                   /* next input INDEX */
  8638.   var put;                    /* next output INDEX */
  8639.   var have, left;             /* available input and output */
  8640.   var hold;                   /* bit buffer */
  8641.   var bits;                   /* bits in bit buffer */
  8642.   var _in, _out;              /* save starting available input and output */
  8643.   var copy;                   /* number of stored or match bytes to copy */
  8644.   var from;                   /* where to copy match bytes from */
  8645.   var from_source;
  8646.   var here = 0;               /* current decoding table entry */
  8647.   var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  8648.   //var last;                   /* parent table entry */
  8649.   var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  8650.   var len;                    /* length to copy for repeats, bits to drop */
  8651.   var ret;                    /* return code */
  8652.   var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
  8653.   var opts;
  8654.  
  8655.   var n; // temporary var for NEED_BITS
  8656.  
  8657.   var order = /* permutation of code lengths */
  8658.     [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  8659.  
  8660.  
  8661.   if (!strm || !strm.state || !strm.output ||
  8662.       (!strm.input && strm.avail_in !== 0)) {
  8663.     return Z_STREAM_ERROR;
  8664.   }
  8665.  
  8666.   state = strm.state;
  8667.   if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
  8668.  
  8669.  
  8670.   //--- LOAD() ---
  8671.   put = strm.next_out;
  8672.   output = strm.output;
  8673.   left = strm.avail_out;
  8674.   next = strm.next_in;
  8675.   input = strm.input;
  8676.   have = strm.avail_in;
  8677.   hold = state.hold;
  8678.   bits = state.bits;
  8679.   //---
  8680.  
  8681.   _in = have;
  8682.   _out = left;
  8683.   ret = Z_OK;
  8684.  
  8685.   inf_leave: // goto emulation
  8686.   for (;;) {
  8687.     switch (state.mode) {
  8688.     case HEAD:
  8689.       if (state.wrap === 0) {
  8690.         state.mode = TYPEDO;
  8691.         break;
  8692.       }
  8693.       //=== NEEDBITS(16);
  8694.       while (bits < 16) {
  8695.         if (have === 0) { break inf_leave; }
  8696.         have--;
  8697.         hold += input[next++] << bits;
  8698.         bits += 8;
  8699.       }
  8700.       //===//
  8701.       if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
  8702.         state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  8703.         //=== CRC2(state.check, hold);
  8704.         hbuf[0] = hold & 0xff;
  8705.         hbuf[1] = (hold >>> 8) & 0xff;
  8706.         state.check = crc32(state.check, hbuf, 2, 0);
  8707.         //===//
  8708.  
  8709.         //=== INITBITS();
  8710.         hold = 0;
  8711.         bits = 0;
  8712.         //===//
  8713.         state.mode = FLAGS;
  8714.         break;
  8715.       }
  8716.       state.flags = 0;           /* expect zlib header */
  8717.       if (state.head) {
  8718.         state.head.done = false;
  8719.       }
  8720.       if (!(state.wrap & 1) ||   /* check if zlib header allowed */
  8721.         (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  8722.         strm.msg = 'incorrect header check';
  8723.         state.mode = BAD;
  8724.         break;
  8725.       }
  8726.       if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  8727.         strm.msg = 'unknown compression method';
  8728.         state.mode = BAD;
  8729.         break;
  8730.       }
  8731.       //--- DROPBITS(4) ---//
  8732.       hold >>>= 4;
  8733.       bits -= 4;
  8734.       //---//
  8735.       len = (hold & 0x0f)/*BITS(4)*/ + 8;
  8736.       if (state.wbits === 0) {
  8737.         state.wbits = len;
  8738.       }
  8739.       else if (len > state.wbits) {
  8740.         strm.msg = 'invalid window size';
  8741.         state.mode = BAD;
  8742.         break;
  8743.       }
  8744.       state.dmax = 1 << len;
  8745.       //Tracev((stderr, "inflate:   zlib header ok\n"));
  8746.       strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  8747.       state.mode = hold & 0x200 ? DICTID : TYPE;
  8748.       //=== INITBITS();
  8749.       hold = 0;
  8750.       bits = 0;
  8751.       //===//
  8752.       break;
  8753.     case FLAGS:
  8754.       //=== NEEDBITS(16); */
  8755.       while (bits < 16) {
  8756.         if (have === 0) { break inf_leave; }
  8757.         have--;
  8758.         hold += input[next++] << bits;
  8759.         bits += 8;
  8760.       }
  8761.       //===//
  8762.       state.flags = hold;
  8763.       if ((state.flags & 0xff) !== Z_DEFLATED) {
  8764.         strm.msg = 'unknown compression method';
  8765.         state.mode = BAD;
  8766.         break;
  8767.       }
  8768.       if (state.flags & 0xe000) {
  8769.         strm.msg = 'unknown header flags set';
  8770.         state.mode = BAD;
  8771.         break;
  8772.       }
  8773.       if (state.head) {
  8774.         state.head.text = ((hold >> 8) & 1);
  8775.       }
  8776.       if (state.flags & 0x0200) {
  8777.         //=== CRC2(state.check, hold);
  8778.         hbuf[0] = hold & 0xff;
  8779.         hbuf[1] = (hold >>> 8) & 0xff;
  8780.         state.check = crc32(state.check, hbuf, 2, 0);
  8781.         //===//
  8782.       }
  8783.       //=== INITBITS();
  8784.       hold = 0;
  8785.       bits = 0;
  8786.       //===//
  8787.       state.mode = TIME;
  8788.       /* falls through */
  8789.     case TIME:
  8790.       //=== NEEDBITS(32); */
  8791.       while (bits < 32) {
  8792.         if (have === 0) { break inf_leave; }
  8793.         have--;
  8794.         hold += input[next++] << bits;
  8795.         bits += 8;
  8796.       }
  8797.       //===//
  8798.       if (state.head) {
  8799.         state.head.time = hold;
  8800.       }
  8801.       if (state.flags & 0x0200) {
  8802.         //=== CRC4(state.check, hold)
  8803.         hbuf[0] = hold & 0xff;
  8804.         hbuf[1] = (hold >>> 8) & 0xff;
  8805.         hbuf[2] = (hold >>> 16) & 0xff;
  8806.         hbuf[3] = (hold >>> 24) & 0xff;
  8807.         state.check = crc32(state.check, hbuf, 4, 0);
  8808.         //===
  8809.       }
  8810.       //=== INITBITS();
  8811.       hold = 0;
  8812.       bits = 0;
  8813.       //===//
  8814.       state.mode = OS;
  8815.       /* falls through */
  8816.     case OS:
  8817.       //=== NEEDBITS(16); */
  8818.       while (bits < 16) {
  8819.         if (have === 0) { break inf_leave; }
  8820.         have--;
  8821.         hold += input[next++] << bits;
  8822.         bits += 8;
  8823.       }
  8824.       //===//
  8825.       if (state.head) {
  8826.         state.head.xflags = (hold & 0xff);
  8827.         state.head.os = (hold >> 8);
  8828.       }
  8829.       if (state.flags & 0x0200) {
  8830.         //=== CRC2(state.check, hold);
  8831.         hbuf[0] = hold & 0xff;
  8832.         hbuf[1] = (hold >>> 8) & 0xff;
  8833.         state.check = crc32(state.check, hbuf, 2, 0);
  8834.         //===//
  8835.       }
  8836.       //=== INITBITS();
  8837.       hold = 0;
  8838.       bits = 0;
  8839.       //===//
  8840.       state.mode = EXLEN;
  8841.       /* falls through */
  8842.     case EXLEN:
  8843.       if (state.flags & 0x0400) {
  8844.         //=== NEEDBITS(16); */
  8845.         while (bits < 16) {
  8846.           if (have === 0) { break inf_leave; }
  8847.           have--;
  8848.           hold += input[next++] << bits;
  8849.           bits += 8;
  8850.         }
  8851.         //===//
  8852.         state.length = hold;
  8853.         if (state.head) {
  8854.           state.head.extra_len = hold;
  8855.         }
  8856.         if (state.flags & 0x0200) {
  8857.           //=== CRC2(state.check, hold);
  8858.           hbuf[0] = hold & 0xff;
  8859.           hbuf[1] = (hold >>> 8) & 0xff;
  8860.           state.check = crc32(state.check, hbuf, 2, 0);
  8861.           //===//
  8862.         }
  8863.         //=== INITBITS();
  8864.         hold = 0;
  8865.         bits = 0;
  8866.         //===//
  8867.       }
  8868.       else if (state.head) {
  8869.         state.head.extra = null/*Z_NULL*/;
  8870.       }
  8871.       state.mode = EXTRA;
  8872.       /* falls through */
  8873.     case EXTRA:
  8874.       if (state.flags & 0x0400) {
  8875.         copy = state.length;
  8876.         if (copy > have) { copy = have; }
  8877.         if (copy) {
  8878.           if (state.head) {
  8879.             len = state.head.extra_len - state.length;
  8880.             if (!state.head.extra) {
  8881.               // Use untyped array for more conveniend processing later
  8882.               state.head.extra = new Array(state.head.extra_len);
  8883.             }
  8884.             utils.arraySet(
  8885.               state.head.extra,
  8886.               input,
  8887.               next,
  8888.               // extra field is limited to 65536 bytes
  8889.               // - no need for additional size check
  8890.               copy,
  8891.               /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  8892.               len
  8893.             );
  8894.             //zmemcpy(state.head.extra + len, next,
  8895.             //        len + copy > state.head.extra_max ?
  8896.             //        state.head.extra_max - len : copy);
  8897.           }
  8898.           if (state.flags & 0x0200) {
  8899.             state.check = crc32(state.check, input, copy, next);
  8900.           }
  8901.           have -= copy;
  8902.           next += copy;
  8903.           state.length -= copy;
  8904.         }
  8905.         if (state.length) { break inf_leave; }
  8906.       }
  8907.       state.length = 0;
  8908.       state.mode = NAME;
  8909.       /* falls through */
  8910.     case NAME:
  8911.       if (state.flags & 0x0800) {
  8912.         if (have === 0) { break inf_leave; }
  8913.         copy = 0;
  8914.         do {
  8915.           // TODO: 2 or 1 bytes?
  8916.           len = input[next + copy++];
  8917.           /* use constant limit because in js we should not preallocate memory */
  8918.           if (state.head && len &&
  8919.               (state.length < 65536 /*state.head.name_max*/)) {
  8920.             state.head.name += String.fromCharCode(len);
  8921.           }
  8922.         } while (len && copy < have);
  8923.  
  8924.         if (state.flags & 0x0200) {
  8925.           state.check = crc32(state.check, input, copy, next);
  8926.         }
  8927.         have -= copy;
  8928.         next += copy;
  8929.         if (len) { break inf_leave; }
  8930.       }
  8931.       else if (state.head) {
  8932.         state.head.name = null;
  8933.       }
  8934.       state.length = 0;
  8935.       state.mode = COMMENT;
  8936.       /* falls through */
  8937.     case COMMENT:
  8938.       if (state.flags & 0x1000) {
  8939.         if (have === 0) { break inf_leave; }
  8940.         copy = 0;
  8941.         do {
  8942.           len = input[next + copy++];
  8943.           /* use constant limit because in js we should not preallocate memory */
  8944.           if (state.head && len &&
  8945.               (state.length < 65536 /*state.head.comm_max*/)) {
  8946.             state.head.comment += String.fromCharCode(len);
  8947.           }
  8948.         } while (len && copy < have);
  8949.         if (state.flags & 0x0200) {
  8950.           state.check = crc32(state.check, input, copy, next);
  8951.         }
  8952.         have -= copy;
  8953.         next += copy;
  8954.         if (len) { break inf_leave; }
  8955.       }
  8956.       else if (state.head) {
  8957.         state.head.comment = null;
  8958.       }
  8959.       state.mode = HCRC;
  8960.       /* falls through */
  8961.     case HCRC:
  8962.       if (state.flags & 0x0200) {
  8963.         //=== NEEDBITS(16); */
  8964.         while (bits < 16) {
  8965.           if (have === 0) { break inf_leave; }
  8966.           have--;
  8967.           hold += input[next++] << bits;
  8968.           bits += 8;
  8969.         }
  8970.         //===//
  8971.         if (hold !== (state.check & 0xffff)) {
  8972.           strm.msg = 'header crc mismatch';
  8973.           state.mode = BAD;
  8974.           break;
  8975.         }
  8976.         //=== INITBITS();
  8977.         hold = 0;
  8978.         bits = 0;
  8979.         //===//
  8980.       }
  8981.       if (state.head) {
  8982.         state.head.hcrc = ((state.flags >> 9) & 1);
  8983.         state.head.done = true;
  8984.       }
  8985.       strm.adler = state.check = 0;
  8986.       state.mode = TYPE;
  8987.       break;
  8988.     case DICTID:
  8989.       //=== NEEDBITS(32); */
  8990.       while (bits < 32) {
  8991.         if (have === 0) { break inf_leave; }
  8992.         have--;
  8993.         hold += input[next++] << bits;
  8994.         bits += 8;
  8995.       }
  8996.       //===//
  8997.       strm.adler = state.check = zswap32(hold);
  8998.       //=== INITBITS();
  8999.       hold = 0;
  9000.       bits = 0;
  9001.       //===//
  9002.       state.mode = DICT;
  9003.       /* falls through */
  9004.     case DICT:
  9005.       if (state.havedict === 0) {
  9006.         //--- RESTORE() ---
  9007.         strm.next_out = put;
  9008.         strm.avail_out = left;
  9009.         strm.next_in = next;
  9010.         strm.avail_in = have;
  9011.         state.hold = hold;
  9012.         state.bits = bits;
  9013.         //---
  9014.         return Z_NEED_DICT;
  9015.       }
  9016.       strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  9017.       state.mode = TYPE;
  9018.       /* falls through */
  9019.     case TYPE:
  9020.       if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  9021.       /* falls through */
  9022.     case TYPEDO:
  9023.       if (state.last) {
  9024.         //--- BYTEBITS() ---//
  9025.         hold >>>= bits & 7;
  9026.         bits -= bits & 7;
  9027.         //---//
  9028.         state.mode = CHECK;
  9029.         break;
  9030.       }
  9031.       //=== NEEDBITS(3); */
  9032.       while (bits < 3) {
  9033.         if (have === 0) { break inf_leave; }
  9034.         have--;
  9035.         hold += input[next++] << bits;
  9036.         bits += 8;
  9037.       }
  9038.       //===//
  9039.       state.last = (hold & 0x01)/*BITS(1)*/;
  9040.       //--- DROPBITS(1) ---//
  9041.       hold >>>= 1;
  9042.       bits -= 1;
  9043.       //---//
  9044.  
  9045.       switch ((hold & 0x03)/*BITS(2)*/) {
  9046.       case 0:                             /* stored block */
  9047.         //Tracev((stderr, "inflate:     stored block%s\n",
  9048.         //        state.last ? " (last)" : ""));
  9049.         state.mode = STORED;
  9050.         break;
  9051.       case 1:                             /* fixed block */
  9052.         fixedtables(state);
  9053.         //Tracev((stderr, "inflate:     fixed codes block%s\n",
  9054.         //        state.last ? " (last)" : ""));
  9055.         state.mode = LEN_;             /* decode codes */
  9056.         if (flush === Z_TREES) {
  9057.           //--- DROPBITS(2) ---//
  9058.           hold >>>= 2;
  9059.           bits -= 2;
  9060.           //---//
  9061.           break inf_leave;
  9062.         }
  9063.         break;
  9064.       case 2:                             /* dynamic block */
  9065.         //Tracev((stderr, "inflate:     dynamic codes block%s\n",
  9066.         //        state.last ? " (last)" : ""));
  9067.         state.mode = TABLE;
  9068.         break;
  9069.       case 3:
  9070.         strm.msg = 'invalid block type';
  9071.         state.mode = BAD;
  9072.       }
  9073.       //--- DROPBITS(2) ---//
  9074.       hold >>>= 2;
  9075.       bits -= 2;
  9076.       //---//
  9077.       break;
  9078.     case STORED:
  9079.       //--- BYTEBITS() ---// /* go to byte boundary */
  9080.       hold >>>= bits & 7;
  9081.       bits -= bits & 7;
  9082.       //---//
  9083.       //=== NEEDBITS(32); */
  9084.       while (bits < 32) {
  9085.         if (have === 0) { break inf_leave; }
  9086.         have--;
  9087.         hold += input[next++] << bits;
  9088.         bits += 8;
  9089.       }
  9090.       //===//
  9091.       if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  9092.         strm.msg = 'invalid stored block lengths';
  9093.         state.mode = BAD;
  9094.         break;
  9095.       }
  9096.       state.length = hold & 0xffff;
  9097.       //Tracev((stderr, "inflate:       stored length %u\n",
  9098.       //        state.length));
  9099.       //=== INITBITS();
  9100.       hold = 0;
  9101.       bits = 0;
  9102.       //===//
  9103.       state.mode = COPY_;
  9104.       if (flush === Z_TREES) { break inf_leave; }
  9105.       /* falls through */
  9106.     case COPY_:
  9107.       state.mode = COPY;
  9108.       /* falls through */
  9109.     case COPY:
  9110.       copy = state.length;
  9111.       if (copy) {
  9112.         if (copy > have) { copy = have; }
  9113.         if (copy > left) { copy = left; }
  9114.         if (copy === 0) { break inf_leave; }
  9115.         //--- zmemcpy(put, next, copy); ---
  9116.         utils.arraySet(output, input, next, copy, put);
  9117.         //---//
  9118.         have -= copy;
  9119.         next += copy;
  9120.         left -= copy;
  9121.         put += copy;
  9122.         state.length -= copy;
  9123.         break;
  9124.       }
  9125.       //Tracev((stderr, "inflate:       stored end\n"));
  9126.       state.mode = TYPE;
  9127.       break;
  9128.     case TABLE:
  9129.       //=== NEEDBITS(14); */
  9130.       while (bits < 14) {
  9131.         if (have === 0) { break inf_leave; }
  9132.         have--;
  9133.         hold += input[next++] << bits;
  9134.         bits += 8;
  9135.       }
  9136.       //===//
  9137.       state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  9138.       //--- DROPBITS(5) ---//
  9139.       hold >>>= 5;
  9140.       bits -= 5;
  9141.       //---//
  9142.       state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  9143.       //--- DROPBITS(5) ---//
  9144.       hold >>>= 5;
  9145.       bits -= 5;
  9146.       //---//
  9147.       state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  9148.       //--- DROPBITS(4) ---//
  9149.       hold >>>= 4;
  9150.       bits -= 4;
  9151.       //---//
  9152. //#ifndef PKZIP_BUG_WORKAROUND
  9153.       if (state.nlen > 286 || state.ndist > 30) {
  9154.         strm.msg = 'too many length or distance symbols';
  9155.         state.mode = BAD;
  9156.         break;
  9157.       }
  9158. //#endif
  9159.       //Tracev((stderr, "inflate:       table sizes ok\n"));
  9160.       state.have = 0;
  9161.       state.mode = LENLENS;
  9162.       /* falls through */
  9163.     case LENLENS:
  9164.       while (state.have < state.ncode) {
  9165.         //=== NEEDBITS(3);
  9166.         while (bits < 3) {
  9167.           if (have === 0) { break inf_leave; }
  9168.           have--;
  9169.           hold += input[next++] << bits;
  9170.           bits += 8;
  9171.         }
  9172.         //===//
  9173.         state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  9174.         //--- DROPBITS(3) ---//
  9175.         hold >>>= 3;
  9176.         bits -= 3;
  9177.         //---//
  9178.       }
  9179.       while (state.have < 19) {
  9180.         state.lens[order[state.have++]] = 0;
  9181.       }
  9182.       // We have separate tables & no pointers. 2 commented lines below not needed.
  9183.       //state.next = state.codes;
  9184.       //state.lencode = state.next;
  9185.       // Switch to use dynamic table
  9186.       state.lencode = state.lendyn;
  9187.       state.lenbits = 7;
  9188.  
  9189.       opts = { bits: state.lenbits };
  9190.       ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  9191.       state.lenbits = opts.bits;
  9192.  
  9193.       if (ret) {
  9194.         strm.msg = 'invalid code lengths set';
  9195.         state.mode = BAD;
  9196.         break;
  9197.       }
  9198.       //Tracev((stderr, "inflate:       code lengths ok\n"));
  9199.       state.have = 0;
  9200.       state.mode = CODELENS;
  9201.       /* falls through */
  9202.     case CODELENS:
  9203.       while (state.have < state.nlen + state.ndist) {
  9204.         for (;;) {
  9205.           here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  9206.           here_bits = here >>> 24;
  9207.           here_op = (here >>> 16) & 0xff;
  9208.           here_val = here & 0xffff;
  9209.  
  9210.           if ((here_bits) <= bits) { break; }
  9211.           //--- PULLBYTE() ---//
  9212.           if (have === 0) { break inf_leave; }
  9213.           have--;
  9214.           hold += input[next++] << bits;
  9215.           bits += 8;
  9216.           //---//
  9217.         }
  9218.         if (here_val < 16) {
  9219.           //--- DROPBITS(here.bits) ---//
  9220.           hold >>>= here_bits;
  9221.           bits -= here_bits;
  9222.           //---//
  9223.           state.lens[state.have++] = here_val;
  9224.         }
  9225.         else {
  9226.           if (here_val === 16) {
  9227.             //=== NEEDBITS(here.bits + 2);
  9228.             n = here_bits + 2;
  9229.             while (bits < n) {
  9230.               if (have === 0) { break inf_leave; }
  9231.               have--;
  9232.               hold += input[next++] << bits;
  9233.               bits += 8;
  9234.             }
  9235.             //===//
  9236.             //--- DROPBITS(here.bits) ---//
  9237.             hold >>>= here_bits;
  9238.             bits -= here_bits;
  9239.             //---//
  9240.             if (state.have === 0) {
  9241.               strm.msg = 'invalid bit length repeat';
  9242.               state.mode = BAD;
  9243.               break;
  9244.             }
  9245.             len = state.lens[state.have - 1];
  9246.             copy = 3 + (hold & 0x03);//BITS(2);
  9247.             //--- DROPBITS(2) ---//
  9248.             hold >>>= 2;
  9249.             bits -= 2;
  9250.             //---//
  9251.           }
  9252.           else if (here_val === 17) {
  9253.             //=== NEEDBITS(here.bits + 3);
  9254.             n = here_bits + 3;
  9255.             while (bits < n) {
  9256.               if (have === 0) { break inf_leave; }
  9257.               have--;
  9258.               hold += input[next++] << bits;
  9259.               bits += 8;
  9260.             }
  9261.             //===//
  9262.             //--- DROPBITS(here.bits) ---//
  9263.             hold >>>= here_bits;
  9264.             bits -= here_bits;
  9265.             //---//
  9266.             len = 0;
  9267.             copy = 3 + (hold & 0x07);//BITS(3);
  9268.             //--- DROPBITS(3) ---//
  9269.             hold >>>= 3;
  9270.             bits -= 3;
  9271.             //---//
  9272.           }
  9273.           else {
  9274.             //=== NEEDBITS(here.bits + 7);
  9275.             n = here_bits + 7;
  9276.             while (bits < n) {
  9277.               if (have === 0) { break inf_leave; }
  9278.               have--;
  9279.               hold += input[next++] << bits;
  9280.               bits += 8;
  9281.             }
  9282.             //===//
  9283.             //--- DROPBITS(here.bits) ---//
  9284.             hold >>>= here_bits;
  9285.             bits -= here_bits;
  9286.             //---//
  9287.             len = 0;
  9288.             copy = 11 + (hold & 0x7f);//BITS(7);
  9289.             //--- DROPBITS(7) ---//
  9290.             hold >>>= 7;
  9291.             bits -= 7;
  9292.             //---//
  9293.           }
  9294.           if (state.have + copy > state.nlen + state.ndist) {
  9295.             strm.msg = 'invalid bit length repeat';
  9296.             state.mode = BAD;
  9297.             break;
  9298.           }
  9299.           while (copy--) {
  9300.             state.lens[state.have++] = len;
  9301.           }
  9302.         }
  9303.       }
  9304.  
  9305.       /* handle error breaks in while */
  9306.       if (state.mode === BAD) { break; }
  9307.  
  9308.       /* check for end-of-block code (better have one) */
  9309.       if (state.lens[256] === 0) {
  9310.         strm.msg = 'invalid code -- missing end-of-block';
  9311.         state.mode = BAD;
  9312.         break;
  9313.       }
  9314.  
  9315.       /* build code tables -- note: do not change the lenbits or distbits
  9316.          values here (9 and 6) without reading the comments in inftrees.h
  9317.          concerning the ENOUGH constants, which depend on those values */
  9318.       state.lenbits = 9;
  9319.  
  9320.       opts = { bits: state.lenbits };
  9321.       ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  9322.       // We have separate tables & no pointers. 2 commented lines below not needed.
  9323.       // state.next_index = opts.table_index;
  9324.       state.lenbits = opts.bits;
  9325.       // state.lencode = state.next;
  9326.  
  9327.       if (ret) {
  9328.         strm.msg = 'invalid literal/lengths set';
  9329.         state.mode = BAD;
  9330.         break;
  9331.       }
  9332.  
  9333.       state.distbits = 6;
  9334.       //state.distcode.copy(state.codes);
  9335.       // Switch to use dynamic table
  9336.       state.distcode = state.distdyn;
  9337.       opts = { bits: state.distbits };
  9338.       ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  9339.       // We have separate tables & no pointers. 2 commented lines below not needed.
  9340.       // state.next_index = opts.table_index;
  9341.       state.distbits = opts.bits;
  9342.       // state.distcode = state.next;
  9343.  
  9344.       if (ret) {
  9345.         strm.msg = 'invalid distances set';
  9346.         state.mode = BAD;
  9347.         break;
  9348.       }
  9349.       //Tracev((stderr, 'inflate:       codes ok\n'));
  9350.       state.mode = LEN_;
  9351.       if (flush === Z_TREES) { break inf_leave; }
  9352.       /* falls through */
  9353.     case LEN_:
  9354.       state.mode = LEN;
  9355.       /* falls through */
  9356.     case LEN:
  9357.       if (have >= 6 && left >= 258) {
  9358.         //--- RESTORE() ---
  9359.         strm.next_out = put;
  9360.         strm.avail_out = left;
  9361.         strm.next_in = next;
  9362.         strm.avail_in = have;
  9363.         state.hold = hold;
  9364.         state.bits = bits;
  9365.         //---
  9366.         inflate_fast(strm, _out);
  9367.         //--- LOAD() ---
  9368.         put = strm.next_out;
  9369.         output = strm.output;
  9370.         left = strm.avail_out;
  9371.         next = strm.next_in;
  9372.         input = strm.input;
  9373.         have = strm.avail_in;
  9374.         hold = state.hold;
  9375.         bits = state.bits;
  9376.         //---
  9377.  
  9378.         if (state.mode === TYPE) {
  9379.           state.back = -1;
  9380.         }
  9381.         break;
  9382.       }
  9383.       state.back = 0;
  9384.       for (;;) {
  9385.         here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
  9386.         here_bits = here >>> 24;
  9387.         here_op = (here >>> 16) & 0xff;
  9388.         here_val = here & 0xffff;
  9389.  
  9390.         if (here_bits <= bits) { break; }
  9391.         //--- PULLBYTE() ---//
  9392.         if (have === 0) { break inf_leave; }
  9393.         have--;
  9394.         hold += input[next++] << bits;
  9395.         bits += 8;
  9396.         //---//
  9397.       }
  9398.       if (here_op && (here_op & 0xf0) === 0) {
  9399.         last_bits = here_bits;
  9400.         last_op = here_op;
  9401.         last_val = here_val;
  9402.         for (;;) {
  9403.           here = state.lencode[last_val +
  9404.                   ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9405.           here_bits = here >>> 24;
  9406.           here_op = (here >>> 16) & 0xff;
  9407.           here_val = here & 0xffff;
  9408.  
  9409.           if ((last_bits + here_bits) <= bits) { break; }
  9410.           //--- PULLBYTE() ---//
  9411.           if (have === 0) { break inf_leave; }
  9412.           have--;
  9413.           hold += input[next++] << bits;
  9414.           bits += 8;
  9415.           //---//
  9416.         }
  9417.         //--- DROPBITS(last.bits) ---//
  9418.         hold >>>= last_bits;
  9419.         bits -= last_bits;
  9420.         //---//
  9421.         state.back += last_bits;
  9422.       }
  9423.       //--- DROPBITS(here.bits) ---//
  9424.       hold >>>= here_bits;
  9425.       bits -= here_bits;
  9426.       //---//
  9427.       state.back += here_bits;
  9428.       state.length = here_val;
  9429.       if (here_op === 0) {
  9430.         //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  9431.         //        "inflate:         literal '%c'\n" :
  9432.         //        "inflate:         literal 0x%02x\n", here.val));
  9433.         state.mode = LIT;
  9434.         break;
  9435.       }
  9436.       if (here_op & 32) {
  9437.         //Tracevv((stderr, "inflate:         end of block\n"));
  9438.         state.back = -1;
  9439.         state.mode = TYPE;
  9440.         break;
  9441.       }
  9442.       if (here_op & 64) {
  9443.         strm.msg = 'invalid literal/length code';
  9444.         state.mode = BAD;
  9445.         break;
  9446.       }
  9447.       state.extra = here_op & 15;
  9448.       state.mode = LENEXT;
  9449.       /* falls through */
  9450.     case LENEXT:
  9451.       if (state.extra) {
  9452.         //=== NEEDBITS(state.extra);
  9453.         n = state.extra;
  9454.         while (bits < n) {
  9455.           if (have === 0) { break inf_leave; }
  9456.           have--;
  9457.           hold += input[next++] << bits;
  9458.           bits += 8;
  9459.         }
  9460.         //===//
  9461.         state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9462.         //--- DROPBITS(state.extra) ---//
  9463.         hold >>>= state.extra;
  9464.         bits -= state.extra;
  9465.         //---//
  9466.         state.back += state.extra;
  9467.       }
  9468.       //Tracevv((stderr, "inflate:         length %u\n", state.length));
  9469.       state.was = state.length;
  9470.       state.mode = DIST;
  9471.       /* falls through */
  9472.     case DIST:
  9473.       for (;;) {
  9474.         here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  9475.         here_bits = here >>> 24;
  9476.         here_op = (here >>> 16) & 0xff;
  9477.         here_val = here & 0xffff;
  9478.  
  9479.         if ((here_bits) <= bits) { break; }
  9480.         //--- PULLBYTE() ---//
  9481.         if (have === 0) { break inf_leave; }
  9482.         have--;
  9483.         hold += input[next++] << bits;
  9484.         bits += 8;
  9485.         //---//
  9486.       }
  9487.       if ((here_op & 0xf0) === 0) {
  9488.         last_bits = here_bits;
  9489.         last_op = here_op;
  9490.         last_val = here_val;
  9491.         for (;;) {
  9492.           here = state.distcode[last_val +
  9493.                   ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  9494.           here_bits = here >>> 24;
  9495.           here_op = (here >>> 16) & 0xff;
  9496.           here_val = here & 0xffff;
  9497.  
  9498.           if ((last_bits + here_bits) <= bits) { break; }
  9499.           //--- PULLBYTE() ---//
  9500.           if (have === 0) { break inf_leave; }
  9501.           have--;
  9502.           hold += input[next++] << bits;
  9503.           bits += 8;
  9504.           //---//
  9505.         }
  9506.         //--- DROPBITS(last.bits) ---//
  9507.         hold >>>= last_bits;
  9508.         bits -= last_bits;
  9509.         //---//
  9510.         state.back += last_bits;
  9511.       }
  9512.       //--- DROPBITS(here.bits) ---//
  9513.       hold >>>= here_bits;
  9514.       bits -= here_bits;
  9515.       //---//
  9516.       state.back += here_bits;
  9517.       if (here_op & 64) {
  9518.         strm.msg = 'invalid distance code';
  9519.         state.mode = BAD;
  9520.         break;
  9521.       }
  9522.       state.offset = here_val;
  9523.       state.extra = (here_op) & 15;
  9524.       state.mode = DISTEXT;
  9525.       /* falls through */
  9526.     case DISTEXT:
  9527.       if (state.extra) {
  9528.         //=== NEEDBITS(state.extra);
  9529.         n = state.extra;
  9530.         while (bits < n) {
  9531.           if (have === 0) { break inf_leave; }
  9532.           have--;
  9533.           hold += input[next++] << bits;
  9534.           bits += 8;
  9535.         }
  9536.         //===//
  9537.         state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  9538.         //--- DROPBITS(state.extra) ---//
  9539.         hold >>>= state.extra;
  9540.         bits -= state.extra;
  9541.         //---//
  9542.         state.back += state.extra;
  9543.       }
  9544. //#ifdef INFLATE_STRICT
  9545.       if (state.offset > state.dmax) {
  9546.         strm.msg = 'invalid distance too far back';
  9547.         state.mode = BAD;
  9548.         break;
  9549.       }
  9550. //#endif
  9551.       //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
  9552.       state.mode = MATCH;
  9553.       /* falls through */
  9554.     case MATCH:
  9555.       if (left === 0) { break inf_leave; }
  9556.       copy = _out - left;
  9557.       if (state.offset > copy) {         /* copy from window */
  9558.         copy = state.offset - copy;
  9559.         if (copy > state.whave) {
  9560.           if (state.sane) {
  9561.             strm.msg = 'invalid distance too far back';
  9562.             state.mode = BAD;
  9563.             break;
  9564.           }
  9565. // (!) This block is disabled in zlib defailts,
  9566. // don't enable it for binary compatibility
  9567. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  9568. //          Trace((stderr, "inflate.c too far\n"));
  9569. //          copy -= state.whave;
  9570. //          if (copy > state.length) { copy = state.length; }
  9571. //          if (copy > left) { copy = left; }
  9572. //          left -= copy;
  9573. //          state.length -= copy;
  9574. //          do {
  9575. //            output[put++] = 0;
  9576. //          } while (--copy);
  9577. //          if (state.length === 0) { state.mode = LEN; }
  9578. //          break;
  9579. //#endif
  9580.         }
  9581.         if (copy > state.wnext) {
  9582.           copy -= state.wnext;
  9583.           from = state.wsize - copy;
  9584.         }
  9585.         else {
  9586.           from = state.wnext - copy;
  9587.         }
  9588.         if (copy > state.length) { copy = state.length; }
  9589.         from_source = state.window;
  9590.       }
  9591.       else {                              /* copy from output */
  9592.         from_source = output;
  9593.         from = put - state.offset;
  9594.         copy = state.length;
  9595.       }
  9596.       if (copy > left) { copy = left; }
  9597.       left -= copy;
  9598.       state.length -= copy;
  9599.       do {
  9600.         output[put++] = from_source[from++];
  9601.       } while (--copy);
  9602.       if (state.length === 0) { state.mode = LEN; }
  9603.       break;
  9604.     case LIT:
  9605.       if (left === 0) { break inf_leave; }
  9606.       output[put++] = state.length;
  9607.       left--;
  9608.       state.mode = LEN;
  9609.       break;
  9610.     case CHECK:
  9611.       if (state.wrap) {
  9612.         //=== NEEDBITS(32);
  9613.         while (bits < 32) {
  9614.           if (have === 0) { break inf_leave; }
  9615.           have--;
  9616.           // Use '|' insdead of '+' to make sure that result is signed
  9617.           hold |= input[next++] << bits;
  9618.           bits += 8;
  9619.         }
  9620.         //===//
  9621.         _out -= left;
  9622.         strm.total_out += _out;
  9623.         state.total += _out;
  9624.         if (_out) {
  9625.           strm.adler = state.check =
  9626.               /*UPDATE(state.check, put - _out, _out);*/
  9627.               (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  9628.  
  9629.         }
  9630.         _out = left;
  9631.         // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  9632.         if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  9633.           strm.msg = 'incorrect data check';
  9634.           state.mode = BAD;
  9635.           break;
  9636.         }
  9637.         //=== INITBITS();
  9638.         hold = 0;
  9639.         bits = 0;
  9640.         //===//
  9641.         //Tracev((stderr, "inflate:   check matches trailer\n"));
  9642.       }
  9643.       state.mode = LENGTH;
  9644.       /* falls through */
  9645.     case LENGTH:
  9646.       if (state.wrap && state.flags) {
  9647.         //=== NEEDBITS(32);
  9648.         while (bits < 32) {
  9649.           if (have === 0) { break inf_leave; }
  9650.           have--;
  9651.           hold += input[next++] << bits;
  9652.           bits += 8;
  9653.         }
  9654.         //===//
  9655.         if (hold !== (state.total & 0xffffffff)) {
  9656.           strm.msg = 'incorrect length check';
  9657.           state.mode = BAD;
  9658.           break;
  9659.         }
  9660.         //=== INITBITS();
  9661.         hold = 0;
  9662.         bits = 0;
  9663.         //===//
  9664.         //Tracev((stderr, "inflate:   length matches trailer\n"));
  9665.       }
  9666.       state.mode = DONE;
  9667.       /* falls through */
  9668.     case DONE:
  9669.       ret = Z_STREAM_END;
  9670.       break inf_leave;
  9671.     case BAD:
  9672.       ret = Z_DATA_ERROR;
  9673.       break inf_leave;
  9674.     case MEM:
  9675.       return Z_MEM_ERROR;
  9676.     case SYNC:
  9677.       /* falls through */
  9678.     default:
  9679.       return Z_STREAM_ERROR;
  9680.     }
  9681.   }
  9682.  
  9683.   // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  9684.  
  9685.   /*
  9686.      Return from inflate(), updating the total counts and the check value.
  9687.      If there was no progress during the inflate() call, return a buffer
  9688.      error.  Call updatewindow() to create and/or update the window state.
  9689.      Note: a memory error from inflate() is non-recoverable.
  9690.    */
  9691.  
  9692.   //--- RESTORE() ---
  9693.   strm.next_out = put;
  9694.   strm.avail_out = left;
  9695.   strm.next_in = next;
  9696.   strm.avail_in = have;
  9697.   state.hold = hold;
  9698.   state.bits = bits;
  9699.   //---
  9700.  
  9701.   if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  9702.                       (state.mode < CHECK || flush !== Z_FINISH))) {
  9703.     if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  9704.       state.mode = MEM;
  9705.       return Z_MEM_ERROR;
  9706.     }
  9707.   }
  9708.   _in -= strm.avail_in;
  9709.   _out -= strm.avail_out;
  9710.   strm.total_in += _in;
  9711.   strm.total_out += _out;
  9712.   state.total += _out;
  9713.   if (state.wrap && _out) {
  9714.     strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  9715.       (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  9716.   }
  9717.   strm.data_type = state.bits + (state.last ? 64 : 0) +
  9718.                     (state.mode === TYPE ? 128 : 0) +
  9719.                     (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  9720.   if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  9721.     ret = Z_BUF_ERROR;
  9722.   }
  9723.   return ret;
  9724. }
  9725.  
  9726. function inflateEnd(strm) {
  9727.  
  9728.   if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  9729.     return Z_STREAM_ERROR;
  9730.   }
  9731.  
  9732.   var state = strm.state;
  9733.   if (state.window) {
  9734.     state.window = null;
  9735.   }
  9736.   strm.state = null;
  9737.   return Z_OK;
  9738. }
  9739.  
  9740. function inflateGetHeader(strm, head) {
  9741.   var state;
  9742.  
  9743.   /* check state */
  9744.   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  9745.   state = strm.state;
  9746.   if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  9747.  
  9748.   /* save header structure */
  9749.   state.head = head;
  9750.   head.done = false;
  9751.   return Z_OK;
  9752. }
  9753.  
  9754. function inflateSetDictionary(strm, dictionary) {
  9755.   var dictLength = dictionary.length;
  9756.  
  9757.   var state;
  9758.   var dictid;
  9759.   var ret;
  9760.  
  9761.   /* check state */
  9762.   if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  9763.   state = strm.state;
  9764.  
  9765.   if (state.wrap !== 0 && state.mode !== DICT) {
  9766.     return Z_STREAM_ERROR;
  9767.   }
  9768.  
  9769.   /* check for correct dictionary identifier */
  9770.   if (state.mode === DICT) {
  9771.     dictid = 1; /* adler32(0, null, 0)*/
  9772.     /* dictid = adler32(dictid, dictionary, dictLength); */
  9773.     dictid = adler32(dictid, dictionary, dictLength, 0);
  9774.     if (dictid !== state.check) {
  9775.       return Z_DATA_ERROR;
  9776.     }
  9777.   }
  9778.   /* copy dictionary to window using updatewindow(), which will amend the
  9779.    existing dictionary if appropriate */
  9780.   ret = updatewindow(strm, dictionary, dictLength, dictLength);
  9781.   if (ret) {
  9782.     state.mode = MEM;
  9783.     return Z_MEM_ERROR;
  9784.   }
  9785.   state.havedict = 1;
  9786.   // Tracev((stderr, "inflate:   dictionary set\n"));
  9787.   return Z_OK;
  9788. }
  9789.  
  9790. exports.inflateReset = inflateReset;
  9791. exports.inflateReset2 = inflateReset2;
  9792. exports.inflateResetKeep = inflateResetKeep;
  9793. exports.inflateInit = inflateInit;
  9794. exports.inflateInit2 = inflateInit2;
  9795. exports.inflate = inflate;
  9796. exports.inflateEnd = inflateEnd;
  9797. exports.inflateGetHeader = inflateGetHeader;
  9798. exports.inflateSetDictionary = inflateSetDictionary;
  9799. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  9800.  
  9801. /* Not implemented
  9802. exports.inflateCopy = inflateCopy;
  9803. exports.inflateGetDictionary = inflateGetDictionary;
  9804. exports.inflateMark = inflateMark;
  9805. exports.inflatePrime = inflatePrime;
  9806. exports.inflateSync = inflateSync;
  9807. exports.inflateSyncPoint = inflateSyncPoint;
  9808. exports.inflateUndermine = inflateUndermine;
  9809. */
  9810.  
  9811. },{"../utils/common":62,"./adler32":64,"./crc32":66,"./inffast":69,"./inftrees":71}],71:[function(require,module,exports){
  9812. 'use strict';
  9813.  
  9814.  
  9815. var utils = require('../utils/common');
  9816.  
  9817. var MAXBITS = 15;
  9818. var ENOUGH_LENS = 852;
  9819. var ENOUGH_DISTS = 592;
  9820. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  9821.  
  9822. var CODES = 0;
  9823. var LENS = 1;
  9824. var DISTS = 2;
  9825.  
  9826. var lbase = [ /* Length codes 257..285 base */
  9827.   3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  9828.   35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  9829. ];
  9830.  
  9831. var lext = [ /* Length codes 257..285 extra */
  9832.   16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  9833.   19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  9834. ];
  9835.  
  9836. var dbase = [ /* Distance codes 0..29 base */
  9837.   1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  9838.   257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  9839.   8193, 12289, 16385, 24577, 0, 0
  9840. ];
  9841.  
  9842. var dext = [ /* Distance codes 0..29 extra */
  9843.   16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  9844.   23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  9845.   28, 28, 29, 29, 64, 64
  9846. ];
  9847.  
  9848. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  9849. {
  9850.   var bits = opts.bits;
  9851.       //here = opts.here; /* table entry for duplication */
  9852.  
  9853.   var len = 0;               /* a code's length in bits */
  9854.   var sym = 0;               /* index of code symbols */
  9855.   var min = 0, max = 0;          /* minimum and maximum code lengths */
  9856.   var root = 0;              /* number of index bits for root table */
  9857.   var curr = 0;              /* number of index bits for current table */
  9858.   var drop = 0;              /* code bits to drop for sub-table */
  9859.   var left = 0;                   /* number of prefix codes available */
  9860.   var used = 0;              /* code entries in table used */
  9861.   var huff = 0;              /* Huffman code */
  9862.   var incr;              /* for incrementing code, index */
  9863.   var fill;              /* index for replicating entries */
  9864.   var low;               /* low bits for current root entry */
  9865.   var mask;              /* mask for low root bits */
  9866.   var next;             /* next available space in table */
  9867.   var base = null;     /* base value table to use */
  9868.   var base_index = 0;
  9869. //  var shoextra;    /* extra bits table to use */
  9870.   var end;                    /* use base and extra for symbol > end */
  9871.   var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
  9872.   var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
  9873.   var extra = null;
  9874.   var extra_index = 0;
  9875.  
  9876.   var here_bits, here_op, here_val;
  9877.  
  9878.   /*
  9879.    Process a set of code lengths to create a canonical Huffman code.  The
  9880.    code lengths are lens[0..codes-1].  Each length corresponds to the
  9881.    symbols 0..codes-1.  The Huffman code is generated by first sorting the
  9882.    symbols by length from short to long, and retaining the symbol order
  9883.    for codes with equal lengths.  Then the code starts with all zero bits
  9884.    for the first code of the shortest length, and the codes are integer
  9885.    increments for the same length, and zeros are appended as the length
  9886.    increases.  For the deflate format, these bits are stored backwards
  9887.    from their more natural integer increment ordering, and so when the
  9888.    decoding tables are built in the large loop below, the integer codes
  9889.    are incremented backwards.
  9890.  
  9891.    This routine assumes, but does not check, that all of the entries in
  9892.    lens[] are in the range 0..MAXBITS.  The caller must assure this.
  9893.    1..MAXBITS is interpreted as that code length.  zero means that that
  9894.    symbol does not occur in this code.
  9895.  
  9896.    The codes are sorted by computing a count of codes for each length,
  9897.    creating from that a table of starting indices for each length in the
  9898.    sorted table, and then entering the symbols in order in the sorted
  9899.    table.  The sorted table is work[], with that space being provided by
  9900.    the caller.
  9901.  
  9902.    The length counts are used for other purposes as well, i.e. finding
  9903.    the minimum and maximum length codes, determining if there are any
  9904.    codes at all, checking for a valid set of lengths, and looking ahead
  9905.    at length counts to determine sub-table sizes when building the
  9906.    decoding tables.
  9907.    */
  9908.  
  9909.   /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  9910.   for (len = 0; len <= MAXBITS; len++) {
  9911.     count[len] = 0;
  9912.   }
  9913.   for (sym = 0; sym < codes; sym++) {
  9914.     count[lens[lens_index + sym]]++;
  9915.   }
  9916.  
  9917.   /* bound code lengths, force root to be within code lengths */
  9918.   root = bits;
  9919.   for (max = MAXBITS; max >= 1; max--) {
  9920.     if (count[max] !== 0) { break; }
  9921.   }
  9922.   if (root > max) {
  9923.     root = max;
  9924.   }
  9925.   if (max === 0) {                     /* no symbols to code at all */
  9926.     //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
  9927.     //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
  9928.     //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
  9929.     table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9930.  
  9931.  
  9932.     //table.op[opts.table_index] = 64;
  9933.     //table.bits[opts.table_index] = 1;
  9934.     //table.val[opts.table_index++] = 0;
  9935.     table[table_index++] = (1 << 24) | (64 << 16) | 0;
  9936.  
  9937.     opts.bits = 1;
  9938.     return 0;     /* no symbols, but wait for decoding to report error */
  9939.   }
  9940.   for (min = 1; min < max; min++) {
  9941.     if (count[min] !== 0) { break; }
  9942.   }
  9943.   if (root < min) {
  9944.     root = min;
  9945.   }
  9946.  
  9947.   /* check for an over-subscribed or incomplete set of lengths */
  9948.   left = 1;
  9949.   for (len = 1; len <= MAXBITS; len++) {
  9950.     left <<= 1;
  9951.     left -= count[len];
  9952.     if (left < 0) {
  9953.       return -1;
  9954.     }        /* over-subscribed */
  9955.   }
  9956.   if (left > 0 && (type === CODES || max !== 1)) {
  9957.     return -1;                      /* incomplete set */
  9958.   }
  9959.  
  9960.   /* generate offsets into symbol table for each length for sorting */
  9961.   offs[1] = 0;
  9962.   for (len = 1; len < MAXBITS; len++) {
  9963.     offs[len + 1] = offs[len] + count[len];
  9964.   }
  9965.  
  9966.   /* sort symbols by length, by symbol order within each length */
  9967.   for (sym = 0; sym < codes; sym++) {
  9968.     if (lens[lens_index + sym] !== 0) {
  9969.       work[offs[lens[lens_index + sym]]++] = sym;
  9970.     }
  9971.   }
  9972.  
  9973.   /*
  9974.    Create and fill in decoding tables.  In this loop, the table being
  9975.    filled is at next and has curr index bits.  The code being used is huff
  9976.    with length len.  That code is converted to an index by dropping drop
  9977.    bits off of the bottom.  For codes where len is less than drop + curr,
  9978.    those top drop + curr - len bits are incremented through all values to
  9979.    fill the table with replicated entries.
  9980.  
  9981.    root is the number of index bits for the root table.  When len exceeds
  9982.    root, sub-tables are created pointed to by the root entry with an index
  9983.    of the low root bits of huff.  This is saved in low to check for when a
  9984.    new sub-table should be started.  drop is zero when the root table is
  9985.    being filled, and drop is root when sub-tables are being filled.
  9986.  
  9987.    When a new sub-table is needed, it is necessary to look ahead in the
  9988.    code lengths to determine what size sub-table is needed.  The length
  9989.    counts are used for this, and so count[] is decremented as codes are
  9990.    entered in the tables.
  9991.  
  9992.    used keeps track of how many table entries have been allocated from the
  9993.    provided *table space.  It is checked for LENS and DIST tables against
  9994.    the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  9995.    the initial root table size constants.  See the comments in inftrees.h
  9996.    for more information.
  9997.  
  9998.    sym increments through all symbols, and the loop terminates when
  9999.    all codes of length max, i.e. all codes, have been processed.  This
  10000.    routine permits incomplete codes, so another loop after this one fills
  10001.    in the rest of the decoding tables with invalid code markers.
  10002.    */
  10003.  
  10004.   /* set up for code type */
  10005.   // poor man optimization - use if-else instead of switch,
  10006.   // to avoid deopts in old v8
  10007.   if (type === CODES) {
  10008.     base = extra = work;    /* dummy value--not used */
  10009.     end = 19;
  10010.  
  10011.   } else if (type === LENS) {
  10012.     base = lbase;
  10013.     base_index -= 257;
  10014.     extra = lext;
  10015.     extra_index -= 257;
  10016.     end = 256;
  10017.  
  10018.   } else {                    /* DISTS */
  10019.     base = dbase;
  10020.     extra = dext;
  10021.     end = -1;
  10022.   }
  10023.  
  10024.   /* initialize opts for loop */
  10025.   huff = 0;                   /* starting code */
  10026.   sym = 0;                    /* starting code symbol */
  10027.   len = min;                  /* starting code length */
  10028.   next = table_index;              /* current table to fill in */
  10029.   curr = root;                /* current table index bits */
  10030.   drop = 0;                   /* current bits to drop from code for index */
  10031.   low = -1;                   /* trigger new sub-table when len > root */
  10032.   used = 1 << root;          /* use root table entries */
  10033.   mask = used - 1;            /* mask for comparing low */
  10034.  
  10035.   /* check available table space */
  10036.   if ((type === LENS && used > ENOUGH_LENS) ||
  10037.     (type === DISTS && used > ENOUGH_DISTS)) {
  10038.     return 1;
  10039.   }
  10040.  
  10041.   var i = 0;
  10042.   /* process all codes and make table entries */
  10043.   for (;;) {
  10044.     i++;
  10045.     /* create table entry */
  10046.     here_bits = len - drop;
  10047.     if (work[sym] < end) {
  10048.       here_op = 0;
  10049.       here_val = work[sym];
  10050.     }
  10051.     else if (work[sym] > end) {
  10052.       here_op = extra[extra_index + work[sym]];
  10053.       here_val = base[base_index + work[sym]];
  10054.     }
  10055.     else {
  10056.       here_op = 32 + 64;         /* end of block */
  10057.       here_val = 0;
  10058.     }
  10059.  
  10060.     /* replicate for those indices with low len bits equal to huff */
  10061.     incr = 1 << (len - drop);
  10062.     fill = 1 << curr;
  10063.     min = fill;                 /* save offset to next table */
  10064.     do {
  10065.       fill -= incr;
  10066.       table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  10067.     } while (fill !== 0);
  10068.  
  10069.     /* backwards increment the len-bit code huff */
  10070.     incr = 1 << (len - 1);
  10071.     while (huff & incr) {
  10072.       incr >>= 1;
  10073.     }
  10074.     if (incr !== 0) {
  10075.       huff &= incr - 1;
  10076.       huff += incr;
  10077.     } else {
  10078.       huff = 0;
  10079.     }
  10080.  
  10081.     /* go to next symbol, update count, len */
  10082.     sym++;
  10083.     if (--count[len] === 0) {
  10084.       if (len === max) { break; }
  10085.       len = lens[lens_index + work[sym]];
  10086.     }
  10087.  
  10088.     /* create new sub-table if needed */
  10089.     if (len > root && (huff & mask) !== low) {
  10090.       /* if first time, transition to sub-tables */
  10091.       if (drop === 0) {
  10092.         drop = root;
  10093.       }
  10094.  
  10095.       /* increment past last table */
  10096.       next += min;            /* here min is 1 << curr */
  10097.  
  10098.       /* determine length of next table */
  10099.       curr = len - drop;
  10100.       left = 1 << curr;
  10101.       while (curr + drop < max) {
  10102.         left -= count[curr + drop];
  10103.         if (left <= 0) { break; }
  10104.         curr++;
  10105.         left <<= 1;
  10106.       }
  10107.  
  10108.       /* check for enough space */
  10109.       used += 1 << curr;
  10110.       if ((type === LENS && used > ENOUGH_LENS) ||
  10111.         (type === DISTS && used > ENOUGH_DISTS)) {
  10112.         return 1;
  10113.       }
  10114.  
  10115.       /* point entry in root table to sub-table */
  10116.       low = huff & mask;
  10117.       /*table.op[low] = curr;
  10118.       table.bits[low] = root;
  10119.       table.val[low] = next - opts.table_index;*/
  10120.       table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  10121.     }
  10122.   }
  10123.  
  10124.   /* fill in remaining table entry if code is incomplete (guaranteed to have
  10125.    at most one remaining entry, since if the code is incomplete, the
  10126.    maximum code length that was allowed to get this far is one bit) */
  10127.   if (huff !== 0) {
  10128.     //table.op[next + huff] = 64;            /* invalid code marker */
  10129.     //table.bits[next + huff] = len - drop;
  10130.     //table.val[next + huff] = 0;
  10131.     table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  10132.   }
  10133.  
  10134.   /* set return parameters */
  10135.   //opts.table_index += used;
  10136.   opts.bits = root;
  10137.   return 0;
  10138. };
  10139.  
  10140. },{"../utils/common":62}],72:[function(require,module,exports){
  10141. 'use strict';
  10142.  
  10143. module.exports = {
  10144.   2:      'need dictionary',     /* Z_NEED_DICT       2  */
  10145.   1:      'stream end',          /* Z_STREAM_END      1  */
  10146.   0:      '',                    /* Z_OK              0  */
  10147.   '-1':   'file error',          /* Z_ERRNO         (-1) */
  10148.   '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
  10149.   '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
  10150.   '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
  10151.   '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
  10152.   '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
  10153. };
  10154.  
  10155. },{}],73:[function(require,module,exports){
  10156. 'use strict';
  10157.  
  10158.  
  10159. var utils = require('../utils/common');
  10160.  
  10161. /* Public constants ==========================================================*/
  10162. /* ===========================================================================*/
  10163.  
  10164.  
  10165. //var Z_FILTERED          = 1;
  10166. //var Z_HUFFMAN_ONLY      = 2;
  10167. //var Z_RLE               = 3;
  10168. var Z_FIXED               = 4;
  10169. //var Z_DEFAULT_STRATEGY  = 0;
  10170.  
  10171. /* Possible values of the data_type field (though see inflate()) */
  10172. var Z_BINARY              = 0;
  10173. var Z_TEXT                = 1;
  10174. //var Z_ASCII             = 1; // = Z_TEXT
  10175. var Z_UNKNOWN             = 2;
  10176.  
  10177. /*============================================================================*/
  10178.  
  10179.  
  10180. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  10181.  
  10182. // From zutil.h
  10183.  
  10184. var STORED_BLOCK = 0;
  10185. var STATIC_TREES = 1;
  10186. var DYN_TREES    = 2;
  10187. /* The three kinds of block type */
  10188.  
  10189. var MIN_MATCH    = 3;
  10190. var MAX_MATCH    = 258;
  10191. /* The minimum and maximum match lengths */
  10192.  
  10193. // From deflate.h
  10194. /* ===========================================================================
  10195.  * Internal compression state.
  10196.  */
  10197.  
  10198. var LENGTH_CODES  = 29;
  10199. /* number of length codes, not counting the special END_BLOCK code */
  10200.  
  10201. var LITERALS      = 256;
  10202. /* number of literal bytes 0..255 */
  10203.  
  10204. var L_CODES       = LITERALS + 1 + LENGTH_CODES;
  10205. /* number of Literal or Length codes, including the END_BLOCK code */
  10206.  
  10207. var D_CODES       = 30;
  10208. /* number of distance codes */
  10209.  
  10210. var BL_CODES      = 19;
  10211. /* number of codes used to transfer the bit lengths */
  10212.  
  10213. var HEAP_SIZE     = 2 * L_CODES + 1;
  10214. /* maximum heap size */
  10215.  
  10216. var MAX_BITS      = 15;
  10217. /* All codes must not exceed MAX_BITS bits */
  10218.  
  10219. var Buf_size      = 16;
  10220. /* size of bit buffer in bi_buf */
  10221.  
  10222.  
  10223. /* ===========================================================================
  10224.  * Constants
  10225.  */
  10226.  
  10227. var MAX_BL_BITS = 7;
  10228. /* Bit length codes must not exceed MAX_BL_BITS bits */
  10229.  
  10230. var END_BLOCK   = 256;
  10231. /* end of block literal code */
  10232.  
  10233. var REP_3_6     = 16;
  10234. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  10235.  
  10236. var REPZ_3_10   = 17;
  10237. /* repeat a zero length 3-10 times  (3 bits of repeat count) */
  10238.  
  10239. var REPZ_11_138 = 18;
  10240. /* repeat a zero length 11-138 times  (7 bits of repeat count) */
  10241.  
  10242. /* eslint-disable comma-spacing,array-bracket-spacing */
  10243. var extra_lbits =   /* extra bits for each length code */
  10244.   [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];
  10245.  
  10246. var extra_dbits =   /* extra bits for each distance code */
  10247.   [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];
  10248.  
  10249. var extra_blbits =  /* extra bits for each bit length code */
  10250.   [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  10251.  
  10252. var bl_order =
  10253.   [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  10254. /* eslint-enable comma-spacing,array-bracket-spacing */
  10255.  
  10256. /* The lengths of the bit length codes are sent in order of decreasing
  10257.  * probability, to avoid transmitting the lengths for unused bit length codes.
  10258.  */
  10259.  
  10260. /* ===========================================================================
  10261.  * Local data. These are initialized only once.
  10262.  */
  10263.  
  10264. // We pre-fill arrays with 0 to avoid uninitialized gaps
  10265.  
  10266. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  10267.  
  10268. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  10269. var static_ltree  = new Array((L_CODES + 2) * 2);
  10270. zero(static_ltree);
  10271. /* The static literal tree. Since the bit lengths are imposed, there is no
  10272.  * need for the L_CODES extra codes used during heap construction. However
  10273.  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  10274.  * below).
  10275.  */
  10276.  
  10277. var static_dtree  = new Array(D_CODES * 2);
  10278. zero(static_dtree);
  10279. /* The static distance tree. (Actually a trivial tree since all codes use
  10280.  * 5 bits.)
  10281.  */
  10282.  
  10283. var _dist_code    = new Array(DIST_CODE_LEN);
  10284. zero(_dist_code);
  10285. /* Distance codes. The first 256 values correspond to the distances
  10286.  * 3 .. 258, the last 256 values correspond to the top 8 bits of
  10287.  * the 15 bit distances.
  10288.  */
  10289.  
  10290. var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
  10291. zero(_length_code);
  10292. /* length code for each normalized match length (0 == MIN_MATCH) */
  10293.  
  10294. var base_length   = new Array(LENGTH_CODES);
  10295. zero(base_length);
  10296. /* First normalized length for each code (0 = MIN_MATCH) */
  10297.  
  10298. var base_dist     = new Array(D_CODES);
  10299. zero(base_dist);
  10300. /* First normalized distance for each code (0 = distance of 1) */
  10301.  
  10302.  
  10303. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  10304.  
  10305.   this.static_tree  = static_tree;  /* static tree or NULL */
  10306.   this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
  10307.   this.extra_base   = extra_base;   /* base index for extra_bits */
  10308.   this.elems        = elems;        /* max number of elements in the tree */
  10309.   this.max_length   = max_length;   /* max bit length for the codes */
  10310.  
  10311.   // show if `static_tree` has data or dummy - needed for monomorphic objects
  10312.   this.has_stree    = static_tree && static_tree.length;
  10313. }
  10314.  
  10315.  
  10316. var static_l_desc;
  10317. var static_d_desc;
  10318. var static_bl_desc;
  10319.  
  10320.  
  10321. function TreeDesc(dyn_tree, stat_desc) {
  10322.   this.dyn_tree = dyn_tree;     /* the dynamic tree */
  10323.   this.max_code = 0;            /* largest code with non zero frequency */
  10324.   this.stat_desc = stat_desc;   /* the corresponding static tree */
  10325. }
  10326.  
  10327.  
  10328.  
  10329. function d_code(dist) {
  10330.   return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  10331. }
  10332.  
  10333.  
  10334. /* ===========================================================================
  10335.  * Output a short LSB first on the stream.
  10336.  * IN assertion: there is enough room in pendingBuf.
  10337.  */
  10338. function put_short(s, w) {
  10339. //    put_byte(s, (uch)((w) & 0xff));
  10340. //    put_byte(s, (uch)((ush)(w) >> 8));
  10341.   s.pending_buf[s.pending++] = (w) & 0xff;
  10342.   s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  10343. }
  10344.  
  10345.  
  10346. /* ===========================================================================
  10347.  * Send a value on a given number of bits.
  10348.  * IN assertion: length <= 16 and value fits in length bits.
  10349.  */
  10350. function send_bits(s, value, length) {
  10351.   if (s.bi_valid > (Buf_size - length)) {
  10352.     s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10353.     put_short(s, s.bi_buf);
  10354.     s.bi_buf = value >> (Buf_size - s.bi_valid);
  10355.     s.bi_valid += length - Buf_size;
  10356.   } else {
  10357.     s.bi_buf |= (value << s.bi_valid) & 0xffff;
  10358.     s.bi_valid += length;
  10359.   }
  10360. }
  10361.  
  10362.  
  10363. function send_code(s, c, tree) {
  10364.   send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  10365. }
  10366.  
  10367.  
  10368. /* ===========================================================================
  10369.  * Reverse the first len bits of a code, using straightforward code (a faster
  10370.  * method would use a table)
  10371.  * IN assertion: 1 <= len <= 15
  10372.  */
  10373. function bi_reverse(code, len) {
  10374.   var res = 0;
  10375.   do {
  10376.     res |= code & 1;
  10377.     code >>>= 1;
  10378.     res <<= 1;
  10379.   } while (--len > 0);
  10380.   return res >>> 1;
  10381. }
  10382.  
  10383.  
  10384. /* ===========================================================================
  10385.  * Flush the bit buffer, keeping at most 7 bits in it.
  10386.  */
  10387. function bi_flush(s) {
  10388.   if (s.bi_valid === 16) {
  10389.     put_short(s, s.bi_buf);
  10390.     s.bi_buf = 0;
  10391.     s.bi_valid = 0;
  10392.  
  10393.   } else if (s.bi_valid >= 8) {
  10394.     s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  10395.     s.bi_buf >>= 8;
  10396.     s.bi_valid -= 8;
  10397.   }
  10398. }
  10399.  
  10400.  
  10401. /* ===========================================================================
  10402.  * Compute the optimal bit lengths for a tree and update the total bit length
  10403.  * for the current block.
  10404.  * IN assertion: the fields freq and dad are set, heap[heap_max] and
  10405.  *    above are the tree nodes sorted by increasing frequency.
  10406.  * OUT assertions: the field len is set to the optimal bit length, the
  10407.  *     array bl_count contains the frequencies for each bit length.
  10408.  *     The length opt_len is updated; static_len is also updated if stree is
  10409.  *     not null.
  10410.  */
  10411. function gen_bitlen(s, desc)
  10412. //    deflate_state *s;
  10413. //    tree_desc *desc;    /* the tree descriptor */
  10414. {
  10415.   var tree            = desc.dyn_tree;
  10416.   var max_code        = desc.max_code;
  10417.   var stree           = desc.stat_desc.static_tree;
  10418.   var has_stree       = desc.stat_desc.has_stree;
  10419.   var extra           = desc.stat_desc.extra_bits;
  10420.   var base            = desc.stat_desc.extra_base;
  10421.   var max_length      = desc.stat_desc.max_length;
  10422.   var h;              /* heap index */
  10423.   var n, m;           /* iterate over the tree elements */
  10424.   var bits;           /* bit length */
  10425.   var xbits;          /* extra bits */
  10426.   var f;              /* frequency */
  10427.   var overflow = 0;   /* number of elements with bit length too large */
  10428.  
  10429.   for (bits = 0; bits <= MAX_BITS; bits++) {
  10430.     s.bl_count[bits] = 0;
  10431.   }
  10432.  
  10433.   /* In a first pass, compute the optimal bit lengths (which may
  10434.    * overflow in the case of the bit length tree).
  10435.    */
  10436.   tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  10437.  
  10438.   for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  10439.     n = s.heap[h];
  10440.     bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  10441.     if (bits > max_length) {
  10442.       bits = max_length;
  10443.       overflow++;
  10444.     }
  10445.     tree[n * 2 + 1]/*.Len*/ = bits;
  10446.     /* We overwrite tree[n].Dad which is no longer needed */
  10447.  
  10448.     if (n > max_code) { continue; } /* not a leaf node */
  10449.  
  10450.     s.bl_count[bits]++;
  10451.     xbits = 0;
  10452.     if (n >= base) {
  10453.       xbits = extra[n - base];
  10454.     }
  10455.     f = tree[n * 2]/*.Freq*/;
  10456.     s.opt_len += f * (bits + xbits);
  10457.     if (has_stree) {
  10458.       s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  10459.     }
  10460.   }
  10461.   if (overflow === 0) { return; }
  10462.  
  10463.   // Trace((stderr,"\nbit length overflow\n"));
  10464.   /* This happens for example on obj2 and pic of the Calgary corpus */
  10465.  
  10466.   /* Find the first bit length which could increase: */
  10467.   do {
  10468.     bits = max_length - 1;
  10469.     while (s.bl_count[bits] === 0) { bits--; }
  10470.     s.bl_count[bits]--;      /* move one leaf down the tree */
  10471.     s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  10472.     s.bl_count[max_length]--;
  10473.     /* The brother of the overflow item also moves one step up,
  10474.      * but this does not affect bl_count[max_length]
  10475.      */
  10476.     overflow -= 2;
  10477.   } while (overflow > 0);
  10478.  
  10479.   /* Now recompute all bit lengths, scanning in increasing frequency.
  10480.    * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  10481.    * lengths instead of fixing only the wrong ones. This idea is taken
  10482.    * from 'ar' written by Haruhiko Okumura.)
  10483.    */
  10484.   for (bits = max_length; bits !== 0; bits--) {
  10485.     n = s.bl_count[bits];
  10486.     while (n !== 0) {
  10487.       m = s.heap[--h];
  10488.       if (m > max_code) { continue; }
  10489.       if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  10490.         // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  10491.         s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  10492.         tree[m * 2 + 1]/*.Len*/ = bits;
  10493.       }
  10494.       n--;
  10495.     }
  10496.   }
  10497. }
  10498.  
  10499.  
  10500. /* ===========================================================================
  10501.  * Generate the codes for a given tree and bit counts (which need not be
  10502.  * optimal).
  10503.  * IN assertion: the array bl_count contains the bit length statistics for
  10504.  * the given tree and the field len is set for all tree elements.
  10505.  * OUT assertion: the field code is set for all tree elements of non
  10506.  *     zero code length.
  10507.  */
  10508. function gen_codes(tree, max_code, bl_count)
  10509. //    ct_data *tree;             /* the tree to decorate */
  10510. //    int max_code;              /* largest code with non zero frequency */
  10511. //    ushf *bl_count;            /* number of codes at each bit length */
  10512. {
  10513.   var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  10514.   var code = 0;              /* running code value */
  10515.   var bits;                  /* bit index */
  10516.   var n;                     /* code index */
  10517.  
  10518.   /* The distribution counts are first used to generate the code values
  10519.    * without bit reversal.
  10520.    */
  10521.   for (bits = 1; bits <= MAX_BITS; bits++) {
  10522.     next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  10523.   }
  10524.   /* Check that the bit counts in bl_count are consistent. The last code
  10525.    * must be all ones.
  10526.    */
  10527.   //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  10528.   //        "inconsistent bit counts");
  10529.   //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  10530.  
  10531.   for (n = 0;  n <= max_code; n++) {
  10532.     var len = tree[n * 2 + 1]/*.Len*/;
  10533.     if (len === 0) { continue; }
  10534.     /* Now reverse the bits */
  10535.     tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  10536.  
  10537.     //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  10538.     //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  10539.   }
  10540. }
  10541.  
  10542.  
  10543. /* ===========================================================================
  10544.  * Initialize the various 'constant' tables.
  10545.  */
  10546. function tr_static_init() {
  10547.   var n;        /* iterates over tree elements */
  10548.   var bits;     /* bit counter */
  10549.   var length;   /* length value */
  10550.   var code;     /* code value */
  10551.   var dist;     /* distance index */
  10552.   var bl_count = new Array(MAX_BITS + 1);
  10553.   /* number of codes at each bit length for an optimal tree */
  10554.  
  10555.   // do check in _tr_init()
  10556.   //if (static_init_done) return;
  10557.  
  10558.   /* For some embedded targets, global variables are not initialized: */
  10559. /*#ifdef NO_INIT_GLOBAL_POINTERS
  10560.   static_l_desc.static_tree = static_ltree;
  10561.   static_l_desc.extra_bits = extra_lbits;
  10562.   static_d_desc.static_tree = static_dtree;
  10563.   static_d_desc.extra_bits = extra_dbits;
  10564.   static_bl_desc.extra_bits = extra_blbits;
  10565. #endif*/
  10566.  
  10567.   /* Initialize the mapping length (0..255) -> length code (0..28) */
  10568.   length = 0;
  10569.   for (code = 0; code < LENGTH_CODES - 1; code++) {
  10570.     base_length[code] = length;
  10571.     for (n = 0; n < (1 << extra_lbits[code]); n++) {
  10572.       _length_code[length++] = code;
  10573.     }
  10574.   }
  10575.   //Assert (length == 256, "tr_static_init: length != 256");
  10576.   /* Note that the length 255 (match length 258) can be represented
  10577.    * in two different ways: code 284 + 5 bits or code 285, so we
  10578.    * overwrite length_code[255] to use the best encoding:
  10579.    */
  10580.   _length_code[length - 1] = code;
  10581.  
  10582.   /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  10583.   dist = 0;
  10584.   for (code = 0; code < 16; code++) {
  10585.     base_dist[code] = dist;
  10586.     for (n = 0; n < (1 << extra_dbits[code]); n++) {
  10587.       _dist_code[dist++] = code;
  10588.     }
  10589.   }
  10590.   //Assert (dist == 256, "tr_static_init: dist != 256");
  10591.   dist >>= 7; /* from now on, all distances are divided by 128 */
  10592.   for (; code < D_CODES; code++) {
  10593.     base_dist[code] = dist << 7;
  10594.     for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  10595.       _dist_code[256 + dist++] = code;
  10596.     }
  10597.   }
  10598.   //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  10599.  
  10600.   /* Construct the codes of the static literal tree */
  10601.   for (bits = 0; bits <= MAX_BITS; bits++) {
  10602.     bl_count[bits] = 0;
  10603.   }
  10604.  
  10605.   n = 0;
  10606.   while (n <= 143) {
  10607.     static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10608.     n++;
  10609.     bl_count[8]++;
  10610.   }
  10611.   while (n <= 255) {
  10612.     static_ltree[n * 2 + 1]/*.Len*/ = 9;
  10613.     n++;
  10614.     bl_count[9]++;
  10615.   }
  10616.   while (n <= 279) {
  10617.     static_ltree[n * 2 + 1]/*.Len*/ = 7;
  10618.     n++;
  10619.     bl_count[7]++;
  10620.   }
  10621.   while (n <= 287) {
  10622.     static_ltree[n * 2 + 1]/*.Len*/ = 8;
  10623.     n++;
  10624.     bl_count[8]++;
  10625.   }
  10626.   /* Codes 286 and 287 do not exist, but we must include them in the
  10627.    * tree construction to get a canonical Huffman tree (longest code
  10628.    * all ones)
  10629.    */
  10630.   gen_codes(static_ltree, L_CODES + 1, bl_count);
  10631.  
  10632.   /* The static distance tree is trivial: */
  10633.   for (n = 0; n < D_CODES; n++) {
  10634.     static_dtree[n * 2 + 1]/*.Len*/ = 5;
  10635.     static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  10636.   }
  10637.  
  10638.   // Now data ready and we can init static trees
  10639.   static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  10640.   static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
  10641.   static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
  10642.  
  10643.   //static_init_done = true;
  10644. }
  10645.  
  10646.  
  10647. /* ===========================================================================
  10648.  * Initialize a new block.
  10649.  */
  10650. function init_block(s) {
  10651.   var n; /* iterates over tree elements */
  10652.  
  10653.   /* Initialize the trees. */
  10654.   for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  10655.   for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  10656.   for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  10657.  
  10658.   s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  10659.   s.opt_len = s.static_len = 0;
  10660.   s.last_lit = s.matches = 0;
  10661. }
  10662.  
  10663.  
  10664. /* ===========================================================================
  10665.  * Flush the bit buffer and align the output on a byte boundary
  10666.  */
  10667. function bi_windup(s)
  10668. {
  10669.   if (s.bi_valid > 8) {
  10670.     put_short(s, s.bi_buf);
  10671.   } else if (s.bi_valid > 0) {
  10672.     //put_byte(s, (Byte)s->bi_buf);
  10673.     s.pending_buf[s.pending++] = s.bi_buf;
  10674.   }
  10675.   s.bi_buf = 0;
  10676.   s.bi_valid = 0;
  10677. }
  10678.  
  10679. /* ===========================================================================
  10680.  * Copy a stored block, storing first the length and its
  10681.  * one's complement if requested.
  10682.  */
  10683. function copy_block(s, buf, len, header)
  10684. //DeflateState *s;
  10685. //charf    *buf;    /* the input data */
  10686. //unsigned len;     /* its length */
  10687. //int      header;  /* true if block header must be written */
  10688. {
  10689.   bi_windup(s);        /* align on byte boundary */
  10690.  
  10691.   if (header) {
  10692.     put_short(s, len);
  10693.     put_short(s, ~len);
  10694.   }
  10695. //  while (len--) {
  10696. //    put_byte(s, *buf++);
  10697. //  }
  10698.   utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  10699.   s.pending += len;
  10700. }
  10701.  
  10702. /* ===========================================================================
  10703.  * Compares to subtrees, using the tree depth as tie breaker when
  10704.  * the subtrees have equal frequency. This minimizes the worst case length.
  10705.  */
  10706. function smaller(tree, n, m, depth) {
  10707.   var _n2 = n * 2;
  10708.   var _m2 = m * 2;
  10709.   return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  10710.          (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  10711. }
  10712.  
  10713. /* ===========================================================================
  10714.  * Restore the heap property by moving down the tree starting at node k,
  10715.  * exchanging a node with the smallest of its two sons if necessary, stopping
  10716.  * when the heap property is re-established (each father smaller than its
  10717.  * two sons).
  10718.  */
  10719. function pqdownheap(s, tree, k)
  10720. //    deflate_state *s;
  10721. //    ct_data *tree;  /* the tree to restore */
  10722. //    int k;               /* node to move down */
  10723. {
  10724.   var v = s.heap[k];
  10725.   var j = k << 1;  /* left son of k */
  10726.   while (j <= s.heap_len) {
  10727.     /* Set j to the smallest of the two sons: */
  10728.     if (j < s.heap_len &&
  10729.       smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  10730.       j++;
  10731.     }
  10732.     /* Exit if v is smaller than both sons */
  10733.     if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  10734.  
  10735.     /* Exchange v with the smallest son */
  10736.     s.heap[k] = s.heap[j];
  10737.     k = j;
  10738.  
  10739.     /* And continue down the tree, setting j to the left son of k */
  10740.     j <<= 1;
  10741.   }
  10742.   s.heap[k] = v;
  10743. }
  10744.  
  10745.  
  10746. // inlined manually
  10747. // var SMALLEST = 1;
  10748.  
  10749. /* ===========================================================================
  10750.  * Send the block data compressed using the given Huffman trees
  10751.  */
  10752. function compress_block(s, ltree, dtree)
  10753. //    deflate_state *s;
  10754. //    const ct_data *ltree; /* literal tree */
  10755. //    const ct_data *dtree; /* distance tree */
  10756. {
  10757.   var dist;           /* distance of matched string */
  10758.   var lc;             /* match length or unmatched char (if dist == 0) */
  10759.   var lx = 0;         /* running index in l_buf */
  10760.   var code;           /* the code to send */
  10761.   var extra;          /* number of extra bits to send */
  10762.  
  10763.   if (s.last_lit !== 0) {
  10764.     do {
  10765.       dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  10766.       lc = s.pending_buf[s.l_buf + lx];
  10767.       lx++;
  10768.  
  10769.       if (dist === 0) {
  10770.         send_code(s, lc, ltree); /* send a literal byte */
  10771.         //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  10772.       } else {
  10773.         /* Here, lc is the match length - MIN_MATCH */
  10774.         code = _length_code[lc];
  10775.         send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  10776.         extra = extra_lbits[code];
  10777.         if (extra !== 0) {
  10778.           lc -= base_length[code];
  10779.           send_bits(s, lc, extra);       /* send the extra length bits */
  10780.         }
  10781.         dist--; /* dist is now the match distance - 1 */
  10782.         code = d_code(dist);
  10783.         //Assert (code < D_CODES, "bad d_code");
  10784.  
  10785.         send_code(s, code, dtree);       /* send the distance code */
  10786.         extra = extra_dbits[code];
  10787.         if (extra !== 0) {
  10788.           dist -= base_dist[code];
  10789.           send_bits(s, dist, extra);   /* send the extra distance bits */
  10790.         }
  10791.       } /* literal or match pair ? */
  10792.  
  10793.       /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  10794.       //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  10795.       //       "pendingBuf overflow");
  10796.  
  10797.     } while (lx < s.last_lit);
  10798.   }
  10799.  
  10800.   send_code(s, END_BLOCK, ltree);
  10801. }
  10802.  
  10803.  
  10804. /* ===========================================================================
  10805.  * Construct one Huffman tree and assigns the code bit strings and lengths.
  10806.  * Update the total bit length for the current block.
  10807.  * IN assertion: the field freq is set for all tree elements.
  10808.  * OUT assertions: the fields len and code are set to the optimal bit length
  10809.  *     and corresponding code. The length opt_len is updated; static_len is
  10810.  *     also updated if stree is not null. The field max_code is set.
  10811.  */
  10812. function build_tree(s, desc)
  10813. //    deflate_state *s;
  10814. //    tree_desc *desc; /* the tree descriptor */
  10815. {
  10816.   var tree     = desc.dyn_tree;
  10817.   var stree    = desc.stat_desc.static_tree;
  10818.   var has_stree = desc.stat_desc.has_stree;
  10819.   var elems    = desc.stat_desc.elems;
  10820.   var n, m;          /* iterate over heap elements */
  10821.   var max_code = -1; /* largest code with non zero frequency */
  10822.   var node;          /* new node being created */
  10823.  
  10824.   /* Construct the initial heap, with least frequent element in
  10825.    * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  10826.    * heap[0] is not used.
  10827.    */
  10828.   s.heap_len = 0;
  10829.   s.heap_max = HEAP_SIZE;
  10830.  
  10831.   for (n = 0; n < elems; n++) {
  10832.     if (tree[n * 2]/*.Freq*/ !== 0) {
  10833.       s.heap[++s.heap_len] = max_code = n;
  10834.       s.depth[n] = 0;
  10835.  
  10836.     } else {
  10837.       tree[n * 2 + 1]/*.Len*/ = 0;
  10838.     }
  10839.   }
  10840.  
  10841.   /* The pkzip format requires that at least one distance code exists,
  10842.    * and that at least one bit should be sent even if there is only one
  10843.    * possible code. So to avoid special checks later on we force at least
  10844.    * two codes of non zero frequency.
  10845.    */
  10846.   while (s.heap_len < 2) {
  10847.     node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  10848.     tree[node * 2]/*.Freq*/ = 1;
  10849.     s.depth[node] = 0;
  10850.     s.opt_len--;
  10851.  
  10852.     if (has_stree) {
  10853.       s.static_len -= stree[node * 2 + 1]/*.Len*/;
  10854.     }
  10855.     /* node is 0 or 1 so it does not have extra bits */
  10856.   }
  10857.   desc.max_code = max_code;
  10858.  
  10859.   /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  10860.    * establish sub-heaps of increasing lengths:
  10861.    */
  10862.   for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  10863.  
  10864.   /* Construct the Huffman tree by repeatedly combining the least two
  10865.    * frequent nodes.
  10866.    */
  10867.   node = elems;              /* next internal node of the tree */
  10868.   do {
  10869.     //pqremove(s, tree, n);  /* n = node of least frequency */
  10870.     /*** pqremove ***/
  10871.     n = s.heap[1/*SMALLEST*/];
  10872.     s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  10873.     pqdownheap(s, tree, 1/*SMALLEST*/);
  10874.     /***/
  10875.  
  10876.     m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  10877.  
  10878.     s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  10879.     s.heap[--s.heap_max] = m;
  10880.  
  10881.     /* Create a new node father of n and m */
  10882.     tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  10883.     s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  10884.     tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  10885.  
  10886.     /* and insert the new node in the heap */
  10887.     s.heap[1/*SMALLEST*/] = node++;
  10888.     pqdownheap(s, tree, 1/*SMALLEST*/);
  10889.  
  10890.   } while (s.heap_len >= 2);
  10891.  
  10892.   s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  10893.  
  10894.   /* At this point, the fields freq and dad are set. We can now
  10895.    * generate the bit lengths.
  10896.    */
  10897.   gen_bitlen(s, desc);
  10898.  
  10899.   /* The field len is now set, we can generate the bit codes */
  10900.   gen_codes(tree, max_code, s.bl_count);
  10901. }
  10902.  
  10903.  
  10904. /* ===========================================================================
  10905.  * Scan a literal or distance tree to determine the frequencies of the codes
  10906.  * in the bit length tree.
  10907.  */
  10908. function scan_tree(s, tree, max_code)
  10909. //    deflate_state *s;
  10910. //    ct_data *tree;   /* the tree to be scanned */
  10911. //    int max_code;    /* and its largest code of non zero frequency */
  10912. {
  10913.   var n;                     /* iterates over all tree elements */
  10914.   var prevlen = -1;          /* last emitted length */
  10915.   var curlen;                /* length of current code */
  10916.  
  10917.   var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10918.  
  10919.   var count = 0;             /* repeat count of the current code */
  10920.   var max_count = 7;         /* max repeat count */
  10921.   var min_count = 4;         /* min repeat count */
  10922.  
  10923.   if (nextlen === 0) {
  10924.     max_count = 138;
  10925.     min_count = 3;
  10926.   }
  10927.   tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  10928.  
  10929.   for (n = 0; n <= max_code; n++) {
  10930.     curlen = nextlen;
  10931.     nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10932.  
  10933.     if (++count < max_count && curlen === nextlen) {
  10934.       continue;
  10935.  
  10936.     } else if (count < min_count) {
  10937.       s.bl_tree[curlen * 2]/*.Freq*/ += count;
  10938.  
  10939.     } else if (curlen !== 0) {
  10940.  
  10941.       if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  10942.       s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  10943.  
  10944.     } else if (count <= 10) {
  10945.       s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  10946.  
  10947.     } else {
  10948.       s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  10949.     }
  10950.  
  10951.     count = 0;
  10952.     prevlen = curlen;
  10953.  
  10954.     if (nextlen === 0) {
  10955.       max_count = 138;
  10956.       min_count = 3;
  10957.  
  10958.     } else if (curlen === nextlen) {
  10959.       max_count = 6;
  10960.       min_count = 3;
  10961.  
  10962.     } else {
  10963.       max_count = 7;
  10964.       min_count = 4;
  10965.     }
  10966.   }
  10967. }
  10968.  
  10969.  
  10970. /* ===========================================================================
  10971.  * Send a literal or distance tree in compressed form, using the codes in
  10972.  * bl_tree.
  10973.  */
  10974. function send_tree(s, tree, max_code)
  10975. //    deflate_state *s;
  10976. //    ct_data *tree; /* the tree to be scanned */
  10977. //    int max_code;       /* and its largest code of non zero frequency */
  10978. {
  10979.   var n;                     /* iterates over all tree elements */
  10980.   var prevlen = -1;          /* last emitted length */
  10981.   var curlen;                /* length of current code */
  10982.  
  10983.   var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  10984.  
  10985.   var count = 0;             /* repeat count of the current code */
  10986.   var max_count = 7;         /* max repeat count */
  10987.   var min_count = 4;         /* min repeat count */
  10988.  
  10989.   /* tree[max_code+1].Len = -1; */  /* guard already set */
  10990.   if (nextlen === 0) {
  10991.     max_count = 138;
  10992.     min_count = 3;
  10993.   }
  10994.  
  10995.   for (n = 0; n <= max_code; n++) {
  10996.     curlen = nextlen;
  10997.     nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  10998.  
  10999.     if (++count < max_count && curlen === nextlen) {
  11000.       continue;
  11001.  
  11002.     } else if (count < min_count) {
  11003.       do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  11004.  
  11005.     } else if (curlen !== 0) {
  11006.       if (curlen !== prevlen) {
  11007.         send_code(s, curlen, s.bl_tree);
  11008.         count--;
  11009.       }
  11010.       //Assert(count >= 3 && count <= 6, " 3_6?");
  11011.       send_code(s, REP_3_6, s.bl_tree);
  11012.       send_bits(s, count - 3, 2);
  11013.  
  11014.     } else if (count <= 10) {
  11015.       send_code(s, REPZ_3_10, s.bl_tree);
  11016.       send_bits(s, count - 3, 3);
  11017.  
  11018.     } else {
  11019.       send_code(s, REPZ_11_138, s.bl_tree);
  11020.       send_bits(s, count - 11, 7);
  11021.     }
  11022.  
  11023.     count = 0;
  11024.     prevlen = curlen;
  11025.     if (nextlen === 0) {
  11026.       max_count = 138;
  11027.       min_count = 3;
  11028.  
  11029.     } else if (curlen === nextlen) {
  11030.       max_count = 6;
  11031.       min_count = 3;
  11032.  
  11033.     } else {
  11034.       max_count = 7;
  11035.       min_count = 4;
  11036.     }
  11037.   }
  11038. }
  11039.  
  11040.  
  11041. /* ===========================================================================
  11042.  * Construct the Huffman tree for the bit lengths and return the index in
  11043.  * bl_order of the last bit length code to send.
  11044.  */
  11045. function build_bl_tree(s) {
  11046.   var max_blindex;  /* index of last bit length code of non zero freq */
  11047.  
  11048.   /* Determine the bit length frequencies for literal and distance trees */
  11049.   scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  11050.   scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  11051.  
  11052.   /* Build the bit length tree: */
  11053.   build_tree(s, s.bl_desc);
  11054.   /* opt_len now includes the length of the tree representations, except
  11055.    * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  11056.    */
  11057.  
  11058.   /* Determine the number of bit length codes to send. The pkzip format
  11059.    * requires that at least 4 bit length codes be sent. (appnote.txt says
  11060.    * 3 but the actual value used is 4.)
  11061.    */
  11062.   for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  11063.     if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  11064.       break;
  11065.     }
  11066.   }
  11067.   /* Update opt_len to include the bit length tree and counts */
  11068.   s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  11069.   //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  11070.   //        s->opt_len, s->static_len));
  11071.  
  11072.   return max_blindex;
  11073. }
  11074.  
  11075.  
  11076. /* ===========================================================================
  11077.  * Send the header for a block using dynamic Huffman trees: the counts, the
  11078.  * lengths of the bit length codes, the literal tree and the distance tree.
  11079.  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  11080.  */
  11081. function send_all_trees(s, lcodes, dcodes, blcodes)
  11082. //    deflate_state *s;
  11083. //    int lcodes, dcodes, blcodes; /* number of codes for each tree */
  11084. {
  11085.   var rank;                    /* index in bl_order */
  11086.  
  11087.   //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  11088.   //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  11089.   //        "too many codes");
  11090.   //Tracev((stderr, "\nbl counts: "));
  11091.   send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  11092.   send_bits(s, dcodes - 1,   5);
  11093.   send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
  11094.   for (rank = 0; rank < blcodes; rank++) {
  11095.     //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  11096.     send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  11097.   }
  11098.   //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  11099.  
  11100.   send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  11101.   //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  11102.  
  11103.   send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  11104.   //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  11105. }
  11106.  
  11107.  
  11108. /* ===========================================================================
  11109.  * Check if the data type is TEXT or BINARY, using the following algorithm:
  11110.  * - TEXT if the two conditions below are satisfied:
  11111.  *    a) There are no non-portable control characters belonging to the
  11112.  *       "black list" (0..6, 14..25, 28..31).
  11113.  *    b) There is at least one printable character belonging to the
  11114.  *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  11115.  * - BINARY otherwise.
  11116.  * - The following partially-portable control characters form a
  11117.  *   "gray list" that is ignored in this detection algorithm:
  11118.  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  11119.  * IN assertion: the fields Freq of dyn_ltree are set.
  11120.  */
  11121. function detect_data_type(s) {
  11122.   /* black_mask is the bit mask of black-listed bytes
  11123.    * set bits 0..6, 14..25, and 28..31
  11124.    * 0xf3ffc07f = binary 11110011111111111100000001111111
  11125.    */
  11126.   var black_mask = 0xf3ffc07f;
  11127.   var n;
  11128.  
  11129.   /* Check for non-textual ("black-listed") bytes. */
  11130.   for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  11131.     if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  11132.       return Z_BINARY;
  11133.     }
  11134.   }
  11135.  
  11136.   /* Check for textual ("white-listed") bytes. */
  11137.   if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  11138.       s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  11139.     return Z_TEXT;
  11140.   }
  11141.   for (n = 32; n < LITERALS; n++) {
  11142.     if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  11143.       return Z_TEXT;
  11144.     }
  11145.   }
  11146.  
  11147.   /* There are no "black-listed" or "white-listed" bytes:
  11148.    * this stream either is empty or has tolerated ("gray-listed") bytes only.
  11149.    */
  11150.   return Z_BINARY;
  11151. }
  11152.  
  11153.  
  11154. var static_init_done = false;
  11155.  
  11156. /* ===========================================================================
  11157.  * Initialize the tree data structures for a new zlib stream.
  11158.  */
  11159. function _tr_init(s)
  11160. {
  11161.  
  11162.   if (!static_init_done) {
  11163.     tr_static_init();
  11164.     static_init_done = true;
  11165.   }
  11166.  
  11167.   s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
  11168.   s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
  11169.   s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  11170.  
  11171.   s.bi_buf = 0;
  11172.   s.bi_valid = 0;
  11173.  
  11174.   /* Initialize the first block of the first file: */
  11175.   init_block(s);
  11176. }
  11177.  
  11178.  
  11179. /* ===========================================================================
  11180.  * Send a stored block
  11181.  */
  11182. function _tr_stored_block(s, buf, stored_len, last)
  11183. //DeflateState *s;
  11184. //charf *buf;       /* input block */
  11185. //ulg stored_len;   /* length of input block */
  11186. //int last;         /* one if this is the last block for a file */
  11187. {
  11188.   send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
  11189.   copy_block(s, buf, stored_len, true); /* with header */
  11190. }
  11191.  
  11192.  
  11193. /* ===========================================================================
  11194.  * Send one empty static block to give enough lookahead for inflate.
  11195.  * This takes 10 bits, of which 7 may remain in the bit buffer.
  11196.  */
  11197. function _tr_align(s) {
  11198.   send_bits(s, STATIC_TREES << 1, 3);
  11199.   send_code(s, END_BLOCK, static_ltree);
  11200.   bi_flush(s);
  11201. }
  11202.  
  11203.  
  11204. /* ===========================================================================
  11205.  * Determine the best encoding for the current block: dynamic trees, static
  11206.  * trees or store, and output the encoded block to the zip file.
  11207.  */
  11208. function _tr_flush_block(s, buf, stored_len, last)
  11209. //DeflateState *s;
  11210. //charf *buf;       /* input block, or NULL if too old */
  11211. //ulg stored_len;   /* length of input block */
  11212. //int last;         /* one if this is the last block for a file */
  11213. {
  11214.   var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
  11215.   var max_blindex = 0;        /* index of last bit length code of non zero freq */
  11216.  
  11217.   /* Build the Huffman trees unless a stored block is forced */
  11218.   if (s.level > 0) {
  11219.  
  11220.     /* Check if the file is binary or text */
  11221.     if (s.strm.data_type === Z_UNKNOWN) {
  11222.       s.strm.data_type = detect_data_type(s);
  11223.     }
  11224.  
  11225.     /* Construct the literal and distance trees */
  11226.     build_tree(s, s.l_desc);
  11227.     // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  11228.     //        s->static_len));
  11229.  
  11230.     build_tree(s, s.d_desc);
  11231.     // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  11232.     //        s->static_len));
  11233.     /* At this point, opt_len and static_len are the total bit lengths of
  11234.      * the compressed block data, excluding the tree representations.
  11235.      */
  11236.  
  11237.     /* Build the bit length tree for the above two trees, and get the index
  11238.      * in bl_order of the last bit length code to send.
  11239.      */
  11240.     max_blindex = build_bl_tree(s);
  11241.  
  11242.     /* Determine the best encoding. Compute the block lengths in bytes. */
  11243.     opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  11244.     static_lenb = (s.static_len + 3 + 7) >>> 3;
  11245.  
  11246.     // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  11247.     //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  11248.     //        s->last_lit));
  11249.  
  11250.     if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  11251.  
  11252.   } else {
  11253.     // Assert(buf != (char*)0, "lost buf");
  11254.     opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  11255.   }
  11256.  
  11257.   if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  11258.     /* 4: two words for the lengths */
  11259.  
  11260.     /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  11261.      * Otherwise we can't have processed more than WSIZE input bytes since
  11262.      * the last block flush, because compression would have been
  11263.      * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  11264.      * transform a block into a stored block.
  11265.      */
  11266.     _tr_stored_block(s, buf, stored_len, last);
  11267.  
  11268.   } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  11269.  
  11270.     send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  11271.     compress_block(s, static_ltree, static_dtree);
  11272.  
  11273.   } else {
  11274.     send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  11275.     send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  11276.     compress_block(s, s.dyn_ltree, s.dyn_dtree);
  11277.   }
  11278.   // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  11279.   /* The above check is made mod 2^32, for files larger than 512 MB
  11280.    * and uLong implemented on 32 bits.
  11281.    */
  11282.   init_block(s);
  11283.  
  11284.   if (last) {
  11285.     bi_windup(s);
  11286.   }
  11287.   // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  11288.   //       s->compressed_len-7*last));
  11289. }
  11290.  
  11291. /* ===========================================================================
  11292.  * Save the match info and tally the frequency counts. Return true if
  11293.  * the current block must be flushed.
  11294.  */
  11295. function _tr_tally(s, dist, lc)
  11296. //    deflate_state *s;
  11297. //    unsigned dist;  /* distance of matched string */
  11298. //    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
  11299. {
  11300.   //var out_length, in_length, dcode;
  11301.  
  11302.   s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
  11303.   s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  11304.  
  11305.   s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  11306.   s.last_lit++;
  11307.  
  11308.   if (dist === 0) {
  11309.     /* lc is the unmatched char */
  11310.     s.dyn_ltree[lc * 2]/*.Freq*/++;
  11311.   } else {
  11312.     s.matches++;
  11313.     /* Here, lc is the match length - MIN_MATCH */
  11314.     dist--;             /* dist = match distance - 1 */
  11315.     //Assert((ush)dist < (ush)MAX_DIST(s) &&
  11316.     //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  11317.     //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
  11318.  
  11319.     s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  11320.     s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  11321.   }
  11322.  
  11323. // (!) This block is disabled in zlib defailts,
  11324. // don't enable it for binary compatibility
  11325.  
  11326. //#ifdef TRUNCATE_BLOCK
  11327. //  /* Try to guess if it is profitable to stop the current block here */
  11328. //  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  11329. //    /* Compute an upper bound for the compressed length */
  11330. //    out_length = s.last_lit*8;
  11331. //    in_length = s.strstart - s.block_start;
  11332. //
  11333. //    for (dcode = 0; dcode < D_CODES; dcode++) {
  11334. //      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  11335. //    }
  11336. //    out_length >>>= 3;
  11337. //    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  11338. //    //       s->last_lit, in_length, out_length,
  11339. //    //       100L - out_length*100L/in_length));
  11340. //    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  11341. //      return true;
  11342. //    }
  11343. //  }
  11344. //#endif
  11345.  
  11346.   return (s.last_lit === s.lit_bufsize - 1);
  11347.   /* We avoid equality with lit_bufsize because of wraparound at 64K
  11348.    * on 16 bit machines and because stored blocks are restricted to
  11349.    * 64K-1 bytes.
  11350.    */
  11351. }
  11352.  
  11353. exports._tr_init  = _tr_init;
  11354. exports._tr_stored_block = _tr_stored_block;
  11355. exports._tr_flush_block  = _tr_flush_block;
  11356. exports._tr_tally = _tr_tally;
  11357. exports._tr_align = _tr_align;
  11358.  
  11359. },{"../utils/common":62}],74:[function(require,module,exports){
  11360. 'use strict';
  11361.  
  11362.  
  11363. function ZStream() {
  11364.   /* next input byte */
  11365.   this.input = null; // JS specific, because we have no pointers
  11366.   this.next_in = 0;
  11367.   /* number of bytes available at input */
  11368.   this.avail_in = 0;
  11369.   /* total number of input bytes read so far */
  11370.   this.total_in = 0;
  11371.   /* next output byte should be put there */
  11372.   this.output = null; // JS specific, because we have no pointers
  11373.   this.next_out = 0;
  11374.   /* remaining free space at output */
  11375.   this.avail_out = 0;
  11376.   /* total number of bytes output so far */
  11377.   this.total_out = 0;
  11378.   /* last error message, NULL if no error */
  11379.   this.msg = ''/*Z_NULL*/;
  11380.   /* not visible by applications */
  11381.   this.state = null;
  11382.   /* best guess about the data type: binary or text */
  11383.   this.data_type = 2/*Z_UNKNOWN*/;
  11384.   /* adler32 value of the uncompressed data */
  11385.   this.adler = 0;
  11386. }
  11387.  
  11388. module.exports = ZStream;
  11389.  
  11390. },{}]},{},[10])(10)
  11391. });
Add Comment
Please, Sign In to add comment